PSCmdlet, how to get calling function's name

Hello all. I’m writing a PSCmdlet in C# (using .NET Core 3.1 based on PS7) and I am having difficulty getting the calling function’s name within PSCmdlet.

If this were a Powershell Cmdlet, I would use the following to get the calling function name (if it exists):

$CallStack = Get-PSCallStack
if ($CallStack.Count -gt 1) {
    $functionName = $CallStack[1].FunctionName
}

return $functionName

However, if I try invoking ‘Get-PSCallStack’ in C#, it would not work because it would create a new PowerShell session and thus, there would never be a calling function:

using PowerShell ps = PowerShell.Create();
ps.AddScript("(Get-PSCallStack)");
Collection<PSObject> stdout = ps.Invoke();


Is there anyway to write a C# PSCmdlet and get the call stack when calling from Powershell sessions?

If I remember right this should be all you need:

$MyInvocation.MyCommand.Name.ToString()

In Powershell that should be enough:

$MyInvocation.MyCommand.Name.ToString()

Hello Olaf, it would appear that in the C# PSCmdlet:

Console.WriteLine(this.MyInvocation.MyCommand.Name);

The following will return the current function name, not the calling function.

 

 

Removed; double reply.

 

So I’ve tried using the C# StackTrace, but unfortunately it just returns the C# stack trace (which in hindsight is what I should’ve expected). Workaround solution is to implement a PowerShell function that acts as a wrapper and to call the C# PSCmdlet with the PS call stack.

 

$CallStack = Get-PSCallStack
if ($CallStack.Count -gt 1) {
    $functionName = $CallStack[1].FunctionName
}
 
// Assuming Get-Foo is your C# PSCmdlet that requires the PS Callstack name
Get-Foo -PSCallingFunction $functionName