PowerShell Error Handling: Learn These Key Techniques

Join PowerShell expert Brien Posey as he demonstrates key techniques for handling errors in PowerShell scripts, including suppressing non-fatal errors with -ErrorAction, using Try and Catch for structured error handling, and generating warnings with Write-Warning.

Brien Posey

April 3, 2024

9 Min View
ITPro Today

In this tutorial, PowerShell expert Brien Posey guides viewers through essential techniques for managing errors within PowerShell scripts. Through practical demonstrations, Posey explores methods such as suppressing non-fatal errors, setting up Try and Catch blocks, and using warning messages to streamline script execution.

The transcript has been lightly edited for length and clarity.

Transcript:

Brien Posey: Hello, greetings and welcome. I'm Brien Posey. In this video, I want to show you some techniques commonly used for handling errors in PowerShell.

If you look on the right side of the screen, you can see a simple script that I've created:

c:
cd\
cd scripts
New-Item -Name “Temp” -ItemType “Directory”
Write-Host ‘Do some other stuff.’

The first line says c: – this changes to the C: drive if you're not already there. Then we have cd\ – this drops the command prompt down to the root directory. Then we have cd scripts. It opens the Scripts folder. Then we have a line that says New-Item -Name “Temp” -ItemType “Directory.” What this line does is create a new folder called Temp. Then the very last line we have is Write-Host ‘Do some other stuff.’ This line is a generic representation of any other instructions you would normally execute. The point is that we have a line of code that executes after we create the Directory.

So, let's execute the script. I'll press Enter. We can see we created the new folder.

Related:4 Cmdlets To Display Text on the PowerShell Console Screen

I'm going to rerun the script. This time I get an error message because the folder already exists.

Let's look at what's going on in the first three steps in the script. The c:, cd\, and cd scripts commands are silent. They don't produce any visible output, so we don't have anything showing up in our PowerShell window.

When we execute the New-Item cmdlet, that's where we get the error. But right here, PowerShell displayed, ‘Do some other stuff.’ So, what happened is that even though we got an error, this wasn't a fatal error. PowerShell, by default, when it encounters a non-fatal error will keep running. The folder already existed in this case, so it threw an error message but continued running, doing what it was supposed to do.

It would be fine if this were a real-world script trying to create a folder and then do other stuff. It would do what it needs to do. The problem with this is that it's ugly. If you gave this script to somebody unsuspecting and they got an error message, they would see all the red text on the screen, and they probably wouldn't know what to do with it.

-ErrorAction SilentlyContinue

Let's look at some ways that we might suppress this error. One of the things that we can do is to add an -ErrorAction to the New-Item cmdlets. The way that we do that is by going to the end of the New-Item line and simply typing:

Related:PowerShell Parameter Validation: Ensuring Valid Input for Functions

New-Item -Name “Temp” -ItemType “Directory” -ErrorAction SilentlyContinue

It tells PowerShell to ignore this line if it causes an error. Don't display the error and continue as long as it's non-fatal.

Let me go ahead and save this file. I'll rerun the script, and you can see the error has been suppressed this time. All we see is, ‘Do some other stuff.’ So, we still encountered an error, but the difference is that PowerShell isn't showing the error.

That's one way that we can handle errors in PowerShell.

Try & Catch

The problem is that we don't necessarily know we will encounter a non-fatal error in our scripts. Sometimes, they can be fatal. If you suspect that one might occur and cause a script to stop running, you don't want to suppress that. A better idea is to use Try and Catch.

Let's look at how that works. Okay, so I paused the video for a moment, and I added a few lines of code to my script:

c:
cd\
cd scripts

Try {
New-Item -Name “Temp” -ItemType “Directory”
}
Catch {
Write-Host “The folder already exists”}

Write-Host ‘Do some other stuff.’

The first three lines are what we had before. You'll notice that we still have the New-Item cmdlet just as we did before, but now the New-Item cmdlet is enclosed in brackets. We can enclose this cmdlet in brackets using the Try command. What the Try command does is execute whatever command is in brackets to see if it produces an error or not. If it does, we use the Catch command to handle the error. So, in this case, the Catch command will execute the line, Write-Host “The folder already exists”.

Related:Getting Started Using GitHub Copilot for PowerShell Scripting

So, rather than displaying a PowerShell-style error message, we will receive a line saying the folder already exists.

Let's go ahead and run the script to see what it does.

When I run the script, we get a big red error message like before we did anything. Let's look at what's happening here. The error message that we get is:

New-Item : An item with the specified name C:\scripts\Temp already exists.

It is the same error message that we got earlier. It would appear the Try and Catch aren't doing anything. Remember, the Catch statement is designed so that if an error does occur, we're supposed to see a line of text saying the folder already exists. That's not happening.

So, why is that? Well, the reason has to do with something that I talked about earlier. I mentioned that PowerShell’s default behavior is that if it encounters a non-fatal error, it will progress the rest of the way through the script. That's what's happening here. We get an error, the error is non-fatal, and so the rest of the script is executing. You can see, ‘Do some other stuff.’

But remember the -ErrorAction from earlier? When I had the New-Item cmdlet, I suppressed the error, which was non-fatal, by typing -ErrorAction SilentlyContinue.

If I save this and rerun the script, the error goes away. But I don't get that message saying that the folder already exists. So, why is that? Well, it is related to the difference between fatal and non-fatal errors. It is a non-fatal error, which means that Try and Catch isn't going to work. Try and Catch are only designed for situations in which a fatal error occurs.

Now, in a situation like this, where we're trying to create a folder but that folder already exists, we're never going to encounter a fatal error. So, what can we do to use Try and Catch? Well, we would fix this problem by changing the -ErrorAction. Instead of using SilentlyContinue, I'm going to use Stop.

Try {
New-Item -Name “Temp” -ItemType “Directory” -ErrorAction Stop
}
Catch {
Write-Host “The folder already exists”}

What Stop does is tell PowerShell to treat this error as though it were a fatal error even though it's not.

Let me go ahead and save this. Let's run the script one more time.

This time I get the error message outlined by the Catch statement: “The folder already exists”. So instead of the big, red, glaring error that PowerShell would usually generate, I see a nice line of formatted text. You'll notice that PowerShell does continue after that. It displays the line that says, ‘Do some other stuff.’

Write-Warning

There's one more thing that we might do to make the script a little bit neater. Instead of displaying a line that says, “The folder already exists,” maybe we want to display a warning message. That way the text will be highlighted. What we would do is easy. We would change Write-Host to Write-Warning.

Catch {
Write-Warning “The folder already exists”}

I'll save my file. Let's run the script. We have a warning message displayed. PowerShell generates a warning that the folder already exists.

WARNING: The folder already exists

Of course, once that warning message is displayed, PowerShell executes the last line of the script, which is Write-Host ‘Do some other stuff.’

Those are a few techniques for suppressing errors within PowerShell scripts. I'm Brien Posey. Thanks for watching.

About the Author

Brien Posey

Brien Posey is a bestselling technology author, a speaker, and a 20X Microsoft MVP. In addition to his ongoing work in IT, Posey has spent the last several years training as a commercial astronaut candidate in preparation to fly on a mission to study polar mesospheric clouds from space.

https://brienposey.com/

Sign up for the ITPro Today newsletter
Stay on top of the IT universe with commentary, news analysis, how-to's, and tips delivered to your inbox daily.

You May Also Like