Recently I had to sort out how to create a HTTPS binding for a site hosted on IIS version 7.5 on a Windows 2008R2 Server.  To do this, I had to have the Certificate installed already and the Website already up and running.  Courtesy of the content in these links at the bottom of the post, I created the following script to find the certificate on the machine, then check for the binding, then create the binding if it didn’t already exist.  Obviously magic strings in the script can/should be replaced with parameters if used in a script or reusable function.

$certificateCommonName = "The Certificate's Common Name"
$certificate = (Get-ChildItem Cert:\LocalMachine\My | where-object { $_.Subject -like "*CN=$certificateCommonName*" } | Select-Object -First 1)
if(!$certificate){
  Write-Output "Unable to find certificate with Common Name containing $certificateCommonName"
  exit 1
}

$hostHeader = "The Host Header for your Site"
# Can use -HostHeader or -Name for the Website name
$httpsBinding = Get-WebBinding -HostHeader $hostHeader -Port 443 -Name $hostHeader -Protocol "https"
if(!$httpsBinding){
  Write-Output "The https binding on 443 for $hostHeader does not exist, creating it now."

  New-WebBinding -HostHeader $hostHeader -Port 443 -Name $hostHeader -Protocol "https"

  $httpsBinding = Get-WebBinding -HostHeader $hostHeader -Port 443 -Name $hostHeader -Protocol "https"
  $httpsBinding.AddSslCertificate($certificate.GetCertHashString(), "my")

  $certificateSubject = $certificate.Subject
  Write-Output "The https binding on 443 for $hostHeader has been created and uses the certificate with subject $certificateSubject"
}

Thanks to the following links for helping me figure this out:

 

Leave a comment

Your email address will not be published. Required fields are marked *