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

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

我编写了一个 PowerShell 脚本,它可以自动发送电子邮件,但有时由于网络问题,电子邮件不会发送出去。

以下是我发送电子邮件的方式:

$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

当我遇到此故障时,有没有办法重新运行发送线路?有人可以给我一些建议吗?

答案1

非常简单地,在其中放置一个带有 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 $_
  }
}

相关内容