Monday, March 20, 2017

Powershell try catch, quick demo

This post is for the person to whom I explained try catch today ;)

When you do things in powershell you will need try-catch blocks to handle your errors.

Try, catch and finally
The try block contains the things you want to do. The catch block handles the error types, the generic catch is a catch all (usually not the right solution) and finally is what to do when you are finished.

The $error variable is the variable that will be your friend. When you run a script the $error.count() should be 0. When you are running in an IDE this can be different so as a matter of safety to avoid headache you might want to put as first lines of your script:

# clearing output and $error
Making errors
To demo the try catch I did a division by zero, as we all know this will give error and is thus an excellent candidate to learn try-catch.

$a = 1
$b = 0
$a / $b

Getting the errors from $error
Now that we have an error we can ask $error what type of error we created.


This returned [System.Management.Automation.RuntimeException]

When you are developing, check $error.count() to see if you handled all errors and did not forget one. During development, you can put as last line

write-host $error

To check if you handled everything.

Handling the error
Now that we know the error type we can handle it:

try {
    $a = 1
    $b = 0
    $a / $b
catch [System.Management.Automation.RuntimeException]{
   write-host "You caught your an error"
   write-host "This is the finally block"

The break statement instructs the catch block to go to the finally block and the $error.clear() in the finally block is cleaning up after yourself.

No comments: