24 Handling errors

 

In this chapter, we’ll focus on how to capture, deal with, log, and otherwise handle errors the tool may encounter.

Note

PowerShell.org offers a free e-book called The Big Book of PowerShell Error Handling, which dives into this topic from a more technical reference perspective, at https://devopscollective.org/ebooks/. We recommend checking it out once you’ve completed this tutorial-focused chapter.

Before we get started, there are two variables that we need to get comfortable with. The first is the $Error automation variable. This contains an array of error objects that have occurred in your current session, with the most recent error object showing up at $Error[0]. By default, all errors will be put into this variable. You can change this behavior by setting your ErrorAction common parameter to Ignore. You can get more information about automatic variables by running get-help about_automatic_variables.

The second built-in variable that you can use is the common parameter variable ErrorVariable. This is an object that you can send errors to, so you can use them at a later time if needed (e.g., for writing to a log file):

New-PsSession -ComputerName SRV01 -ErrorVariable a

ErrorVariable will only hold the most recent error unless you add a + (plus) sign in front of it:

New-PsSession -ComputerName SRV01 -ErrorVariable +a
NOTE

We did not use the $ in front of the error variable because it is not needed here.

24.1 Understanding errors and exceptions

24.2 Bad handling

24.3 Two reasons for exception handling

24.4 Handling exceptions

24.5 Handling exceptions for noncommands

24.6 Going further with exception handling

24.7 Lab

24.8 Lab answer