When you call a function, the PowerShell increases the nesting level one at a time. When a function calls another function, or a script, it increases the nesting level. Share a function today that tells you the nesting level of the script:
function Test-nestlevel
{
$i = 1
$ok = $true
do
{
try
{
$test = Get-variable-name Host -scope $i
}
catch
{
$ok = $false
}
$i + +
} while ($ok)
$i
}
When you call a function that has a recursive call, the above function is useful to see an example of an invocation:
function test-diving
{
param ($Depth)
if ($Depth-gt) {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 10 times. function uses a parameter to control the nesting level, and Test-nestlevel is responsible for returning the exact number of depths.
Note that there is a difference: Test-nestlevel returns an absolute nesting level, and the argument records how many times the function calls itself. If the test-diving is embedded in another function, the absolute depth and relative depth are different.
PS c:\> test-diving-depth 1 Diving deeper to 1 meters ... calculated depth:1 Diving to 2 deeper ... meters Depth:2 diving deeper to 3 meters calculated depth:3 diving deeper to 4 meters ... calculated depth:4 diving deeper T o 5 meters ... calculated depth:5 diving deeper to 6 meters ... calculated depth:6 diving to 7 deeper ... meters Depth:7 diving deeper to 8 meters ... calculated depth:8 diving deeper to 9 meters ... calculated-depth:9 diving deeper To ten meters ... calculated depth:10 PS c:\> & {test-diving-depth 1} Diving deeper to 1 meters ... calculated D Epth:2 diving deeper to 2 meters ... calculated depth:3 diving deeper to 3 meters ... calculated depth:4 the diving to 4 meters ... calculated depth:5 diving deeper to 5 meters ... calculated depth:6 diving to 6 deeper ... meters Depth:7 diving deeper to 7 meters calculated depth:8 diving deeper to 8 meters ... calculated depth:9 diving deeper T o 9 meters ... calculated Depth:10 diving deeper to meters calculated depth:11 PS c:\>
The
Test-nestlevel always returns the nesting depth from the scope of the current code to the global scope.