Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to retrieve a PowerShell function name from within a function?

For example:

function Foo {      [string]$functionName = commandRetrievesFoo     Write-Host "This function is called $functionName" } 

Output:

PS > Foo This function is called foo 
like image 834
alphadev Avatar asked Sep 11 '10 02:09

alphadev


People also ask

How do you call a PowerShell function name?

If you are on PowerShell 2.0 use (Get-PSCallStack)[1]. Command . I've come across two methods of getting the calling function name: 1) (Get-PSCallStack | Select-Object FunctionName -Skip 1 -First 1). FunctionName and 2) (Get-Variable MyInvocation -Scope 1).

How do I get the contents of a function in PowerShell?

To use the Get-Content cmdlet to display the contents of a function, you enter Get-Content and supply the path to the function. All functions available to the current Windows PowerShell environment are available via the Function Windows PowerShell drive.

Can you have a function within a function in PowerShell?

In a standard Windows PowerShell script or function, names of nested functions can be reused. Calls invoke the last function defined with the specific name before the call.

What is MyInvocation in PowerShell?

$MyInvocation Contains information about the current command, such as the name, parameters, parameter values, and information about how the command was started, called, or invoked, such as the name of the script that called the current command. $MyInvocation is populated only for scripts, function, and script blocks.


Video Answer


1 Answers

You can use $MyInvocation which contains some useful information about what is currently executed.

function foo {     'This function is called {0}.' -f $MyInvocation.MyCommand } 
like image 109
Joey Avatar answered Sep 17 '22 02:09

Joey