如何 运行 在 TRY 块中多次重试命令

How to run retry the commands multiple times in TRY block

在下面的 try 块代码中,我想多次重试 运行 的最后三个命令,然后继续 catchfinally 块。如果我们可以放置第 5、6 和 7 行,则意味着一种重试。假设第 5 行应该 运行 3 次,如果失败则继续 catchfinally.

try {
    $hostcomputer = hostname
    $IP = "10.x.x.x"
    $pso = New-PSSessionOption -SkipCACheck -SkipRevocationCheck -SkipCNCheck:$TRUE -ErrorAction Stop
    $session = New-PSSession -Authentication Negotiate -ConnectionUri https://mail.test.com/powershell/?ExchClientVer=15.1 -ConfigurationName microsoft.exchange -SessionOption $pso -ErrorAction Stop
    Import-PSSession $session -AllowClobber -ErrorAction Stop
} catch {
    $ErrorMessage = $_.Exception.Message
    $FailedItem = $Error
    Send-MailMessage -From User1.test@test.com -To "User2@test.com" -Subject "DC2 - RPS Not Working" -SmtpServer smtp.test.net -Body "Error generated on $hostcomputer = $IP. The Error Message was:- $ErrorMessage."
    $Text = "Connection Failed"
    # You have to create .csv file manually and name the column as 'DC2'
    $Text  | select @{l='DC2';e={$_}} | Export-Csv D:\DC2.csv -Append
} finally {
    $Time=Get-Date
    if (!$Error) {
        $Time | select @{l='DC2';e={$_.DateTime}} | Export-Csv D:\DC2.csv -Append
    }
}

尝试第 5 行 3 次的一种方法是使用如下所示的 Do Until 功能:

Try
{
$hostcomputer = hostname
$IP = "10.x.x.x"
$pso = New-PSSessionOption -SkipCACheck -SkipRevocationCheck -SkipCNCheck:$TRUE -ErrorAction Stop
$session = New-PSSession -Authentication Negotiate -ConnectionUri https://mail.test.com/powershell/?ExchClientVer=15.1 -ConfigurationName microsoft.exchange -SessionOption $pso -ErrorAction Stop


        [int]$retryCount = 0;
        Do{


         try{
            $retryCount++;
            import-pssession $session -allowclobber -ErrorAction Stop


         } catch [Exception]{

                Write-Warning "Try Number $retryCount"

                if($retryCount -eq 3){
                    $_ 
                    $_.GetType() 
                    $_.Exception 
                    $_.Exception.StackTrace 
                    throw 

                }
              }

        } #End of Do
        Until($retryCount -eq 3)


}
Catch
{
$ErrorMessage = $_.Exception.Message
$FailedItem = $Error
Send-MailMessage -From User1.test@test.com -To "User2@test.com" -Subject "DC2 - RPS Not Working" -SmtpServer smtp.test.net -Body "Error generated on $hostcomputer = $IP. The Error Message was:- $ErrorMessage."
$Text = "Connection Failed"
###You have to create .csv file manually and name the column as 'DC2'
$Text  | select @{l='DC2';e={$_}} | Export-Csv D:\DC2.csv -append
}

Finally 
{

$Time=Get-Date
if (!$Error) {
    $Time | select @{l='DC2';e={$_.DateTime}} | Export-Csv D:\DC2.csv -append
}

}

那不是 try..catch 的工作方式。对于类似的事情,您需要使用命令在 try..catch 块周围放置一个循环,延迟错误处理并自己管理 "finally" 内容。像这样:

$attempt = 3
$success = $false
while ($attempt -gt 0 -and -not $success) {
  try {
    $pso = New-PSSessionOption ...
    $success = $true
  } catch {
    # remember error information
    $ErrorMessage = $_.Exception.Message
    $FailedItem   = $Error

    $attempt--
  }
}

...

# error processing
if (-not $success) {
  $Text = "Connection Failed"
  Send-MailMessage -From ...
} else {
  $Text = Get-Date
}

# "finally"
$Text | select @{l='DC2';e={$_}} | Export-Csv D:\DC2.csv -append

也许您可以将重复命令的代码包装在这样的函数中(未经测试):

function Repeat-Command {
  [CmdletBinding()]
  Param(
    [Parameter(Mandatory=$true)]
    [scriptblock]$Scriptblock,

    [Parameter(Mandatory=$false)]
    [int]$Count = 1
  )

  Begin {
    $attempt = $Count
    $success = $false
  }
  Process {
    while ($attempt -gt 0 -and -not $success) {
      try {
        $res = Invoke-Command -ScriptBlock $Scriptblock -ErrorAction Stop
        $success = $true
      } catch {
        $ex = $_    # remember error information
        $attempt--
      }
    }
  }
  End {
    if ($success) {
      return ,$res
    } else {
      throw $ex
    }
  }
}

$pso = Repeat-Command -Scriptblock { New-PSSessionOption ... } -Count 3
...