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