1

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
  } 
}

1 Answer 1

2

Declare an array before the foreach and add messages. Then call Send-MailMessage after your foreach. Example:

$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 "[email protected]" -To "[email protected]" -UseSsl
}
Sign up to request clarification or add additional context in comments.

3 Comments

Don't do this. Appending to an array in a loop is bound to perform poorly, because each time the array is re-created with size+1, and all existing elements are copied to the new instance. Instead just echo inside the loop and assign the loop output to a variable ($var = foreach ($server in $servers) { ... }).
imo, append to an array will be a problem just for large data. But that don't deny your warning.
True, for small amounts of data it usually isn't noticable, but you don't gain anything either.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.