SoFunction
Updated on 2025-03-10

PowerShell implements the nesting depth of statistical functions

When you call a function, PowerShell adds a nesting hierarchy. When a function calls another function, or script, the nesting level will also be added. Today I'm sharing a function that can tell you the level of nesting of scripts:

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

The above function is very useful when the function you call has recursive calls. Let's take a look at an example of the call:

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 will call itself 10 times. The function uses a parameter to control the nesting hierarchy, and Test-NestLevel is responsible for returning the exact number of depths.

Note that there is a difference here: Test-NestLevel returns an absolute nesting level, and the parameters will record how many times this function is called. If Test-Diving is embedded in another function, the absolute depth and the relative depth will be different.

 

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 will always return the nesting depth from the scope of the current code to the global scope.