How to Get Current Function Name in PowerShell?

Do you want to get the current PowerShell function name? In this PowerShell tutorial, I will explain how to get the current function name in PowerShell.

Get the Current Function Name in PowerShell

 A function in PowerShell is a block of code with a name that performs a specific task. You declare a function using the function keyword followed by the function name and a pair of curly braces containing the code to be executed.

Here’s a simple example of a PowerShell function:

function Get-HelloWorld {
    "Hello, World!"
}

When you call Get-HelloWorld, it returns the string “Hello, World!”.

To retrieve the current function’s name, you can use the automatic variable $MyInvocation. This variable contains information about the current command, such as its name, parameters, and invocation options.

Here’s a basic example of using $MyInvocation to get the function name:

function Get-FunctionName {
    $MyInvocation.MyCommand.Name
}

When you call Get-FunctionName, it will return the name of the function, which is “Get-FunctionName”.

Let’s say you’re writing a script with multiple functions, and you want to include the function names in your debug output. You can use $MyInvocation to help with this.

function Start-ProcessTask {
    Write-Debug "Entering function: $($MyInvocation.MyCommand.Name)"
    # Process task code here
    Write-Debug "Exiting function: $($MyInvocation.MyCommand.Name)"
}

function Start-BackupTask {
    Write-Debug "Entering function: $($MyInvocation.MyCommand.Name)"
    # Backup task code here
    Write-Debug "Exiting function: $($MyInvocation.MyCommand.Name)"
}

When you run these functions with debugging enabled, this will output debug information with the function names.

In more complex scenarios, such as when functions call other functions, you might want to know not just the current function name but also which function called it. PowerShell provides the Get-PSCallStack cmdlet for this purpose.

Here’s an example of how to use Get-PSCallStack:

function InnerFunction {
    $caller = (Get-PSCallStack)[1].FunctionName
    "This is InnerFunction, called by $caller"
}

function OuterFunction {
    InnerFunction
}

When you call OuterFunctionInnerFunction will output “This is InnerFunction, called by OuterFunction”.

Conclusion

Retrieving the current function name in PowerShell can be incredibly useful for debugging and logging purposes. By using $MyInvocation and the Get-PSCallStack cmdlet, you can easily identify which function is running and how it was called. In this PowerShell tutorial, I have explained how to get the current function name in PowerShell.

You may also like:

>