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 capturing, dealing with, logging, and otherwise handling errors the tool may encounter.

Note

PowerShell.org offers a free e-book, 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

15.2 Bad handling

15.3 Two reasons for exception handling

15.4 Handling exceptions in your tool

15.5 Capturing the exception

15.6 Handling exceptions for non-commands

15.7 Going further with exception handling

15.8 Your turn

15.8.1 Start here

15.8.2 Your task

15.8.3 Our take

Summary