Powershell: SWITCH statement overrides automatic variable $_

Created on 22 May 2020  路  7Comments  路  Source: PowerShell/PowerShell

Steps to reproduce

1 | % { SWITCH (0) { DEFAULT { $_ } } }

Expected behavior

1

Actual behavior

0

Environment data

Name                           Value
----                           -----
PSVersion                      7.0.1
PSEdition                      Core
GitCommitId                    7.0.1
OS                             Microsoft Windows 10.0.18363
Platform                       Win32NT
PSCompatibleVersions           {1.0, 2.0, 3.0, 4.0鈥
PSRemotingProtocolVersion      2.3
SerializationVersion           1.1.0.1
WSManStackVersion              3.0

Issue-Question Resolution-External

Most helpful comment

All 7 comments

Workaround:
powershell 1 | % { SWITCH (0) { DEFAULT { $INPUT } } }

I don't think this is an issue, the switch statement sets $PSItem to the value passed into the switch which is 0 in this case.

This behaviour is undocumented. The automatic variable $_ is documented to be set by commands, the SWITCH statement is not a command.

Ah right, the switch statement is documented to set it, but it does look to be inconsistent with the documentation regarding $PSItem/$_

The design is explicitly documented now.

This issue has been marked as external and has not had any activity for 1 day. It has been be closed for housekeeping purposes.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

concentrateddon picture concentrateddon  路  3Comments

rkeithhill picture rkeithhill  路  3Comments

alx9r picture alx9r  路  3Comments

manofspirit picture manofspirit  路  3Comments

JohnLBevan picture JohnLBevan  路  3Comments