Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

$MyInvocation.Statement in PowerShell 5.1?

$MyInvocation.Statement Property was added in PowerShell v7.4.0-preview.2 (PR #19027) and represents the "The full text of the invocation statement":

function Get-Statement {
    param($MyParam)

    $MyInvocation.Statement
}

Get-Statement @(
    'foo'
    'bar'
    'baz')

Outputs:

Get-Statement @(
    'foo'
    'bar'
    'baz')

Is it possible to get the same value in Windows PowerShell 5.1?

like image 217
Santiago Squarzon Avatar asked Oct 30 '25 03:10

Santiago Squarzon


1 Answers

$MyInvocation.Statement is retrieved from ScriptPosition.Text property (InvocationInfo.cs#L274-L284):

        /// <summary>
        /// The full text of the invocation statement, may span multiple lines.
        /// </summary>
        /// <value>Statement that was entered to invoke this command.</value>
        public string Statement
        {
            get
            {
                return ScriptPosition.Text;
            }
        }

ScriptPosition is an internal property and has been available in previous versions including Windows PowerShell 5.1. We can use reflection to get the property value and from there the value of the .Text property. We can also add a script property via Update-TypeData to $MyInvocation:

$updateTypeDataSplat = @{
    MemberType = 'ScriptProperty'
    TypeName   = 'System.Management.Automation.InvocationInfo'
    MemberName = 'Statement'
}

Update-TypeData @updateTypeDataSplat -Value {
    if (-not $script:_scriptPosition) {
        # cache the PropertyInfo
        $script:_scriptPosition = [System.Management.Automation.InvocationInfo].
            GetProperty(
                'ScriptPosition',
                [System.Reflection.BindingFlags] 'Instance, NonPublic')
    }

    $script:_scriptPosition.GetValue($this).Text
}

Now the property is available to use on any function on that session:

function Get-Statement {
    param($Parameter)

    $MyInvocation.Statement
}

Get-Statement @(
    'foo'
    'bar'
    'baz')
like image 128
Santiago Squarzon Avatar answered Nov 01 '25 17:11

Santiago Squarzon



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!