Understanding Set-PSBreakpoint in PowerShell
Welcome back to Wahmans PowerShell Blog! Today we are diving into a versatile debugging cmdlet: Set-PSBreakpoint
. This powerful-tool allows you to pause script execution at a specific line, command, or when a specific variable changes. It’s extremely useful when you’re troubleshooting complex scripts or learning how different parts of your code work.
According to Microsoft, Set-PSBreakpoint
“Sets a breakpoint on a line, command, or variable.” Let’s explore how to put it to use in your PowerShell toolbelt—from beginner-friendly examples to more advanced scenarios.
Example 1: Set a Line Breakpoint (Beginner)
Setting a breakpoint on a specific line in a script file is perfect for diving into your script incrementally.
# myscript.ps1
Write-Output "Start"
$a = 5
$b = $a * 2
Write-Output $b
Write-Output "End"
# Set a line breakpoint on line 4
Set-PSBreakpoint -Script "myscript.ps1" -Line 4
When running myscript.ps1
in the debugger, execution will pause at line 4 so you can inspect variables or step through the code.
Example 2: Command Breakpoint
Suppose you want to pause every time a specific command like Get-Process
is called. You can set a command breakpoint like so:
Set-PSBreakpoint -Command "Get-Process"
Now running any script or command using Get-Process
will trigger the breakpoint allowing you to investigate what’s happening.
Example 3: Variable Breakpoint (Intermediate)
Variable breakpoints pause execution when a specific variable is accessed or changed—super useful when tracking down unexpected values.
# myscript.ps1
$a = 1
for ($i = 0; $i -lt 10; $i++) {
$a = $i * 2
Write-Output $a
}
# Set a breakpoint when variable $a is written to
Set-PSBreakpoint -Variable a -Mode Write
This pauses execution every time $a
is updated, so you can see when and how its value changes.
Example 4: Advanced Debugging with Multiple Breakpoints
Here’s a more advanced example using a combination of breakpoints for comprehensive debugging insight.
# Combine line, command, and variable breakpoints
Set-PSBreakpoint -Script "advancedscript.ps1" -Line 10
Set-PSBreakpoint -Command "Invoke-WebRequest"
Set-PSBreakpoint -Variable "response" -Mode Write
Imagine your script is making API calls. These breakpoints can help you monitor when the request happens and observe how the response is handled.
Conclusion
Whether you’re debugging a small one-liner or a massive automation script, Set-PSBreakpoint
offers flexible control over script execution. Combine different types of breakpoints for powerful debugging workflows.
Happy scripting, and I will see you in the next post!
Leave a Reply