IF/ELSE vs TRY/CATCH
Hi,
I got few questions about how Try/Catch works in PowerShell recently.
First of all, you need to get the thing that the cmdlet you put in the try section has to return an exception in case of error.
I mean, if your cmdlet return boolean value it won’t work !
Let’s try an example with Test-Path
If we took a drive Z: which doesn’t exist and try to catch an exception on it what’s happen ?
Try { Test-Path Z: } Catch { "Drive NOT exists" } Finally { "Hello World" }
If-Then-Else
This little script will never get back the “Drive NOT exists” because no exception is returned by a Test-Path CMDLet.
Test-Path Z:\
You see it’s returning “False”, so for PowerShell nothing is wrong here !!
If you wanna invoke an action in case or true or false, you have to use
if (Test-Path Z:\) { Do-Something here } Else { Do-SOmethingElse }
By the way, let’s see how Try/Catch works with exception…
Try/Catch/Finally
First let’s create an exception out from nowhere and trap it with Catch !
Try { throw [invalidoperationexception] } Catch [exception] { Throw "This is a test. Error: $($_.Exception.Message)" } Finally { "Hello world!" }
Obviously, you can catch as many as exception as you want like this
Try { throw [invalidoperationexception] } Catch [exception1] { Throw "This is a test. Error: $($_.Exception.Message)" } Catch [exception2] { Throw "This is a test. Error: $($_.Exception.Message)" } Catch { Throw "This is a test. Error: $($_.Exception.Message)" } Finally { "Hello world!" }
Here are the exceptions you can encounter : http://msdn.microsoft.com/en-us/library/vstudio/system.exception%28v=vs.100%29.aspx
See ya!