How To Use Try Catch Finally With PowerShell
Think you can do better? Show us!
Jason takes us through the craziness that is throwing exceptions around, catching and finally doing something. Error handling is an important topic in PowerShell and is one that a lot of people don’t take too seriously. Luckily, Jason’s the man and he’s putting down some knowledge you need to pick up ASAP.
In this snip we're going to focus on how to use the try catch and finally script blocks with powershell. First let’s talk about want to use a try catch and finally block They’re used to respond or handle terminating errors and scripts for more information on forcing non terminating errors to terminate check out my other snip covering non terminating errors. In the try block you would have found a section of code you would like powershell to monitor for errors. Here we are using the get child item commandlet to look for the snip dot log. Since we are forcing a terminating error powershell will search for the catch block to determine how to handle the error. And our catch block we're writing a warning message about the exception and printing out the exception type. They finally block is executed every time the script is run with or without error. You can use this block to free up resources write a message or clean up any other objects. Now we execute this code we can see that the item not found exception was thrown and caught by our catch block. It even though and error was thrown our finally blocked still executed. Now building on our example. You can specify an exception type in the catch block in order to handle specific exceptions, a certain way. Here we are specifying the exception type item, not found exception in our first catch block. It is possible to specify multiple exception types in the same or different catch blocks. However, the first catch blog. That matches the exception thrown will be the one executed. Running this code we can see that the item not found exception was thrown and call it but now our item, not found exception catch block is creating the file and the finally block is still running after the error. Notice that the second catch block. It did not execute that was because the first catch block match the exception type that was thrown. In our last example. We're specifying 3 catch blocks, but 2 are using specific exception types item not found exception and command, not found exception. Running the code we can see our first catch block was skipped because they did not match the exception type. However, these second catch block was executed because it matched the exception type command, not found exception. That covers using the try catch and finally script blocks in powershell. Thank you for watching.