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 ?

 If-Then-Else

This little script will never get back the “Drive NOT exists” because no exception is returned by a Test-Path CMDLet.

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

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 !

Obviously, you can catch as many as exception as you want like this

Here are the exceptions you can encounter : http://msdn.microsoft.com/en-us/library/vstudio/system.exception%28v=vs.100%29.aspx

See ya!