Private/Get-ParentFunction.ps1

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
Function Get-ParentFunction {
    <#
    .SYNOPSIS
    Returns details of the calling function from a variable scope

    .DESCRIPTION
    Returns the FunctionName and the ParameterSetName which was used to invoke another function

    .PARAMETER Scope
    The Scope number from which to return the calling functions details.

    .EXAMPLE
    Function Test-Parent {Test-Child}
    Function Test-Child {Get-ParentFunction}
    $example = Test-Parent

    $example.FunctionName #Returns Test-Parent

    .EXAMPLE
    Function Test-Example {
        [CmdletBinding()]
        param([parameter(ParameterSetName = "ExampleParamSet")][string]$Name)
            Test-Parent
    }
    Function Test-Parent {Test-Child}
    Function Test-Child {Get-ParentFunction -Scope 3}
    $example = Test-Example -Name "test"

    $example.Function #Returns "Test-Example"
    $example.ParameterSetName #Returns "ExampleParamSet"

    .NOTES

    #>

    [CmdletBinding()]
    Param(
        # The scope number from which to retrieve the parent function name
        [Parameter(
            Mandatory = $false,
            ValueFromPipelineByPropertyName = $true
        )]
        [Int]
        $Scope = 2
    )

    [PSCustomObject]@{
        FunctionName     = (Get-Variable MyInvocation -Scope $Scope).Value.MyCommand.Name
        ParameterSetName = (Get-Variable PSCmdlet -Scope $Scope -ErrorAction SilentlyContinue).Value.ParameterSetName
    }

}