For example:
function Foo {
[string]$functionName = commandRetrievesFoo
Write-Host "This function is called $functionName"
}
Output:
PS > Foo
This function is called foo
For example:
function Foo {
[string]$functionName = commandRetrievesFoo
Write-Host "This function is called $functionName"
}
Output:
PS > Foo
This function is called foo
You can use $MyInvocation
which contains some useful information about what is currently executed.
function foo {
'This function is called {0}.' -f $MyInvocation.MyCommand
}
gv -sc $_ myinvocation
. See jtruher.spaces.live.com/blog/cns!7143DA6E51A2628D!172.entry
Sep 13, 2010 at 3:24
(Get-PSCallStack | Select-Object FunctionName -Skip 1 -First 1).FunctionName
and 2) (Get-Variable MyInvocation -Scope 1).Value.MyCommand.Name
. I tried running each in a loop 1000 times to see how long each took. The Get-Variable... method takes about half the time of the Get-PSCallStack... method.
Mar 22, 2017 at 1:05
$MyInvocation
cannot be used to get the name of a function within a class. To do this, I needed to use Get-PSCallStack)[0].FunctionName
When you are in a function you can access the automatic variable $PSCmdLet.
This is an extremely useful variable that holds a lot of information about the currently executing cmdlet.
In our scenario we wanted the name and the definition of the current function for some recursion. $MyInvocation was null because the function was within a PowerShell module.
However, there is a "MyInvocation" property on the PSCmdLet object which contains all the information needed and allowed our scenario to run.
e.g. $PSCmdlet.MyInvocation.MyCommand.Name = The name of the function $PSCmdlet.MyInvocation.MyCommand.Definition = The definition of the function
$PSCmdlet
appears to only work if the function has an explicit [CmdletBinding()]
attribute.
Contains an object that represents the cmdlet or advanced function that is being run
. So it only works with advanced functions, which have the CmdletBindingAttribute, not normal functions.
Jan 17, 2018 at 5:27
Easy.
function Get-FunctionName ([int]$StackNumber = 1) {
return [string]$(Get-PSCallStack)[$StackNumber].FunctionName
}
By default Get-FunctionName in the example will get the name of the function that called it.
Function get-foo () {
Get-FunctionName
}
get-foo
#Reutrns 'get-foo'
Increasing the StackNumber parameter will get the name of the next function call up.
Function get-foo () {
Get-FunctionName -StackNumber 2
}
Function get-Bar () {
get-foo
}
get-Bar
#Reutrns 'get-Bar'
The Get-PSCallStack
option seems to work only once: when calling a function from the body of the script, the first time it will retrieve the script name, but the second time it will retrieve the text ''
Get-PSCallStack | Select-Object FunctionName -Skip 1 -First 1
to get the name of the calling function. If the current function is called from the top level script this will return '<ScriptBlock>'.
Mar 22, 2017 at 0:33