Skip to content

$MyInvocation.MyCommand.Name becomes null in Where-Object block #10477

Description

Issue description:
Unable to use $MyInvocation.MyCommand.Name in Where-Object block as it becomes null. ForEach and For-EachObject works fine. I see this only with Where-Object.

I understand there are workarounds but just want to know if this is expected behavior or not as I was not able to find document that describes scope in Where-Object.

Steps to reproduce

Copy the following script to test.ps1

1 | Where-Object{
    Write-Host('MyInvocation in Where-Object: ' + $MyInvocation.MyCommand.Name)
}

1 | ForEach-Object{
    Write-Host('MyInvocation in ForEach-Object: ' + $MyInvocation.MyCommand.Name)
}

ForEach($FileName in 1){
    Write-Host('MyInvocation in ForEach: ' + $MyInvocation.MyCommand.Name)
}

Then run

.\test.ps1

Expected behavior

## Expected output in case script name is test.ps1.

MyInvocation in Where-Object: test.ps1
MyInvocation in ForEach-Object: test.ps1
MyInvocation in ForEach: test.ps1

Actual behavior

## Expected output in case script name is test.ps1.

MyInvocation in Where-Object:       <-------- $MyInvocation.MyCommand.Name becomes null 
MyInvocation in ForEach-Object: test.ps1
MyInvocation in ForEach: test.ps1

Environment data

> $PSVersionTable

Name Value
---- -----
PSVersion 6.2.1
PSEdition Core
GitCommitId 6.2.1
OS Microsoft Windows 10.0.18362
Platform Win32NT
PSCompatibleVersions {1.0, 2.0, 3.0, 4.0…}
PSRemotingProtocolVersion 2.3
SerializationVersion 1.1.0.1
WSManStackVersion 3.0

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    Committee-ReviewedPS-Committee has reviewed this and made a decisionIssue-BugIssue has been identified as a bug in the productResolution-No ActivityIssue has had no activity for 6 months or moreUp-for-GrabsUp-for-grabs issues are not high priorities, and may be opportunities for external contributorsWG-Cmdletsgeneral cmdlet issues

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions