萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> 程式語言綜合

PowerShell 統計函數呼叫巢狀深度:Get-Variable Scope 遞迴檢測實作

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 為自動變數,存在於每個作用域
  • 嘗試存取不存在的作用域會拋出例外,作為終止條件
  • 回傳值為絕對深度(到全域),而非相對遞迴層數
copyright © 萬盛學電腦網 all rights reserved