Get parent function name

This topic contains 5 replies, has 4 voices, and was last updated by Profile photo of Nathan Todd Nathan Todd 3 weeks, 2 days ago.

Viewing 6 posts - 1 through 6 (of 6 total)
  • Author
    Posts
  • #52929
    Profile photo of David Zemdegs
    David Zemdegs
    Participant

    I have a script called x.ps1 which contains a function called Parent. This function calls another function called Child (which is located in a separate module).
    In the Child function I want to retrieve the name of the script and the name of the parent function.
    I can get the script name (Get-ChildItem $MyInvocation.PSCommandPath | Select -Expand Name).
    I cannot find out how to get the name of the parent function from within the child function.

    Thanks

    #52938
    Profile photo of Curtis Smith
    Curtis Smith
    Participant

    I think you are going to have to pass it in as a parameter

    Here's an example:

    cls
    function parent {
        child $MyInvocation.MyCommand, "SomeOtherStuff"
    }
    
    function child {
        Param (
            [string]$PFunc,
            [string]$OtherParam
        )
        $PFunc
        $OtherParam
    }
    
    $a = parent
    $a
    #52940
    Profile photo of Daniel Krebs
    Daniel Krebs
    Participant

    You can use Get-PSCallStack since PowerShell v3 to access information about the parent function.

    cls
    function parent {
        child 
    }
    
    function child {
        $callStack = Get-PSCallStack
        if ($callStack.Count -gt 1) {
            'Parent function: {0}' -f $callStack[1].FunctionName
        }
    }
    
    parent
    
    #52942
    Profile photo of Curtis Smith
    Curtis Smith
    Participant

    Ooo, nice tip Daniel. That's good stuff right there.

    #52944
    Profile photo of David Zemdegs
    David Zemdegs
    Participant

    Thanks Daniel – exactly what I needed 🙂

    #53801
    Profile photo of Nathan Todd
    Nathan Todd
    Participant

    This can also be done using the $MyInvocation variable by specifying the scope:

    function child
    {
        "Parent Function Name: $((Get-Variable MyInvocation -Scope 1).Value.MyCommand.Name)"
    }
    
    function parent
    {
        child
    }
    
    parent
    

    Scope 0 = Current Scope
    Scope 1 = Parent Scope

    about_Scopes

Viewing 6 posts - 1 through 6 (of 6 total)

You must be logged in to reply to this topic.