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
New-PsSession -ComputerName SRV01 -ErrorVariable +a