3 min read

Debugging PowerShell in VS Code

Visual Studio Code (VS Code) is the de facto standard editor for PowerShell. Its integrated debugger allows you to step through code, inspect variables, and troubleshoot issues efficiently.

Parent Topic: PowerShell Scripting and Programming Related: PowerShell Comprehensive Guide

1. Prerequisites

  1. Visual Studio Code: Installed.
  2. PowerShell Extension: The official Microsoft extension must be installed and enabled.

2. The Basics of Debugging

Setting Breakpoints

A breakpoint tells the debugger to pause execution at a specific line.

  • Click in the gutter (the space to the left of the line numbers) next to the line you want to pause on.
  • A red dot will appear.

Starting the Debugger

  • Open the script you want to debug.
  • Press F5 (or go to Run > Start Debugging).
  • The script will run until it hits your breakpoint.

3. Debugging Controls

Once paused, a toolbar appears at the top:

  • Continue (F5): Resume execution until the next breakpoint.
  • Step Over (F10): Execute the current line and pause at the next line in the current file. (Skips going inside functions called on that line).
  • Step Into (F11): Execute the current line. If it's a function call, pause at the first line inside that function.
  • Step Out (Shift+F11): Finish the current function and pause immediately after it returns.
  • Restart (Ctrl+Shift+F5): Stop and restart the script.
  • Stop (Shift+F5): Terminate the debugger.

4. Inspecting State

When paused, the Run and Debug view (Ctrl+Shift+D) on the left sidebar provides critical info:

Variables

Shows the current value of all variables in scope (Local, Script, Global). You can expand objects to see their properties.

Watch

Allows you to track specific expressions.

  • Click + and type a variable name (e.g., $i) or an expression (e.g., $i + 5).
  • The value updates in real-time as you step through code.

Call Stack

Shows the chain of function calls that led to the current location. Useful for understanding "how did I get here?".

Debug Console

The Debug Console (bottom panel) is an interactive shell running in the current context of the paused script.

  • You can type commands to check values or run ad-hoc code using the script's current variables.
  • Example: Type $User.Name to see the value, even if you aren't hovering over it.

5. Launch Configurations (launch.json)

For complex scenarios (e.g., passing arguments to a script), you need a launch configuration.

  1. Go to the Run and Debug view.
  2. Click create a launch.json file.
  3. Select PowerShell.

This creates a .vscode/launch.json file. You can modify the "PowerShell: Launch Script" configuration:

{
    "name": "PowerShell: Launch Script with Args",
    "type": "powershell",
    "request": "launch",
    "script": "${file}",
    "args": ["-UserName", "jdoe", "-Verbose"],
    "cwd": "${workspaceFolder}"
}

Return to PowerShell Scripting and Programming