Chapter 15. Debugging

 

This chapter covers

  • Creating script instrumentation
  • Capturing session output
  • The PowerShell debugger
  • Command-line debugging
  • Debugging PowerShell jobs, runspaces, and remote scripts

Big Julie: “I had the numbers taken off for luck, but I remember where the spots formerly were.”

Guys and Dolls, words and music by Frank Loesser

No one writes code that always works correctly the first time it’s run. When the worst happens and your code won’t run, or deliver the correct results, you need to debug it to find the problem or problems. Start by adding statements that track your code’s execution and capture session output and then move on to more advanced techniques using the PowerShell debugger on running code. The techniques we’ll show you in this chapter will enable you to find and fix code problems much faster.

Let’s start by looking at how you can provide instrumentation for your scripts so they provide you with diagnostic information.

15.1. Script instrumentation

The most basic form of debugging a script is to put statements in it, using the Write* cmdlets, that display information about the script’s execution. The Write* cmdlets separate your debugging output from the rest of the output by displaying the debugging output directly on the console.

Note

These statements will slow down your code execution because they’ll still be parsed even if they aren’t run. You may need to remove them in production code if execution speed is of paramount importance.

15.2. Capturing session output

15.3. PowerShell script debugging features

15.4. Command-line debugging

15.5. Beyond scripts

15.6. Summary