Using Variable Breakpoints (Part 2)

In the previous tip we examined Set-PSBreakpoint to create dynamic variable breakpoints in PowerShell. We showed how a breakpoint can trigger when a variable changes.

However, what if you want to monitor the change of object properties? Let’s assume you want to monitor the size of an array, and break into the debugger when it grows too large.

In this scenario, the PowerShell variable never changes. It is the object inside the variable that changes. Which is why you need a “Read” mode breakpoint rather than a “Write” mode breakpoint:

# break when $array’s length is greater than 10
Set-PSBreakpoint -Variable array -Action { if ($array.Length -gt 10) { break }} -Mode Read -Script $PSCommandPath

$array = @()
do
{
    $number = Get-Random -Minimum -20 -Maximum 20
    "Adding $number to $($array.count) elements"
    $array += $number
    
} while ($true)

This script breaks into the debugger once the array in $array has more than 10 elements. Don’t forget to press SHIFT+F5 to exit the debugger.


psconf.eu – PowerShell Conference EU 2019 – June 4-7, Hannover Germany – visit www.psconf.eu There aren’t too many trainings around for experienced PowerShell scripters where you really still learn something new. But there’s one place you don’t want to miss: PowerShell Conference EU – with 40 renown international speakers including PowerShell team members and MVPs, plus 350 professional and creative PowerShell scripters. Registration is open at www.psconf.eu, and the full 3-track 4-days agenda becomes available soon. Once a year it’s just a smart move to come together, update know-how, learn about security and mitigations, and bring home fresh ideas and authoritative guidance. We’d sure love to see and hear from you!

Twitter This Tip! ReTweet this Tip!

GD Star Rating
loading...