我有一个脚本,如果任务失败,它会发送一封电子邮件(SendMailErr)。如果先前的send-mailmessage失败,我想添加重试以发送电子邮件。我曾尝试将其放入函数中的try catch finally循环中,但它没有按预期工作。这是我的代码
$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
}
任何建议都将不胜感激。我确信有更好的方法来构建它,我的谷歌搜索还没有找到它。
谢谢, 阿米莉亚
我用自己笨拙的方式想出来了......
感谢那位指出我在陷阱中退出的人。
以下对我有用
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
}
答案 0 :(得分:1)
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
}