$PFXPath = "C:\Cert\"$PFXPW = ''$PublishedURL = "smtp.contoso.com"Import-Module WebAdministration$MicrosoftIISv2WMI = Get-CimInstance -Namespace root/MicrosoftIISv2 -Class __Namespace -ErrorAction SilentlyContinueif ($MicrosoftIISv2WMI -eq $Null) {Install-WindowsFeature Web-Mgmt-Compat, Web-WMI;};$SMTPServer = Get-CimInstance -Namespace root/MicrosoftIISv2 -Class IIsSmtpServerSetting -Filter ("FullyQualifiedDomainName='".$PublishedURL."'")if ($SMTPServer.AccessSSL -ne $True) {write-host 'TLS not enabled';exit;};Restart-Service SMTPSVC$SMTPLog = Get-WinEvent -LogName System | Where-Object { $_.ProviderName -eq 'smtpsvc' -and ($_.Id -eq 2000 -or $_.Id -eq 2001) } | Select-Object -First 1 -Property TimeCreated,Id,Message$PFXFullPath = ($PFXPath + ($PublishedURL -Replace '\*','_') + '.pfx')$NewCertProperties = New-Object System.Security.Cryptography.X509Certificates.X509Certificate2$NewCertProperties.Import($PFXFullPath,$PFXPW,[System.Security.Cryptography.X509Certificates.X509KeyStorageFlags]"DefaultKeySet")$StoredCerts = Get-ChildItem -Path 'Cert:\LocalMachine\My';if ($SMTPLog.Id -eq 2000) {$OldCert = $StoredCerts | where {$_.Thumbprint -eq ((($SMTPLog.Message -Split 'thumbprint')[1] -Split '\.')[0].Trim())};} else {$OldCert = $StoredCerts | where {$_.FriendlyName -eq $PublishedURL};};$NewCert = $StoredCerts | where {$_.Thumbprint -eq $NewCertProperties.Thumbprint};if ($NewCert -eq $Null) {$PasswordSection = ('-p ' + $PFXPW);if ($PFXPW -eq '') {$PasswordSection = ('-p "' + $PFXPW + '"');};$CommandLine = 'C:\Windows\System32\certutil.exe -f ' + $PasswordSection + ' -importpfx "'+$PFXFullPath+'" NoExport'cmd /c $CommandLine};$NewCert = Get-Item ('Cert:\LocalMachine\My\' + $NewCertProperties.Thumbprint);if ($NewCert -eq $Null) {write-host 'Can not Store New Cert';};if (($OldCert -eq $Null) -or ($NewCert.NotAfter -gt $OldCert.NotAfter)) {$IP = $SMTPServer.ServerBindings.IP;if ($IP -eq '') {$IP = '0.0.0.0';};if ((Get-Item IIS:\SslBindings\0.0.0.0!25) -ne $Null) {Remove-Item ('IIS:\SSLBindings\' + $IP + '!' + $SMTPServer.ServerBindings.Port) -Force};$NewCert | New-Item ('IIS:\SSLBindings\' + $IP + '!' + $SMTPServer.ServerBindings.Port)};
2025-10-23
Replace Ceritificate on IIS SMTP Virtual Server
Labels:
Certificate,
Email,
PowerShell,
SMTP
訂閱:
張貼留言 (Atom)
沒有留言:
張貼留言