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
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
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
Ooo, nice tip Daniel. That’s good stuff right there.
Thanks Daniel - exactly what I needed
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