PowerShell Fault Treatment

*If you're merely joining united states, this post is part of a series on Getting Started with PowerShell. If yous'd like to catch upwards (or skip ahead), click on the appropriate post below.

Getting Started with PowerShell
Windows PowerShell, PowerShell Core and PowerShell: Huh?
Installing PowerShell and Visual Studio Code
Running PowerShell Commands and Getting Help
Working with the PowerShell Pipeline
Writing your First PowerShell Script
Agreement Loops in PowerShell
Using PowerShell Modules
Connecting to Azure

We all would like to think our scripts never run into an error. And that we only write the best of the all-time. We'd be wrong.

Regardless of how much time and try you put into writing a PowerShell script to run perfectly, an mistake volition pitter-patter in with you to the lowest degree expecting it.

To ensure we set upwardly a net to grab all of the errors that are spring to happen, it's of import to understand error treatment. Fault handling is a concept in all programming languages that outlines steps, procedures and lawmaking that'south written to intelligently capture errors and do something nearly them. PowerShell is no different.

In this article in our Getting Started with PowerShell series, yous're going to learn:

  • when to use error handling techniques

  • where errors might pop up

  • how to foreclose them from derailing your blood, sweat and tears PowerShell script

Let's get going!

Error Handling: Expect the Unexpected

In a nutshell, error handling is attempting to code for the unexpected. When yous begin writing more avant-garde scripts, y'all'll observe many different ways the lawmaking fails. Regardless of how many times y'all test a script, unless information technology'southward run exactly the same style in the exact same environment, chances are it might fail.

Let's suppose you lot, the reader were casually following along in the previous postal service on creating your first PowerShell script <link here>. Later on y'all followed each step provided, you were able understand the lawmaking snippet we covered before below.

The lawmaking snippet beneath finds the notepad process. If found, it and then stops the process. Simple plenty, right? Not quite.

                    $procedure = Become-Process -Name notepad if ($process) {     $procedure | Stop-Procedure }                  

The code above works fine if notepad is open simply attempt it when it'due south not. You'll be presented with that lovely scarlet text.

Error for command not finding Notepad

That was unexpected.

Agreement Terminating vs. Not-Terminating Errors

The error you lot saw above in the ugly red text was one of 2 types - terminating or not-terminating. Which one it was, yous can't tell by just viewing the mistake bulletin. Let'south find out.

A terminating mistake is 1 that's been labeled equally bad enough to completely stop code execution. When you run a script and the script encounters a terminating error, the entire script stops. The error terminates execution. Yous'll run across one error message and the unabridged script halts.

Some errors aren't quite as serious. These errors are called non-terminating errors. Not-terminating errors do not halt lawmaking execution. Instead, they spit out the error and the script continues. These errors aren't considered important enough to stop everything.

Have the above instance of attempting to find the notepad process using Get-Process. That command returned an error but what kind? To detect out, you need to use a common parameter on all PowerShell commands called ErrorAction. This parameter is available on all commands in PowerShell and controls what happens when a non-terminating error is returned.

To demonstrate, ensure notepad is closed and running the following command.

                    Get-Process -Proper name notepad -ErrorAction Ignore                  

Notice that nada happens. We've confirmed that when the notepad process does not exist, Become-Process returns a non-terminating error. If this code were in a script, the script would go on to run.

Let's say you disagree with PowerShell and remember this command should return a terminating error. The case when the notepad procedure doesn't exist should stop a script. In that case, use Stop for the ErrorAction.

                    Get-Process -Proper name notepad -ErrorAction Stop                  

When you run a control using the Stop value, PowerShell treats any errors returned every bit terminating and acts appropriately.

You can control non-terminating and terminating errors globally using the $ErrorActionPreference variable.

Catching Unexpected Errors

A script'south goal is not to render any errors - it'southward to not return unexpected errors. But how are yous supposed to know when an mistake will happen? You build a internet or, more specifically, you endeavour to catch an error.

To build an "fault cyberspace", you need to empathize try/catch blocks. When a terminating fault is returned from a command that'due south known every bit throwing. PowerShell throws terminating errors. Without whatsoever other code around, PowerShell throws that fault which stops code execution.

The primal to error handling is catching errors as they happen and then doing something about that in code. Permit's take our Get-Process scenario for example.

Previously, when you lot ran Go-Process -Proper name notepad -ErrorAction Cease, a terminating error was thrown and you saw the mistake bulletin in the console. If that line were in a script, what kind of activeness would you similar to perform if an fault was thrown?

If you run the below lawmaking, information technology won't work. PowerShell volition die at line ane if notepad isn't running.

                    $process = Go-Process -Name notepad if ($procedure) {     $process | End-Process }                  

How would yous ensure notepad is stopped? By introducing a try/take hold of block. A try/catch block is really two blocks indicated past the opening and closing curly braces. To implement a effort/catch block, add all of the code that is capable of throwing an mistake within of the try block. And then, add the lawmaking to run if the error is thrown within the catch block.

You tin can see below a well-handled script. If the notepad process is started, no error volition be thrown and the script will stop the process. But if the procedure is non started, the script will throw an error, cease up in the catch block and return a squeamish bulletin.

                    attempt {     $process = Become-Process -Name notepad -ErrorAction End     $process | End-Procedure } catch {     Write-Host "The notepad procedure was not started." }                  

The endeavour/catch block is your friend when handling errors.

Determination

Introducing mistake treatment ups your PowerShell game. If you're properly implementing error handling techniques, you've graduated from a beginner to intermediate-level scripter. Error handling is a critical skill to learn if you intend to write scripts of any complexity.

Remember to wrap a try cake effectually lawmaking that may return a terminating fault and be sure to handle that scenario in the catch block.

Adam Bertram

Almost the Author

Hi, I'g Adam. I'm a 20+ year veteran of Information technology and experienced online business professional. I'm an entrepreneur, IT influencer, Microsoft MVP, blogger, trainer, writer and content marketing writer for multiple technology companies.

Follow me on my blog, Twitter, LinkedIn