如何在TRY块

时间:2017-01-09 18:14:51

标签: powershell exchange-server

在下面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
    }
}

2 个答案:

答案 0 :(得分:4)

这不是try..catch的工作方式。对于类似的东西,你需要使用命令在try..catch块周围循环,延迟错误处理并自己管理“最终”的东西。像这样:

$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
...

答案 1 :(得分:1)

尝试第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
}

}