Chapter 22. Trapping and handling errors

 

Anytime you’re dealing with computers, errors are bound to occur: network problems, permission denied, server not found ... you know what I’m talking about. Fortunately, your PowerShell commands and scripts can plan for those errors and deal with them, rather than spewing out a bunch of red text.

22.1. Dealing with errors you just knew were going to happen

To be clear, I’m not talking about errors that you make, such as typos, using the wrong syntax, or something like that. Your errors are called bugs, and we’ll deal with those in the next chapter. This chapter is going to deal with the errors that are out of your control, but that you can usually anticipate. Here are some examples:

  • A “file not found” error
  • A “permission denied” error
  • The “RPC server not found” error that Get-WmiObject can produce
  • Other errors related to network connectivity

You can’t necessarily prevent these errors from happening, but when they happen you may want to take some specific action. For example, you might want to log the names of computers that can’t be reached, or prompt for a different filename if the one specified can’t be found. PowerShell offers you a number of ways to deal with these kinds of errors, and we’ll cover the two most commonly used ways in this chapter.

22.2. Errors and exceptions

First, we need to get some terminology straight. Try running this command:

Get-WmiObject Win32_BIOS -computer notonline,localhost

22.3. The $ErrorActionPreference variable

22.4. The -ErrorAction parameter

22.5. Using a Trap construct

22.6. Trap scope

22.7. Using a Try construct

22.8. The -ErrorVariable parameter

22.9. Common points of confusion

22.10. Lab

22.11. Ideas for on your own