PowerShell 每層函數呼叫建立新作用域。透過 Get-Variable -Scope N 逐層嘗試存取自動變數 Host,直到拋出例外為止,即可計算當前絕對巢狀深度。適用於遞迴函數除錯與呼叫鏈分析。
function Test-NestLevel {
$i = 1
$ok = $true
do {
try {
$test = Get-Variable -Name Host -Scope $i
}
catch {
$ok = $false
}
$i++
} while ($ok)
return $i
}
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
Diving deeper to 1 meters...
calculated depth: 1
Diving deeper to 2 meters...
calculated depth: 2
...
Diving deeper to 10 meters...
calculated depth: 10
# 直接呼叫
Test-Diving -Depth 1
# 深度 1~10
# 匿名腳本區塊包裹
& { Test-Diving -Depth 1 }
# 深度 2~11(外層腳本區塊增加一層)
Get-Variable -Scope N:0=當前、1=父作用域、...、全域Host 為自動變數,存在於每個作用域