Discovering Nesting Level

by Apr 10, 2019

Get-PSCallStack returns a so-called “Call Stack” which – in its simplest form – tells you the nesting depth of your code: there will be a new object added to the stack each time you enter a script block. Have a look:

function test1
{
    $callstack = Get-PSCallStack
    $nestLevel = $callstack.Count - 1   
    "TEST1: Nest Level: $nestLevel"    
    test2
}

function test2
{
    $callstack = Get-PSCallStack
    $nestLevel = $callstack.Count - 1
    "TEST2: Nest Level: $nestLevel"    
}

# calls test1 which in turn calls test2
test1
# calls test2 directly
test2

In this sample, you have two functions which use Get-PSCallStack to determine their “nest level”. When you run test1, it in turn runs test2, so test2 is running at nest level 2. When you call test2 directly, however, it runs at nest level 1:

 
TEST1: Nest Level: 1
TEST2: Nest Level: 2
TEST2: Nest Level: 1
 

Here is a more useful example of the same technique: a recursive function call that stops at a nest level of ten:

function testRecursion
{
    $callstack = Get-PSCallStack
    $nestLevel = $callstack.Count - 1
    "TEST3: Nest Level: $nestLevel"
    
    # function calls itself if nest level is below 10
    if ($nestLevel -lt 10) { testRecursion }

}

# call the function
testRecursion

Here is the result:

 
TEST3: Nest Level: 1
TEST3: Nest Level: 2
TEST3: Nest Level: 3
TEST3: Nest Level: 4
TEST3: Nest Level: 5
TEST3: Nest Level: 6
TEST3: Nest Level: 7
TEST3: Nest Level: 8
TEST3: Nest Level: 9
TEST3: Nest Level: 10
 

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!