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.
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.
First, we need to get some terminology straight. Try running this command: