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)
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With