Handle PowerShell Errors Like a Boss With These Tips
Whatsapp Pinterest

When you first start scripting in PowerShell, it can be tempting to package up a series of commands Powershell Cmdlets That'll Improve Your Windows Admin Skills Powershell Cmdlets That'll Improve Your Windows Admin Skills Powershell is equal parts command line tool and scripting language. It gives you the ability to automate your computer via the same commands you use to administer it. Read More . However, if your script fails you will not know where to start troubleshooting. To save yourself from wasting time trying to guess why your script failed, you should use error handling.

There are four parts to PowerShell error handling: the Error Action parameter, Try/Catch blocks, the Error Variable parameter, and logging.

PowerShell Error Handling the Easy Way

The first time you want to handle errors is when something stops your script in its tracks. If the failure does not affect your later steps, it might be best just to skip it and move on.

powershell error handling tips

On the other hand, it is not always clear when a given cmdlet throws a terminating error. Some cmdlets return an error but do not stop your script. You can then end up waiting for your script to complete while it outputs nonsense.

This is where the -ErrorAction parameter comes in. You use this to force a cmdlet to handle the error the way you want. If you are modifying an existing script Boost Your Productivity With Windows PowerShell Scripts Boost Your Productivity With Windows PowerShell Scripts What if you could bring the productivity of Linux over to Windows? Most Linux distros come packaged with the powerful Bash shell. PowerShell is an equally powerful terminal for Windows. Read More , you append it to the end of the cmdlet line.

Get-ChildItem -Path "~\Documents\*.jpg" -Recurse -ErrorAction Stop

Obviously, if you are using the Get-ChildItem cmdlet on its own, the error does not do much for you. However, if you want to do anything with the data, it would be good to stop the script, so you know the search failed and why. Alternatively, if you are doing multiple searches, change the parameter from Stop to SilentlyContinue, so the script continues if a search fails. If you want to see what the error is, you can use Continue as the parameter instead.

Get-ChildItem -Path "~\Documents\*.jpg" -Recurse -ErrorAction SilentlyContinue

If you would rather have the option of controlling what happens each time your script runs, you can change it to Inquire. When your cmdlet hits a snag, it gives options: Yes, Yes For All, Halt Command, Suspend, or Help.

powershell error handling tips

This option is a bit more flexible but does mean errors cause your script to wait for your input. That might not be something you want when you’re running a long process overnight.

Error Handling the Programming Way

The ErrorAction parameter addresses your errors in an uncomplicated way. However, if you are looking for a bit more control over errors, PowerShell still has you covered. Using Try/Catch, we can now branch the script when cmdlets return an error.

powershell error handling tips

As the name suggests, Try/Catch is made up of two parts. (There is technically a third, but we will get to that in a minute.) The first is the Try section. You are going to run your normal code in this section. You are still going to use the -ErrorAction parameter, but it can only be set as Stop. This flag ensures that your cmdlet triggers the Catch–even if it does not have a terminating error.

  Get-Process "Cortana" -ErrorAction Stop

Try can also prevent other cmdlets from running if the search fails. In this case, if you were sending the Get-Process results to Stop-Process, a failed search prevents the second cmdlet from running.

So now that you’ve created a try block of cmdlets, what do you want to do when it fails? Using the Catch half, you are going to define this.

  Write-Host "Process Not Found"

As with the ErrorAction parameter, when you are doing something a bit more complex 3 Clever PowerShell Functions After Upgrading to Windows 10 3 Clever PowerShell Functions After Upgrading to Windows 10 Windows 10 brings us a new PowerShell, essentially Command Prompt on steroids. This article shows you how to do the otherwise impossible with PowerShell. And it's easier than you think! Read More Catch will be useful for more than giving a plain language failure. (In the example above, the failure is forced by using the app name, and not the process name.) So make sure that you play with the Try block to create a search/action you need. You can use the Catch block for your script to email you if it fails.

The third part comes in handy if you want something to run regardless of whether your cmdlet succeeds or not. For this, you can use the Finally block. You add this after Try and Catch and log when a section of your script ends.

The Error Variable and Logging

