2012-02-09 42 views
1

我有一個腳本在任務失敗時發送電子郵件(SendMailErr)。如果以前的發送郵件消息失敗,我想添加重試以發送電子郵件。我試圖把它放入try函數中,最後在函數內循環,但它沒有像預期的那樣工作。這裏是我的代碼等待60秒,然後重新發送,如果Send-MailMessage失敗Powershell

$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

你忘了說明問題。你期望什麼?發生了什麼? – 2012-02-09 03:14:15

+0

對不起。它根本沒有發送電子郵件。我希望它會嘗試發送電子郵件,如果它沒有在日誌文件中寫入,如果失敗,但又在嘗試。我發現發送郵件偶爾沒有發送,但一分鐘後手動重試(SMTP服務不可用) – user1131196 2012-02-09 03:28:38

+1

很高興你知道了。只是爲了讓你知道,你可以在這裏回答你自己的問題,這非常好。 – 2012-02-09 05:51:31

回答

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 
}