Chapter 10. Error handling

 

The Get-SystemInfo function we wrote earlier was designed from the outset to log the names of computers it failed to reach. In this chapter, we’ll make that happen, through a set of techniques collectively known as error handling.

10.1. It’s all about the action

Whenever a PowerShell command—be it a native cmdlet or a function you write—encounters a non-terminating error, it asks PowerShell what to do. PowerShell looks at a built-in variable, $ErrorActionPreference, to see what it should do.

Before we dive into that, let’s talk about this non-terminating error thing. It’s any error that presents a problem, but one from which the command can recover and continue. “Hey, this computer was unreachable, but if you want, I can continue trying with the next computer in the list.” That’s different than a terminating error, which means everything will stop completely.

So what does $ErrorActionPreference do? It can be set to one of four values:

10.2. Setting the error action

10.3. Saving the error

10.4. Error handling v1: Trap

10.5. Error Handling v2+: Try...Catch...Finally

10.6. Providing some visuals

10.7. Coming up next

10.8. Labs