Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I get the original expression used to invoke a powershell function?

How would I go about retrieving the original expression used to invoke a Powershell function, from within the function itself? As in, the expression as it was typed/read from the script or command line.

I know that one can use $MyInvocation.Line to retrieve the first line of the invocation expression, however this won't correctly retrieve a multi-line expression.

( This answer only retrieves the first line, or the arguments, not the original expression)

like image 911
Clay Sweetser Avatar asked May 13 '26 13:05

Clay Sweetser


1 Answers

It's really meant for the debugger, but I think you can use Get-PSCallStack for this:

Function Get-Something {
    Param(
        [Parameter(Mandatory = $true)]
        [String]$Param1
    )

    (Get-PSCallStack)[1].Position.Text
}

Get-Something `
1

Multiple lines to call it. The function should return the exact line that was called.

Note: Inside the function I had to reference the second element returned from Get-PSCallStack this is because [0] would be the GetPSCallStack command itself. So, be forewarned, I can see this being finicky if it were nested down a bit.

Get-PSCallStack Documentation

like image 50
Steven Avatar answered May 15 '26 09:05

Steven



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!