Chapter 14. Debugging


While developing scripts and functions, you’ll often find yourself running into behavior that you didn’t intend. This is a natural part of software development, and the path to diagnosing these issues is the fine art known as debugging.

For the simplest of problems, a well-placed call to Write-Host can answer many of your questions. Did your script get to the places you thought it should? Were the variables set to the values you thought they should be?

Once problems get more complex, print-style debugging quickly becomes cumbersome and unwieldy. Rather than continually modifying your script to diagnose its behavior, you can leverage PowerShell’s much more extensive debugging facilities to help you get to the root of the problem.

PS > Set-PsBreakPoint .\Invoke-ComplexDebuggerScript.ps1 -Line 14 ID Script Line Command Variable Action -- ------ ---- ------- -------- ------ 0 Invoke-Comple... 14 PS > .\Invoke-ComplexDebuggerScript.ps1 Calculating lots of complex information 1225 89 Entering debug mode. Use h or ? for help. Hit Line breakpoint on 'Z:\Documents\CookbookV2\chapters\current\PowerShellCookbook\Invoke-Complex DebuggerScript.ps1:14' Invoke-ComplexDebuggerScript.ps1:14 $dirCount = 0 PS > ? s, stepInto Single step (step into functions, scripts, etc.) v, stepOver Step to next statement (step over functions, scripts, etc.) o, stepOut Step out of the current function, script, etc. c, continue Continue execution q, quit Stop execution and exit the ...

Get Windows PowerShell Cookbook, 2nd Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.