Skip to content

foreach iterates once over functions that return $null if they are not enclosed in parentheses #5674

Closed

Description

Steps to reproduce

> function ReturnNull() {return $null}
> foreach ($x in $null) {Write-Host "Loop entered."}
> foreach ($x in ReturnNull) {Write-Host "Loop entered."}
Loop entered.
> foreach ($x in (ReturnNull)) {Write-Host "Loop entered."}
>

Expected behavior

The middle foreach should not enter the loop body; it should behave consistently with the other two loops.

Actual behavior

See above.

Environment data

> $PSVersionTable

Name                           Value
----                           -----
PSVersion                      6.0.0-rc
PSEdition                      Core
GitCommitId                    v6.0.0-rc
OS                             Microsoft Windows 10.0.17053
Platform                       Win32NT
PSCompatibleVersions           {1.0, 2.0, 3.0, 4.0...}
PSRemotingProtocolVersion      2.3
SerializationVersion           1.1.0.1
WSManStackVersion              3.0

Activity

  1. markekraus commented on Dec 12, 2017

    @markekraus
    Contributor

    I believe this is by design. When you place the cmdlet/functions in a sub expression it runs the expression first and then squeezes the result to be treated as a variable. When you do not put the cmdlet/function in a subexpression, the results of the cmdlets are yielded one at a time to the foreach loop.

    Returning $null is still returning something and is conceptually different from returning nothing.

    In this example, the Foreach loop will not run:

    function ReturnNothing {}
    foreach($result in ReturnNothing){'entered'}

    However, in your example:

    function ReturnNull {$null}
    foreach($result in ReturnNull){'entered'}

    The Foreach runs because ReturnNull is being yielded to $result for each value returned. Since you are returning $null $result gets populated with $null

  2. added
    WG-Engine
    Issue-Question
    on Dec 12, 2017
  3. mklement0 commented on Dec 17, 2017

    @mklement0
    Contributor

    Tom Molenhouse (@tmolenh):

    That's certainly a baffling inconsistency (related to the distinction between an expression and a command, as Mark Kraus (@markekraus) explains), but there's a bigger issue underlying it:

    Given that $null is a "something" (more on that below), this behavior is unexpected, so my expectation is that all of your commands enter the loop.

    And that is indeed how things worked up to PSv2.

    PSv3, regrettably, changed the behavior of foreach ($x in $null) to not enumerate anymore - i.e., to not enter the loop body with $null bound to $x as the only element of the enumeration.

    I don't know what motivated this change - perhaps the goal was to prevent enumeration of references to nonexistent variables, given that such references default to $null (unless an error due to Set-StrictMode -Version 1 or higher).

    PowerShell has always had the distinction between a scalar $null (a "something") and a null collection ("nothing"), the latter technically being singleton [System.Management.Automation.Internal.AutomationNull]::Value, most easily produced with the following statement: & {}.

    In PSv2-, however, you couldn't store [System.Management.Automation.Internal.AutomationNull]::Value in a variable; on attempting to do so, the value was converted to $null.
    So, when dealing with variables, any original distinction between $null and a null collection was lost.

    PowerShell v3 fixed that: You can now store [System.Management.Automation.Internal.AutomationNull]::Value as well as $null in a variable:

    $a = $null  # Store $null
    $null -eq $a  # $True
    @($a).Count # 1 - $null is "something"
    
    $b = & {}  # Store [System.Management.Automation.Internal.AutomationNull]::Value
    $null -eq $b # !! Also $True(!) - however:
    @($b).Count # 0(!) - [System.Management.Automation.Internal.AutomationNull]::Value is "nothing"
    
    # A more direct test, courtesy of @PetSerAl, from https://stackoverflow.com/a/30018601/45375
    [Object].GetMethod('ReferenceEquals').Invoke($null, @([System.Management.Automation.Internal.AutomationNull]::Value, $b)) # $True

    @PetSerAl's test uses reflection rather than a direct call to [object]::ReferenceEquals to prevent PowerShell from quietly converting [System.Management.Automation.Internal.AutomationNull]::Value to $null and thereby thwarting the test.
    This treatment of [System.Management.Automation.Internal.AutomationNull]::Value as $null in certain contexts may offer a solution to the larger problem, however - see below.

    Therefore, the changes introduced in PSv3 represent both a step forward and a step back:

    • Step forward: The ability to store [System.Management.Automation.Internal.AutomationNull]::Value in variables, allowing the distinction between a null scalar ("something") and a null collection ("nothing").

    • Step backward: Not enumerating $null with foreach anymore introduced a regrettable inconsistency with pipeline behavior: $null | % { 'entered' } outputs entered - $null is enumerated - whereas the seemingly equivalent foreach ($x in $null) { 'entered' } does not.

      • This change would have made much more sense as a back-port to PSv2 and its inability to distinguish between the null scalar and the null collection in variables, so as to ensure that foreach ($x in &{}) { 'entered' } and $result = & {}; foreach ($x in $result) { 'entered' } behave the same.
        PSv3+, by contrast, never needed this change - except perhaps to prevent enumeration of $null when referencing nonexistent variables (see below for thoughts on that) - and introducing it introduced the similar, but distinct inconsistency mentioned above.

    As for a way forward:

    We obviously have to be very careful to make changes to such fundamental behaviors, but here's food for thought:

    • Make $null a "something" again in a foreach context, as used to be the case in PSv2: i.e, foreach ($x in $null) should again enter the loop once, with $null bound to $x - irrespective of whether the $null is a literal, the value of a variable or other expression, or direct output from a command.

    • Default references to nonexistent variables to [System.Management.Automation.Internal.AutomationNull]::Value rather than $null, so that foreach ($x in $NoSuchVariable) does not enumerate, effectively retaining the current behavior.

      • Note that PowerShell treats $null and [System.Management.Automation.Internal.AutomationNull]::Value as equal in a scalar context, so, ideally, this change would have no practical impact.
      • Arguably, from a conceptual standpoint, in line with PowerShell's collection-oriented nature, references to nonexistent variables should always have evaluated to [System.Management.Automation.Internal.AutomationNull]::Value - i.e., "nothing".

    Of course, if users have gotten used to assuming that a $null is NOT enumerated in foreach loops, and therefore use explicit initialization to $null to prevent enumeration, the above would be a breaking change:

    $val = $null  # explicit initialization to $null
    # ... 
    foreach ($x in $val) ...   # with the proposed change, this would now enumerate

    P.S.: As I've just realized, the very example that prompted you to create the issue demonstrates that you've indeed come to expect and rely on foreach ($x in $null) to not enumerate the $null.

  4. added
    Breaking-Change
    Issue-Enhancement
    and removed
    Issue-Question
    on Oct 13, 2019
  5. microsoft-github-policy-service commented on Nov 16, 2023

    @microsoft-github-policy-service
    Contributor

    This issue has not had any activity in 6 months, if this is a bug please try to reproduce on the latest version of PowerShell and reopen a new issue and reference this issue if this is still a blocker for you.

  6. microsoft-github-policy-service commented on Nov 16, 2023

    @microsoft-github-policy-service
    Contributor

    This issue has not had any activity in 6 months, if this is a bug please try to reproduce on the latest version of PowerShell and reopen a new issue and reference this issue if this is still a blocker for you.

  7. added
    Resolution-No Activity
    on Nov 16, 2023
  8. microsoft-github-policy-service commented on Nov 16, 2023

    @microsoft-github-policy-service
    Contributor

    This issue has not had any activity in 6 months, if this is a bug please try to reproduce on the latest version of PowerShell and reopen a new issue and reference this issue if this is still a blocker for you.

  9. microsoft-github-policy-service commented on Nov 23, 2023

    @microsoft-github-policy-service
    Contributor

    This issue has been marked as "No Activity" as there has been no activity for 6 months. It has been closed for housekeeping purposes.

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

    Breaking-ChangeIssue-EnhancementResolution-No ActivityWG-Engine

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions