How to run retry the commands multiple times in TRY block

前端 未结 2 770
终归单人心
终归单人心 2021-01-17 01:39

Here in below code in try block I want to retry the last three commands to run multiple times and then proceed with catch and finally

2条回答
  •  刺人心
    刺人心 (楼主)
    2021-01-17 02:16

    One way to try the 5th line 3 times is to use the Do Until functionality like below:

    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
    }
    
    }
    

提交回复
热议问题