15 Errors and how to deal with them
You have much functionality yet to write in the tool you’ve been building, and we’ve been deferring a lot of it to this point. 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 eBook, The Big Book of PowerShell Error Handling, which dives into this topic from a more technical reference perspective (https://powershell.org/free-resources/). We recommend checking it out once you’ve completed this tutorial-focused chapter.
15.1 Understanding Errors and Exceptions
PowerShell defines two broad types of bad situations: errors and exceptions. Because most PowerShell commands are designed to deal with multiple things at once, and because a problem with one thing doesn’t mean you want to stop dealing with all the other things, PowerShell tries to err on the side of “keep going until it breaks.” So, PowerShell will often emit an error when something goes wrong in a command and keep going. For example
Get-Service -Name BITS, Nobody, WinRM
Figure 15.1 Error message for Nobody service