Test Nested Depth

by May 20, 2015

When you call a function, PowerShell increases the nest level. When a function calls another function, or script, this will again increase the nest level. Here is a function that can tell you the current nest level of your code:

function Test-NestLevel
{
  $i = 1
  $ok = $true
  do
  {
    try
    {
      $test = Get-Variable -Name Host -Scope $i
    }
    catch
    {
      $ok = $false
    }
    $i++
  } While ($ok)
    
  $i
} 

This can be useful if you design functions with recursion (function that call themselves).

Here is sample code that uses this technique:

function Test-Diving
{
    param($Depth)

    if ($Depth -gt 10) { return }

    "Diving deeper to $Depth meters..."
    
    $currentDepth = Test-NestLevel
    "calculated depth: $currentDepth"
    
    
    Test-Diving -depth ($Depth+1)
}


Test-Diving -depth 1

When you run Test-Diving, the function calls itself until a depth of 10 meters is reached. The function uses a parameter to control nest level, but the call to Test-NestLevel returns the exact same number.

Note the difference: Test-NestLevel returns the overall (absolute) nest level, whereas the parameters tells you how often the function called itself. If Test-Diving was embedded inside another function, the absolute and relative nest level would differ:

 
PS C:\> Test-Diving -Depth 1
diving deeper to 1 meters...
calculated depth: 1
diving deeper to 2 meters...
calculated depth: 2
diving deeper to 3 meters...
calculated depth: 3
diving deeper to 4 meters...
calculated depth: 4
diving deeper to 5 meters...
calculated depth: 5
diving deeper to 6 meters...
calculated depth: 6
diving deeper to 7 meters...
calculated depth: 7
diving deeper to 8 meters...
calculated depth: 8
diving deeper to 9 meters...
calculated depth: 9
diving deeper to 10 meters...
calculated depth: 10

PS C:\> & { Test-Diving -Depth 1 }
diving deeper to 1 meters...
calculated depth: 2
diving deeper to 2 meters...
calculated depth: 3
diving deeper to 3 meters...
calculated depth: 4
diving deeper to 4 meters...
calculated depth: 5
diving deeper to 5 meters...
calculated depth: 6
diving deeper to 6 meters...
calculated depth: 7
diving deeper to 7 meters...
calculated depth: 8
diving deeper to 8 meters...
calculated depth: 9
diving deeper to 9 meters...
calculated depth: 10
diving deeper to 10 meters...
calculated depth: 11

PS C:\>  
 

Test-NestLevel always returns the nesting level from the current code to the global scope.

Twitter This Tip! ReTweet this Tip!