2025-11-26

PowerShell 更新 IIS Site Bind SSL Cert

$PublishedURL = "www.contoso.com"
$IISSiteName = "www.contoso.com"

$PFXPath = "C:\Cert\Cert\"
$Password = "password"

$PFXFullPath = "$PFXPath$PublishedURL.pfx"

$pfx = New-Object System.Security.Cryptography.X509Certificates.X509Certificate2
$pfx.Import($PFXFullPath, $Password, [System.Security.Cryptography.X509Certificates.X509KeyStorageFlags]::EphemeralKeySet)

Import-Module IISAdministration

$NewCertProperties = $pfx | Select Thumbprint,NotAfter

$LastCertProperties = Get-ChildItem -Path "Cert:\LocalMachine\My" | where {($_.FriendlyName).tolower() -like $PublishedURL.tolower()} | select Thumbprint,NotAfter

$NewCertThumbprint = $NewCertProperties.Thumbprint
$NewCertNotAfter = $NewCertProperties.NotAfter
$LastCertThumbprint = $LastCertProperties.Thumbprint
$LastCertNotAfter = $LastCertProperties.NotAfter

write-host
write-host "New  Cert Thumbprint is: $NewCertThumbprint"
write-host "New  Cert NotAfter is: $NewCertNotAfter"
write-host
write-host "Last Cert Thumbprint is: $LastCertThumbprint"
write-host "Last Cert NotAfter is: $LastCertNotAfter"
write-host 

if ( ($NewCertNotAfter -lt $LastCertNotAfter) -or ($NewCertNotAfter -eq $LastCertNotAfter) ) {
 write-host "New Cert's ExpireDate is Less then the old one, Please check."
 Stop-Transcript
 exit;
}

if ($NewCertThumbprint -eq $LastCertThumbprint) {
 write-host "Cert Doesn't Change, Program Close, Please check."
 Stop-Transcript
 exit;
}

write-host ""
write-host "*** Import New Cert"
write-host ""

$CommandLine = 'C:\Windows\System32\certutil.exe -f -p "'+$Password+'" -importpfx "'+$PFXFullPath+'" NoExport'
cmd /c $CommandLine

write-host ""
write-host ("*** Enable New Cert on " + $IISSiteName)
write-host ""

$binding = Get-WebBinding -Name $IISSiteName -Protocol "https"
$binding.RemoveSslCertificate()
$binding.AddSslCertificate($NewCertThumbprint, 'My')

IISReset

write-host ""
write-host "*** Remove Last Cert"
write-host ""

Get-ChildItem -Path "Cert:\LocalMachine\My" | where {$_.Thumbprint -eq $LastCertThumbprint} | Remove-Item -Confirm:$false


沒有留言:

張貼留言