从结果发送邮件(应该很容易)

时间:2015-10-22 13:19:27

标签: email certificate invoke-command

我已经构建了一个脚本来检查来自某个发行者的本地机器证书在远程服务器上400.000天内到期(在测试时获得命中),但我不知道如何得到结果以发送实际电子邮件在IF语句之后(和之中)试验管道似乎不起作用。 我一直在谷歌搜索安静(当然),但因为我是Powershell的新手,有些代码很难解释。

我正在寻找类似的东西; if $ OutputFromtheIFStatement | Measure-Object -gt 0 {使用$ SendReportNow发送电子邮件。}

我的代码:

$Servers = 'testserver1,'testserver2'
$Threshold = 400000 
$Deadline = (Get-Date).AddDays($Threshold)
$MailSMTP = '-SmtpServer smtpserver.domain.com -Port 25'
$MailTo = "receiversmailaddress@company.com"
$MailFrom = "sendersmailaddress@company.com"
$MailSubject = '-Subject Certifikat expiring within 90 days'
$MailBody = '-Body ?'
$SendReportNow = 'Send-MailMessage $MailSMTP $MailFrom $MailTo $MailSubject'
Invoke-Command -ComputerName $Servers { Get-ChildItem Cert:\LocalMachine\My } | ForEach { 
If ($_.NotAfter -le $Deadline -and $_.Issuer -like '*CertainCompanyName*') { $_ | Select @{Label="Servername";Expression={($_.PSComputerName)}}, Issuer, Subject, @{Label="Expiry Date & Time";Expression={($_.NotAfter)}}, @{Label="Expires In (Days)";Expression={($_.NotAfter - (Get-Date)).Days}}
}
}

1 个答案:

答案 0 :(得分:0)

我清理了你的代码,希望这更容易消化。

$Servers = 'testserver1','testserver2'
$Threshold = 400000 
$Deadline = (Get-Date).AddDays($Threshold)

$certs = Invoke-Command -ComputerName $Servers { Get-ChildItem Cert:\LocalMachine\My } 

ForEach ($cert in $certs){
    If ($cert.NotAfter -le $Deadline -and $cert.Issuer -like '*CertainCompanyName*') { 
        $body = $cert | Select @{Label="Servername";Expression={($cert.PSComputerName)}}, Issuer, Subject, @{Label="Expiry Date & Time";Expression={($cert.NotAfter)}}, @{Label="Expires In (Days)";Expression={($cert.NotAfter - (Get-Date)).Days}}
        $MailSubject = "[$($cert.PsComputerName)] Certifikat expiring within 90 days"
        Send-MailMessage -SmtpServer smtpserver.domain.com -Port 25 -From sendersmailaddress@company.com -To receiversmailaddress@company.com -Subject $MailSubject -Body $body
    }
}

这将导致电子邮件发送如下:

Title:              [ServerA] Certifikat expiring within 90 days
-----  Body-------
Servername         : ServerA
Issuer             : CN=localhost
Subject            : CN=localhost
Expiry Date & Time : 4/5/2020 8:00:00 PM
Expires In (Days)  : 1627