powershell 更新 IIS SSL 证书
Intro
最近发现我们开发环境的 IIS 上的 SSL 证书过期了,为了后面方便维护和更新,搞了一个 powershell 脚本,以后要更新的时候直接跑一下脚本就可以了,所以有了这篇文章
Solution
更新过程:
- 移除之前老的证书
- 导入新的证书
- 移除旧的 ssl 证书
- 创建新的 ssl 证书绑定新的证书
完整的更新脚本如下:
$hostName = "xxx.com"
$pfxCertPath = "C:ackupxxxxx.pfx"
$pfxCertPwdPath = "C:ackuppfx-password.txt"
$certImportPwd = Get-Content $pfxCertPwdPath | ConvertTo-SecureString -AsPlainText -Force
# try remove before ssl certs
Get-ChildItem "cert:LocalMachineMy" | where-object { $_.Subject -like "*$hostName*" } | Remove-Item
# import new ssl
$importedCert = Import-PfxCertificate -FilePath $pfxCertPath -CertStoreLocation "Cert:LocalMachineMy" -p $certImportPwd
$certHash = $importedCert.Thumbprint
# remove sslcert binding
netsh http delete sslcert hostnameport="${hostName}:443"
# add new sslcert binding
$guid = [guid]::NewGuid().ToString("B")
netsh http add sslcert hostnameport="${hostName}:443" certhash=$certHash certstorename=MY appid="$guid"
Reference
- https://docs.microsoft.com/en-us/windows/win32/http/delete-sslcert
- https://docs.microsoft.com/en-us/powershell/module/pkiclient/import-pfxcertificate?view=win10-ps
- https://stackoverflow.com/questions/37228851/delete-certificate-from-computer-store
- https://4sysops.com/archives/manage-iis-website-bindings-in-powershell/
- https://weblog.west-wind.com/posts/2016/Jun/23/Use-Powershell-to-bind-SSL-Certificates-to-an-IIS-Host-Header-Site