I want to use If/Else statement in Try/Catch block. Below is my code. Here I am able catch the error when script fails but when its successful I want to stamp a datetime in .csv file but its not working. Please help.
Try
{
$hostcomputer = hostname
$IP = "10.x.x.x"
$pso = New - PSSessionOption - SkipCACheck - SkipRevocationCheck - SkipCNCheck: $TRUE - ErrorAction Stop# $Session = New - PSSession - ConfigurationName Microsoft.Exchange - ConnectionUri https: //mail.Test.com/powershell/?ExchClientVer=15.0 -Credential (Get-Credential) -Authentication Basic –AllowRedirection –SessionOption (New-PSSessionOption –SkipRevocationCheck)
$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 FromAddress @Test.com - To "ToAddress@Test.com", "ToAddress2@Test.com" - Subject "Test - RPS Not Working" - SmtpServer smtp.TEST.net - Body "Error generated on $hostcomputer = $IP. The Error Message was:- $ErrorMessage. AdditionalInfo:--$FailedItem. --NOTE: This is very first error and you may require to check and diagnose if any other issue."
$Text = "Connection Failed"###
You have to create.csv file manually and name the column as 'DC2'
$Text | select @ {
l = 'DC2';
e = {
$_
}
} | Export - Csv D: \Output.csv - append
}
$Time = Get - Date
if (!$Error)
{
$Time | select @ {l = 'DC2'; e = {$_.DateTime}} | Export - Csv D: \Output.csv - append
}