天天看點

powershell 更新 IIS SSL 證書

最近發現我們開發環境的 IIS 上的 SSL 證書過期了,為了後面友善維護和更新,搞了一個 powershell 腳本,以後要更新的時候直接跑一下腳本就可以了,是以有了這篇文章

powershell 更新 IIS SSL 證書

Intro

Solution

更新過程:

  1. 移除之前老的證書
  2. 導入新的證書
  3. 移除舊的 ssl 證書
  4. 建立新的 ssl 證書綁定新的證書

完整的更新腳本如下:

$hostName = "xxx.com"

$pfxCertPath = "C:\backup\xxxxx.pfx"
$pfxCertPwdPath = "C:\backup\pfx-password.txt"
$certImportPwd = Get-Content $pfxCertPwdPath | ConvertTo-SecureString -AsPlainText -Force

# try remove before ssl certs
Get-ChildItem "cert:\LocalMachine\My" | where-object { $_.Subject -like "*$hostName*" }  | Remove-Item

# import new ssl 
$importedCert = Import-PfxCertificate -FilePath $pfxCertPath -CertStoreLocation "Cert:\LocalMachine\My" -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

本文版權歸作者和部落格園共有,歡迎轉載,但未經作者同意必須保留此段聲明,且在文章頁面明顯位置給出原文連接配接,否則保留追究法律責任的權利。