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

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

本文介绍了如何在TRY块中多次运行重试命令的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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 block. Means a kind of retries if we can put for this 5th, 6th, and 7th line. Lets say 5th line should run 3 times and if it fails then proceed with catch and finally.

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 [email protected] -To "[email protected]" -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块周围放一个循环,延迟错误处理并自己管理最终"的东西.像这样:

That's not how try..catch works. For something like that you'd need to put a loop around the try..catch block with the commands, delay the error processing and manage the "finally" stuff yourself. Something like this:

$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

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

Maybe you could wrap the code for repeating a command in a function like this (untested):

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

这篇关于如何在TRY块中多次运行重试命令的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-23 19:08