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 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
}
}
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
...
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
}
}
来源:https://stackoverflow.com/questions/41554300/how-to-run-retry-the-commands-multiple-times-in-try-block