Chapter 15. Dealing with errors

 

You have a lot of 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/ebooks). 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 situation: an error and an exception. Because most PowerShell commands are designed to deal with multiple things at once, and because in many cases 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 “just keep going.” So, often, when something goes wrong in a command, PowerShell will emit an error and keep going. For example

Get-Service -Name BITS,Nobody,WinRM

There’s no service named Nobody, so PowerShell will emit an error on that second item. But by default, PowerShell will keep going and process the third item in the list. When PowerShell is in this keep-going mode, you can’t have your code respond to the problem condition. If you want to do something about the problem, you have to change PowerShell’s default response to this kind of non-terminating error.

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