我现在正在我的代码中运行下面的foreach
循环,效果很好。但是,如果条件满足,我宁愿让它在脚本末尾发送一封电子邮件,而不是发现每个问题的电子邮件。我怎么能这样做?
foreach ($server in $servers) {
$DT = Get-WmiObject -Class Win32_LocalTime -ComputerName $server
$DateTime = (Get-Date -Day $DT.Day -Month $DT.Month -Year $DT.Year -Minute $DT.Minute -Hour $DT.Hour -Second $DT.Second)
$SUTC = $DateTime.ToUniversalTime()
$now = Get-Date
$NUTC = $now.ToUniversalTime()
$Difference = (New-TimeSpan -Start ($NUTC) -End ($SUTC))
Write-Host "Time at $server is $SUTC. Time difference of $Difference."
if ($Difference -ge '00:03:00') {
Send-MailMessage -Subject "Time Report -$(get-date -Format "MM-dd-yyy")" -Body "Time difference of more then 3 minutes detected." -SmtpServer "SMTPSERVER" -From "admin@firm.com" -To "group@firm.com" -UseSsl
}
}
答案 0 :(得分:2)
在foreach之前声明一个数组并添加消息。然后在foreach之后调用Send-MailMessage。例如:
$errors = @()
foreach ($server in $servers) {
$DT = Get-WmiObject -Class Win32_LocalTime -ComputerName $server
$DateTime = (Get-Date -Day $DT.Day -Month $DT.Month -Year $DT.Year -Minute $DT.Minute -Hour $DT.Hour -Second $DT.Second)
$SUTC = $DateTime.ToUniversalTime()
$now = Get-Date
$NUTC = $now.ToUniversalTime()
$Difference = (New-TimeSpan -Start ($NUTC) -End ($SUTC))
Write-Host "Time at $server is $SUTC. Time difference of $Difference."
if ($Difference -ge '00:03:00') {
$errors += "Time difference of more then 3 minutes detected."
}
}
if($errors.Count -gt 0) {
Send-MailMessage -Subject "Time Report -$(get-date -Format "MM-dd-yyy")" -Body ($errors -join "`n") -SmtpServer "SMTPSERVER" -From "admin@firm.com" -To "group@firm.com" -UseSsl
}