如果失败,如何重新运行PowerShell cmdlet的一行

我写了一个应该自动发送电子邮件的PowerShell脚本,但是有时候由于networking问题邮件不会发送出去。

以下是我如何发送电子邮件:

$smtp_notification.Send($mail_notification) 

这里是错误日志:

 Exception calling "Send" with "1" argument(s): "Failure sending mail." At line:1 char:24 + $smtp_notification.Send <<<< ($mail_notification) + CategoryInfo : NotSpecified: (:) [], MethodInvocationException + FullyQualifiedErrorId : DotNetMethodException 

遇到这种故障时,是否有重新运行发送线? 任何人都可以给我一些build议吗?

用一个try块放入一个循环,非常简单:

 $worked = $false while (-not $worked) { try { #Perform command to retry, passing -ErrorAction Stop $worked = $true # An exception will skip this } catch { # Should check to retry: error record is in $_ } }