I have a script that sends an email if a task fails (SendMailErr). I would like to add in retrying to send the email if the previous send-mailmessage failed. I had tried to put it into a try catch finally loop within the function but it didn’t work as expected. Here is my code
$waitMail = 60
$sendErr = "Error Sending Email to SI Team: $_. Retrying in $waitMail minute(s)"
function SendMailErr {
$MessageParameters = @{
From = $from
To = $to
Subject = "ALERT: Backup Failed for $env:ComputerName.$env:USERDNSDOMAIN - $((Get-Date).ToShortDateString())"
Body = $body | Out-String
SmtpServer = $Smtp
Priority = "High"
Attachments = $attachments
}
try { Send-MailMessage @MessageParameters -EA Stop
Exit
}
catch { Write-Log $sendErr
Sleep $waitMail
Send-MailMessage @MessageParameters
Exit
}
finaly {
Write-Log "Error: Unable to send email to SI Team"
Exit
}
Any suggestions would be greatly appreciated. I’m sure there’s a better way to structure it, my googling just hasn’t found it yet.
Thanks,
Amelia
I’ve figured this out in my own clumsy way…
Thank you to the person that pointed out I had an Exit within the trap.
The following works for me now
function SendMailErr {
$MessageParameters = @{
From = $from
To = $to
Subject = "ALERT: Backup Failed for $env:ComputerName.$env:USERDNSDOMAIN - $((Get-Date).ToShortDateString())"
SmtpServer = $smtp
Body = $body
Priority = "High"
}
try {
Send-MailMessage @MessageParameters -EA Stop;
}
catch { Write-Host $sendErr
Sleep $waitMail
Send-MailMessage @MessageParameters
}
Exit
}
1 Answer