Skip to content

Support a foreach statement with implicit iteration variable $_ for consistency with the ForEach-Object cmdlet #3830

@mklement0

Description

@mklement0

Inspired by #3695.

The builtin foreach alias for the ForEach-Object cmdlet keeps causing confusion with the foreach statement.

Given that the cmdlet and the statement are conceptually analogous, perhaps one way to mitigate the confusion is to allow the foreach statement to have an implied iteration variable, namely $_, just as when using ForEach-Object.

Desired behavior

# This works currently: an *explicit* iteration variable is needed.
> foreach ($suffix in 1, 2, 3) { "A" + $suffix }
A1
A2
A3

# Wishful thinking: allow *omitting* an iteration variable to use $_ by default,
# as in a pipeline, which would be the equivalent of:
#   1, 2, 3 | ForEach-Object { "A" + $_ }
> foreach (1, 2, 3) { "A" + $_ }
A1
A2
A3

Currently, one is forced to choose between:

  • more concise, but decidedly slower pipeline syntax: 1, 2, 3 | ForEach-Object { "A" + $_ }

  • faster, but more verbose foreach syntax: foreach($suffix in 1, 2, 3) { "A" + $suffix }

The suggested foreach syntax evens the playing field and allows a solution that is both concise and performant.

PowerShell Core v6.0.0-beta (v6.0.0-beta.1) 

Metadata

Metadata

Assignees

No one assigned

    Labels

    Committee-ReviewedPS-Committee has reviewed this and made a decisionIssue-Enhancementthe issue is more of a feature request than a bugResolution-Won't FixThe issue won't be fixed, possibly due to compatibility reason.WG-Languageparser, language semantics

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions