检查函数是否在递归函数调用中

时间:2016-05-02 18:07:49

标签: .net function powershell recursion

Powershell中是否有任何方法可以让函数知道它是否已从它自己调用?

是否可以知道当前函数的深度是多少?我可以用反射的东西来做这件事,还是我必须通过设置旗帜或其他东西自己做?

1 个答案:

答案 0 :(得分:8)

使用Get-PSCallStack(在3.0版中引入),您可以进行简单的"递归检查"通过将callstack中的最后一个条目与当前命令名称进行比较:

if((Get-PSCallStack)[1].Command -eq $MyInvocation.MyCommand)
{
    Write-Warning "Function was likely called by itself"
}
  

是否可以知道当前函数的深度是多少?

是的,您可以遍历调用堆栈并计算当前调用堆栈之前的嵌套调用次数(当您爬入兔子洞时,这会变得非常缓慢)

考虑这个例子:

function Invoke-Recurse
{
    param(
        [Parameter()]
        [ValidateRange(0,10)]
        [int]$Depth = 5
    )

    $CallStack = @(Get-PSCallStack)
    $Caller    = $CallStack[1].Command
    $Self      = $CallStack[0].Command

    if($Caller -eq $Self)
    {
        for($i = 1; $i -lt $CallStack.Count; $i++)
        {
            if($CallStack[$i].Command -ne $Self)
            {
                $RecursionLevel = $i - 1
                break
            }
        }
        Write-Warning "Recursion detected! Current depth: $RecursionLevel; Remaining iterations: $Depth"
    }

    if($Depth -lt 1)
    {
        return $true
    }
    else
    {
        return Invoke-Recurse -Depth $($Depth - 1)
    }
}

你会看到:

PS C:\> Invoke-Recurse
WARNING: Recursion detected! Current depth: 1; Remaining iterations: 4
WARNING: Recursion detected! Current depth: 2; Remaining iterations: 3
WARNING: Recursion detected! Current depth: 3; Remaining iterations: 2
WARNING: Recursion detected! Current depth: 4; Remaining iterations: 1
WARNING: Recursion detected! Current depth: 5; Remaining iterations: 0
Done!
相关问题