You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
Repository navigation
foreach iterates once over functions that return $null if they are not enclosed in parentheses #5674
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
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.
The Foreach runs because ReturnNull is being yielded to $result for each value returned. Since you are returning $null $result gets populated with $null
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]::Valuein 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 - $nullis 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 ($xin$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.
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.
microsoft-github-policy-service commented on Nov 16, 2023
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.
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.
microsoft-github-policy-service commented on Nov 23, 2023
Activity
markekraus commentedon Dec 12, 2017
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
$nullis still returning something and is conceptually different from returning nothing.In this example, the Foreach loop will not run:
However, in your example:
The Foreach runs because
ReturnNullis being yielded to$resultfor each value returned. Since you are returning$null$result gets populated with$nullmklement0 commentedon Dec 17, 2017
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
$nullis 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$nullbound to$xas 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 toSet-StrictMode -Version 1or 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]::Valuein a variable; on attempting to do so, the value was converted to$null.So, when dealing with variables, any original distinction between
$nulland a null collection was lost.PowerShell v3 fixed that: You can now store
[System.Management.Automation.Internal.AutomationNull]::Valueas well as$nullin a variable:@PetSerAl's test uses reflection rather than a direct call to
[object]::ReferenceEqualsto prevent PowerShell from quietly converting[System.Management.Automation.Internal.AutomationNull]::Valueto$nulland thereby thwarting the test.This treatment of
[System.Management.Automation.Internal.AutomationNull]::Valueas$nullin 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]::Valuein variables, allowing the distinction between a null scalar ("something") and a null collection ("nothing").Step backward: Not enumerating
$nullwithforeachanymore introduced a regrettable inconsistency with pipeline behavior:$null | % { 'entered' }outputsentered-$nullis enumerated - whereas the seemingly equivalentforeach ($x in $null) { 'entered' }does not.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
$nullwhen 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
$nulla "something" again in aforeachcontext, as used to be the case in PSv2: i.e,foreach ($x in $null)should again enter the loop once, with$nullbound to$x- irrespective of whether the$nullis 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]::Valuerather than$null, so thatforeach ($x in $NoSuchVariable)does not enumerate, effectively retaining the current behavior.$nulland[System.Management.Automation.Internal.AutomationNull]::Valueas equal in a scalar context, so, ideally, this change would have no practical impact.[System.Management.Automation.Internal.AutomationNull]::Value- i.e., "nothing".Of course, if users have gotten used to assuming that a
$nullis NOT enumerated inforeachloops, and therefore use explicit initialization to$nullto prevent enumeration, the above would be a breaking change: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.microsoft-github-policy-service commentedon Nov 16, 2023
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.
microsoft-github-policy-service commentedon Nov 16, 2023
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.
microsoft-github-policy-service commentedon Nov 16, 2023
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.
microsoft-github-policy-service commentedon Nov 23, 2023
This issue has been marked as "No Activity" as there has been no activity for 6 months. It has been closed for housekeeping purposes.