The simplest way to handle error catching is by using the try handler built into PowerShell. While you can can use an if loop to catch errors with additional logic, this handler is built-in to PowerShell and makes error handling dead simple. This is the basic structure of a try/catch statement:
Follow along and we'll go through a few different ways to use this as a comprehensive error-handling tool.
We'll start with something basic. Go ahead and paste this code into a new PS1 file and and run it:
"" doing?
When you are producing console output for the user to read, you may want to simply insert a blank line. The most common-sense way to do this is to just put in a blank Write-Host line, but a quicker way is to simply put an empty pair of double quotes ("") on a line. It's just a formatting shortcut.
You should see some output similar to this:
Let's break down what we see here.
Write-Host "Some text" -ForegroundColor SomeColor to display output to the screen.try block - simply attempting to divide 10 by 1, and save the value as $resultcatch block comes next -- but since the $result is valid, we had no failures and we simply skip itRead-Host to progress the script when the user is ready.try statement -- however, this time we try the impossible: divide by zero. We also fail.$result becomes invalid, we jump down to the catch block - we never see the "Result is valid!" messagecatch block, we log a basic failure message, but then also use Write-Error to display $_ -- which inside a catch block will always contain the error message that produced it.As you can see, this is a very useful statement - it simply allows code to jump to another place as soon as an error occurs. It will stop processing code and move onto the error handler. From there, we can determine how to handle the failure - we don't always need to exit the script entirely, but we may want to set some sort of variable that tells us to try something else or simply write an error message to a log.
There are also occasions where it might be important to know why an error was generated, such as knowing whether a file doesn't exist, a drive letter doesn't exist, or we lack permissions to see the file. We can use multiple catch statements to sort through errors. In the code below, try commenting out different lines in the try block to the different errors you can generate.
If you try out all the different error messages, you'll get some output like this:
finally block
You may not always want to finish execution just because the catch block has been called. In that case, we can use the final type of block for error handling, the finally block. Save and run the example below to see it in action. Try commenting out the throw line to see how it handles successful runs as well as failures.
throw-ing it all away
You can use the throw command to force an error. You may want to do this in the event that some piece of data isn't the way you want it to be, even if it technically didn't throw any errors. It can also be useful for simulations, such as this one!
If you try out both success and failure, you'll have output like this:
Seeing all of this in the console is nice - but you might want to refer to this later, especially if this is an automated task. If you'd like to generate a log file to view later, we can create a simple function to take care of that while also display some console output for us. Try out the following code to see it in action:
By tying in an if statement, we can even handle automated alerts when failures occur, or, as in our example, prompt the user to view the error log. All tied together, you can create an intuitive, useful logging system to see how your applications are working. As your programs get more and more complicated, good error logging will save tremendous amounts of frustration.
This lesson may have been a little less exciting than others, but it's an extremely useful bit of information to keep in your toolset while you develop your scripts and applications. Here are our main takeaways:
try statements to execute code and catch blocks to handle failures.try block will cause an immediate jump down to the catch block - no additional code will be executed.catch blocks to sort through different types of error messages.finally block to execute code regardless of the outcome of the try block.