Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
Updating multiple site bindings in IIS with new SSL-certificate
# Example of usage:
# Update-Certificates -domainNameMatchPattern "mycompany.com" -variableNameForCertificateToUse "CurrentMyCompanyDotComCertificate"
function Write-Info ($message) {
Write-Host "Info:" $message
}
function AssignCertificate([string] $friendlyName, [string] $hostName, [int] $port) {
$matchingCertificates = (Get-ChildItem cert:\localmachine\my) | Where-Object {$_.FriendlyName -eq $friendlyName}
$matchCount = ($matchingCertificates | Measure-Object).Count
if ($matchCount -ne 1) {
Write-Info ("Found " + $matchCount + " certificates matching friendly name " + $friendlyName + " (Expecting 1 match).")
Write-Info "The following certificates are installed: "
(Get-ChildItem cert:\localmachine\my) | Format-Table -Property Thumbprint, FriendlyName, Subject
}
else {
$certificate = $matchingCertificates[0]
$existingBinding = Get-WebBinding | Where-Object { $_.bindingInformation -match ":$($port):$($hostName)" }
if ($existingBinding) {
if ($existingBinding.certificateHash -ne $certificate.Thumbprint) {
Write-Info "Found existing binding with different thumbprint $($certificate.Thumbprint), will remove old certificate binding"
"netsh http delete sslcert hostnameport=$($hostName):$($port)"
$command = "& netsh.exe http delete sslcert hostnameport=$($hostName):$($port)"
Write-Info "Executing: $command"
Invoke-Expression $command
}
else {
return
}
}
$appIdGuid = [guid]::NewGuid().ToString("B")
$command = "& netsh.exe http add sslcert hostnameport=$($hostName):$($port) certhash=$($certificate.Thumbprint) certstorename=MY appid='$($appIdGuid)' "
Write-Info "Executing: $command"
Invoke-Expression $command
}
}
function Update-Certificates([string] $domainNameMatchPattern, [string] $variableNameForCertificateToUse)
{
Write-Info "Update-Certificates starting"
$certificateFriendlyName = $OctopusParameters["$($variableNameForCertificateToUse).Name"]
Write-Info "Certificate variable name is $certificateFriendlyName"
Import-Module WebAdministration
$bindingsToUpdate = Get-WebBinding | Where-Object { $_.protocol -eq "https" -and $_.bindingInformation -match $domainNameMatchPattern }
Write-Info "Found $($bindingsToUpdate.Length) binding(s) to update:"
Write-Info $bindingsToUpdate
[regex]$bindingInfoRegEx = "\*:(?<portNo>\d+):(?<hostName>.+)"
foreach ($binding in $bindingsToUpdate) {
$bindingInfoMatch = $bindingInfoRegEx.Match($binding.bindingInformation)
[int]$portNo = $bindingInfoMatch.Groups["portNo"].Value
$hostName = $bindingInfoMatch.Groups["hostName"].Value
AssignCertificate -friendlyName $certificateFriendlyName -hostName $hostName -port $portNo
}
}
@sverrehundeide

This comment has been minimized.

Show comment Hide comment
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment