Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if function is inside a recursive function call

Is there any way in Powershell for a function to know if it has been called from itself?

Is it possible to know how many levels deep the current function is? Can I do this with reflection stuff or will I have to do it myself by setting a flag or something?

like image 683
red888 Avatar asked Feb 26 '26 05:02

red888


1 Answers

Using Get-PSCallStack (introduced in version 3.0), you can hack a simple "recursion check" together by comparing the last entry in the callstack with the current command name:

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

Is it possible to know how many levels deep the current function is?

Yes, you can walk through the call stack and count how many nested invocations preceded the current one (this is gonna get super slow as you climb down into the rabbit hole)

Consider this example:

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)
    }
}

And you'll see:

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!
like image 176
Mathias R. Jessen Avatar answered Feb 27 '26 20:02

Mathias R. Jessen