🎓 A1Learner
🔍
0 of 46 lessons completed

PowerShell Conditional Breakpoints

A conditional breakpoint is a breakpoint that only acts when a condition is true. The condition is checked each time the function runs, and this lesson counts only the runs that meet the condition.

Count every hit with an action

The action runs on every call. Two calls give a count of two.

$script:hitCount = 0
function Get-Double { param([int]$n) $n * 2 }
$breakpoint = Set-PSBreakpoint -Command "Get-Double" -Action { $script:hitCount++ }
Get-Double -n 5 | Out-Null
Get-Double -n 6 | Out-Null
"hits: $script:hitCount"

Count only large inputs

An if statement inside the action skips small inputs. Only the two large inputs are counted.

$script:bigHits = 0
function Get-Double { param([int]$n) $n * 2 }
$breakpoint = Set-PSBreakpoint -Command "Get-Double" -Action { if ($n -gt 10) { $script:bigHits++ } }
Get-Double -n 5 | Out-Null
Get-Double -n 20 | Out-Null
Get-Double -n 30 | Out-Null
"big hits: $script:bigHits"

Record which inputs matched

The action can record a value as well as count it. Small inputs leave no record.

$script:seen = @()
function Get-Double { param([int]$n) $n * 2 }
$breakpoint = Set-PSBreakpoint -Command "Get-Double" -Action { if ($n -gt 10) { $script:seen += $n } }
Get-Double -n 5 | Out-Null
Get-Double -n 20 | Out-Null
Get-Double -n 30 | Out-Null
$script:seen -join ", "

Example

$script:bigHits = 0
$script:seen = @()
function Get-Double { param([int]$n) $n * 2 }
$breakpoint = Set-PSBreakpoint -Command "Get-Double" -Action { if ($n -gt 10) { $script:bigHits++; $script:seen += $n } }
Get-Double -n 4 | Out-Null
Get-Double -n 15 | Out-Null
Get-Double -n 25 | Out-Null
"big hits: $script:bigHits"
"seen: $($script:seen -join ", ")"

Key points

  • Conditional breakpoint: a breakpoint with an action that runs only for matching calls.
  • Action: a small script block that runs when a breakpoint is hit.
  • Use Set-PSBreakpoint -Action to run a script block each time a breakpoint is hit.
  • Use an if statement inside the action to count only matching calls.
  • Use $script: for a counter that the action and the main script both share.

In this example, the action checks each input, counts only the inputs greater than 10, records those inputs, and the two print lines show the count and the recorded inputs.

Note

An action without a pause step lets the function keep running after the action finishes.

Try it Yourself

Edit the code, then press Run.

Running is simulated

Exercise

A conditional breakpoint action counts calls where the input is greater than 10. Calls use 5, 20, and 30. What is the count?