Automatic HTTP Certificates with Let's Encrypt

From Tech-Wiki
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.

Then you need to run this monthly via Task Scheduler with elevated privileges.

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

# For SANs use: 
# $Domains = @("example.com", "www.example.com", "sub.example.com")
# Set-PAOrder -MainDomain $Domains[0] -AltNames $Domains[1..($Domains.Count - 1)]
# $cert = New-PACertificate -Domain $Domains -DnsPlugin Cloudflare -PluginArgs $pArgs

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')
    }
}