Automatic HTTP Certificates with Let's Encrypt

From Tech-Wiki
Revision as of 20:53, 16 February 2025 by Fabricio.Lima (Talk | contribs)

Jump to: navigation, search

Back to Windows Server


In order to use this, you'll need CloudFlare DNS (which is Free). If you rather using HTML validation instead of DNS, you can use this.

$Domain = "www.domain.com"
$Email = "helpdesk@domain.com"
$Token = "xxxxxxxxxxxxxxxx"
$pfxfile = "c:\installs\$Domain.pfx"
$password = ConvertTo-SecureString -String "abc123" -Force -AsPlainText

try{
    Import-Module -Name Posh-ACME
    Import-Module -Name Posh-ACME.Deploy
    #Identify as existing user
    Set-PAAccount -Contact $Email
    Set-PAOrder $Domain
} catch{
    # New installation - Run once
    Install-PackageProvider -Name NuGet -Force
    Install-Module -Name Posh-ACME  -Force
    Install-Module -Name Posh-ACME.Deploy -Force
    Set-PAServer LE_PROD # (or LE_STAGE)
    # Identify and register
    New-PAAccount -AcceptTOS -Contact $Email
    # Request a new certificate
    New-PAOrder $Domain
    return "Installed, run this again"
}

$pArgs = @{
    CFToken = (ConvertTo-SecureString -String $Token -AsPlainText -Force)
}
$cert = New-PACertificate $Domain -DnsPlugin Cloudflare -PluginArgs $pArgs 

# renew an existing certificate and bind it into IIS
if ($cert = Submit-Renewal) {
	#Import Certificate into Windows
	Import-PfxCertificate -Password $cert.PfxPass -FilePath $cert.PfxFile -CertStoreLocation Cert:\LocalMachine\My -Exportable

    # Export certificate as PFX
    Export-PfxCertificate -Cert ("Cert:\LocalMachine\My\" + $cert.Thumbprint) -FilePath $pfxfile -Password $password

	# Bind new cert into IIS
    Get-WebBinding | Where-Object { $_.protocol -eq "https"} | ForEach-Object {
       $_.AddSslCertificate($cert.thumbprint, 'My')
    }
}