1

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
 }
MobileEvangelist
  • 2,583
  • 1
  • 25
  • 36
Jeetcu
  • 43
  • 3
  • 10
  • Did you just meant that you want last three lines should get executed after try or catch anyway?? I'm not getting what you want to say. – MobileEvangelist Dec 27 '16 at 06:50
  • Yes that's right. In detail, when the above commands in Try block have some issues it will make an entry to csv file and also sends a mail. But I also want to make an entry if its run successfully. Which is not working. – Jeetcu Dec 27 '16 at 06:55
  • You can move that part to finally{} block after catch so will get executed after try and catch execution. Even you got exception or not after try and catch execution will come to finally block and add that csv file entry. – MobileEvangelist Dec 27 '16 at 06:55
  • No. We can't use Finally because this will executes whatsoever and make entry regardless of error we get or not. – Jeetcu Dec 27 '16 at 06:59
  • Dude are you serious !! you just not agreed to accepted the answer I've given to you in prev. comment ; and said that something else.. – MobileEvangelist Dec 27 '16 at 08:56
  • Oops. Really apologize for that, somehow in hurry i read something and misinterpreted. Whatever you have mentioned is perfect. I Take my words back ;). Thanks and thumbsup. – Jeetcu Dec 27 '16 at 12:20
  • fair enough.. :)..even I said something with wrong perception.. – MobileEvangelist Dec 27 '16 at 16:46

2 Answers2

1

You should use Finally Block for your requirement. So that whatever results in try or catch, it should always run the Finally block.

So Instead of this:

$Time=Get-Date
if (!$Error) {
    $Time | select @{l='DC2';e={$_.DateTime}} | Export-Csv D:\Output.csv -append
}

Do This:

Finally 
{

$Time=Get-Date
    if (!$Error) {
        $Time | select @{l='DC2';e={$_.DateTime}} | Export-Csv D:\Output.csv -append
    }

}

Hope it helps...

Ranadip Dutta
  • 8,857
  • 3
  • 29
  • 45
  • @Randadip: Done :) – Jeetcu Dec 27 '16 at 08:08
  • The same thing I've mentioned in the 3rd comment of the question. So how this answer is different from it.??? Do you guys know each other ??? !!! – MobileEvangelist Dec 27 '16 at 08:58
  • @AndriodNewbie : 1st thing we don't know each other. Second , if you are giving any solution, you should post as an answer cause that will help others also. Thirdly, I have not gone through all the comments. Its not possible to go through all the comments every time. Fourthly, It sounded rude. – Ranadip Dutta Dec 27 '16 at 10:22
  • 1
    @AndriodNewbie : We don't know each other. Its not about knowing each other but a quick understanding of sentences and the way of presenting the answer. Also it was my mistake to throw myself in hurry and misinterpreted. Already I have accepted that by mentioning in comments. – Jeetcu Dec 27 '16 at 12:27
1

If you only want to put a date time stamp in a csv file, if you had a successful passing of the statements in the try block. You can just put the stamping as the last command in the try block.

Here is a break down:

Errors in the Try block: Each statement will be executed sequentially until there is a error.
Then the remaining statements in the Try block will not be executed. Instead the Catch block will be executed.

No errors in the Try block: All the statements in the Try block will be executed.
The Catch block will not be executed.

The Finally block Will always be executed!! You normally use this block for cleaning up. if you open a connection to the database or a open a file in the try block. you close the connection or the file in the Finally so you are sure that you closed every thing properly.

Tips If you want to be sure you catch every error in Try block you better use somting like the following:

Try
{
    $OldErrorActionPreference = $ErrorActionPreference
    $ErrorActionPreference = 'Stop'

    Statement 1
    Statement 2
    Statement 3
    Statement ...
}
Catch
{
     Errorhandling
}
Finally
{
    $ErrorActionPreference = $OldErrorActionPreference
}

Or you have to use the "-ErrorAction Stop" parameter with each important statement.

you can find more about errorhanding Here

Bert Levrau
  • 975
  • 8
  • 11