I'm running the foreach loop below in my code right now, and it works great. However, I'd prefer to have it send one single email at the end of the script if the condition is met, instead of an email for each problem found. How can I do this?
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 "[email protected]" -To "[email protected]" -UseSsl
}
}