我正在尝试创建一个powershell脚本,当我的一个或多个证书即将到期时,它会提醒我。我结合了一些我在互联网上找到的脚本,它似乎工作正常。唯一的问题是,当发送电子邮件时,我只获得一个大行,所有证书一个接一个。我希望获得更多的列表,例如: 证书1 主题:CN =你好 到期时间:2/11/2017 1:00:00 AM
证书2 主题:CN = hello2 到期时间:2/11/2017 1:00:00 AM
如果可能的话,我还想要一些帮助,如何从证书主题获取CN而不是完整的主题(OU,O,L,S,C)
这是我目前的剧本:
import-module webadministration
$DaysToExpiration = 700 #just modify this date for more or less
$expirationDate = (Get-Date).AddDays($DaysToExpiration)
$body = Get-ChildItem CERT:LocalMachine/My |
Where {$_.NotAfter -lt (Get-Date).AddDays($DaysToExpiration)}
$body | select Subject, @{Name="Expiration"; Expression = {$_.NotAfter}} | fl | out-string
$emailSmtpServer = "172.17.1.236"
$emailSmtpServerPort = "25"
$emailSmtpUser = "test"
$emailSmtpPass = "test"
$emailMessage = New-Object System.Net.Mail.MailMessage
$PCName = $env:COMPUTERNAME
$emailMessage.From = "$PCName@test.com"
$emailMessage.To.Add( "test@dev.test.de" )
$emailMessage.Body = $body | select Subject, @{Name="Expiration"; Expression = {$_.NotAfter}} | fl | out-string
$emailMessage.Subject = "Certificates Expiring within $DaysToExpiration days"
$emailMessage.IsBodyHtml = $true
$SMTPClient = New-Object System.Net.Mail.SmtpClient( $emailSmtpServer , $emailSmtpServerPort )
$SMTPClient.EnableSsl = $false
$SMTPClient.Credentials = New-Object System.Net.NetworkCredential( $emailSmtpUser , $emailSmtpPass );
if ($emailMessage.Body.Length -gt 1)
{
Write-host "Sending Email"
$SMTPClient.Send( $emailMessage )
}
答案 0 :(得分:1)
我正在搜索相同的内容,我发现以下堆栈溢出 link
$s = Get-ChildItem -Path 'Cert:\localmachine\My'| select subject
$s -replace "(CN=)(.*?),.*",'$2'
$s = $s -replace "@{Subject="
或非正则表达方式..
$sub = $_.Subject.split(",")[0].split("=")
$sub[1] = $sub[1] -replace "\*","star"
$sub[1]
它适用于大多数域证书,但我可以看到自我证书和服务器证书的一些问题。
答案 1 :(得分:0)
配置$ emailMessage.IsBodyHtml = $ false或创建HTML正文。