Your script now controls how it handles errors and how it responds to them. You can use it as a scheduled task, or at least run it when you are not at your desk 5 Reasons You Should Use PowerShell Instead of Batch Scripting 5 Reasons You Should Use PowerShell Instead of Batch Scripting PowerShell is what you'd get if you crossed the Command Prompt with Batch Scripting, threw in some extra features, and kicked it all up several notches. Here are several reasons you should try it. Read More . However, how can you investigate a failed script? With the -ErrorVariable parameter your cmdlet’s errors write to a custom variable. This is an alternative to the system $Error variable, which contains all the errors from the current session.

powershell error handling tips

Your cmdlet needs to get a bit longer. First, define a variable, something like $SearchError will do for the example. When you call SearchError in the ErrorVariable parmeter, you don’t use the dollar sign. Even though you’re calling a variable you created, due to the way the parameter works you call it without the dollar sign. Then add that to the end of the line.

Get-ChildItem -Path "~\Documents\*.jpg" -Recurse -ErrorAction Continue -ErrorVariable SearchError

If you add a + in front of the variable name, you can add to the variable rather than replace it outright. That gets you the same behavior as the global error variable. Instead, you can use this output and Try/Catch to write custom output, and time stamp it.

powershell error handling tips

To make this work, create a text file right after you set the error variable. Do this with the New-Item cmdlet. You may want to use the Inquire option for the ErrorAction parameter. This lets you add to an existing log when the New-Item cmdlet fails.

$SearchLog = New-Item "~\SearchLog.txt" -type file -ErrorAction Inquire

Now when you build your Try/Catch block, you can use the Catch to log to a text file. You use Get-Date to create the timestamp. The formatting can be a tricky so be sure to copy that from the example.

  Get-ChildItem -Path "~\Documents\*.jpg" -Recurse -ErrorAction Stop -ErrorVariable SearchError
  Add-Content -Path $SearchLog -Value "$(Get-Date -Format dd-MM-yy-hh_mm_ss) Files not found returned error: $SearchError"

Repeat that as needed for all your cmdlets 15 Advanced Tasks PowerShell Can Handle in Windows 10 15 Advanced Tasks PowerShell Can Handle in Windows 10 PowerShell is similar to the command prompt, but better. It's a powerful system administration tool. We have compiled 15 tasks, some simple, some complex, that benefit from the magic of PowerShell. Read More , and you now have a nice log of any errors. If you want to track things that run successfully you can add a similar Add-Content at the end of the Try block. This logging only runs when your Try cmdlet succeeds. You can then log your errors and successes with time stamps. The logging now lets you know everything that your script has done, success or failure.

The Power of Code

Using PowerShell on the command line Command Prompt vs. Windows PowerShell: What's the Difference? Command Prompt vs. Windows PowerShell: What's the Difference? Windows users can get by without using either the Command Prompt or PowerShell. But with Windows 10 and new features around the corner, maybe it's about time we learned. Read More is a powerful way to manage your system. You can string those same commands together in a way that allows powerful automation. Proper error handling is necessary to ensure that your scripts only do what you want them to. Logging everything can save you time when troubleshooting.

Is there a time that error handling saved your bacon? Is there a PowerShell script you have that could use some better error handling? What’s your next PowerShell project? Let us know in the comments.

Enjoyed this article? Stay informed by joining our newsletter!

Enter your Email

Leave a Reply

Your email address will not be published. Required fields are marked *

  1. Gyz
    October 28, 2017 at 10:16 am

    I think a better way would be:
    Get-ChildItem -Path "c:\windows\system32\*" -Recurse -ErrorAction SilentlyContinue -ErrorVariable +SearchError
    write-verbose "Some terminating error : $err"
    Add-Content -Path $SearchLog -Value $SearchError
    This way you have all errors in the log and the Try/Catch block catches terminating errors
    You should read the great article from Powershell MVP Mike Shepard regarding this: https://powershellstation.com/2017/10/03/missing-point-powershell-error-handling/

  2. Q
    October 27, 2017 at 8:09 am

    Great article.. definitely will be adding error handling to my scripts

  3. Dave
    October 27, 2017 at 6:29 am

    Great article, thanks!