Repository navigation
Description
The PSv4+ collection operators .Where() and .ForEach() differ from normal pipeline-output collecting behavior in two respects:
- If the result is a single item, it isn't unwrapped; that is, a collection is always returned, and
- that collection is always of type
[System.Collections.ObjectModel.Collection[psobject]]rather than a regular PS array ([object[]])
In the spirit of PowerShell/PowerShell-RFC#120, the behavior should be harmonized with how pipeline output is already collected and how the -*Variable common parameters (except -PipelineVariable) should collect output, according to the RFC.
Given how contentious the linked -OutVariable-related RFC is turning out to be, this proposal may need to become an RFC as well, though perhaps the decision on said RFC will imply how to proceed here.
To reiterate what, to me, motivates this desire for harmonization / resolving inconsistencies:
The unifying vision is to provide a consistent experience whenever PowerShell collects output for you, so you never need to worry about different unwrapping behavior and/or differing collection types.
Note:
This harmonization would currently incur a performance cost, because the internally used, resizable collection data types must on output be converted to object[]].
However, the proper way to resolve this is to switch PowerShell's fundamental collection data type from [object[]] to an efficiently resizable one that can be used internally and directly output.
Discussion in that direction has started, but it's obviously a massive internal change; externally, assuming no bugs have crept in, however, much of existing code may not only continue to work as-is, but may exhibit automatic performance gains.
To quote Jason Shirk (@lzybkr) from the linked issue:
I've often wondered if the comma operator could create a list instead of an array. I have a feeling most scripts would never notice a difference because of how freely things are converted to an object array.
Current Behavior
PS> (1).ForEach({$_}).GetType().Name; (1, 2).ForEach({$_}).GetType().Name
Collection`1 # single-item result wasn't unwrapped
Collection`1 # output collection type is not [object[]]Desired Behavior
PS> (1).ForEach({$_}).GetType().Name; (1, 2).ForEach({$_}).GetType().Name
Int32 # single-item result was unwrapped
Object[] # regular PS array
Activity
BrucePay commentedon Mar 27, 2018
Michael Klement (@mklement0) The
Where()andForeach()methods always returnCollection[PSObject]by design. This is intended to match the signatures of other methods in the PowerShell API, for example:mklement0 commentedon Mar 27, 2018
Bruce Payette (@BrucePay):
[powershell]::Create().Invokeis an API method, as you say, whereas.Where()and.ForEach()are public methods on any object surfaced in regular PowerShell use.Or where they never meant to be used as such?
If they are meant to be provided as - more performant and flexible - complements to
ForEach-ObjectandWhere-Object(which they are), then consistency with normal PowerShell behavior seems more important to me.Perhaps, though, that breaks existing API uses; at any rate, we may have another
Documentation Neededon our hands - Steve Lee (@SteveL-MSFT)?BrucePay commentedon Mar 27, 2018
Michael Klement (@mklement0) I guess I'm not being clear. The key point is that they are methods, not _commands_and should behave like methods, not commands. Methods don't stream so there is no ambiguity as to whether the result should be a collection or not. The design team explicitly decided that they would have consistent behaviour and always return a collection. They return
Collection<PSObject>both for performance reasons, and because this matches the return type other methods in the PowerShell API. Again, both explicit decisions on the part of the design team.mklement0 commentedon Mar 28, 2018
That is indeed an important clarification.
On a side note: That's perhaps the most commendably succinct rationale for pipeline-output behavior I've ever come across.
Understood. I've addressed the performance aspect in my proposal.
So the awkwardness arises out of these methods doing double duty: (a) being part of the API and (b) being public methods accessible to regular PowerShell users.
But perhaps (b) was incidental, given that:
these methods aren't documented, as far as I'm aware of.
at least internally terming them operators - seems like a misnomer, given the method syntax.
.Where()"operator" (though not.ForEach(), as far as I can tell) does make a brief - and unexpected - cameo in the documentation: "Where() operator behavior has changed.".Was (b) incidental?
Either way, how about surfacing these API methods as bona fide operators?
So, instead of:
implementing something like:
(And analogously for
.ForEach()).That would not only make for more natural, PowerShell-like syntax, but would allow us to discuss the output behavior separately from the strictures of the API.
BrucePay commentedon Mar 28, 2018
.Where()and.Foreachare documented in the context for which they were designed: processing DSC ConfigurationData. See Using configuration data in DSC and Separating configuration and environment data. The second document in particular shows examples of use.Now there doesn't appear to be a standalone help topic for these methods. We should add this but as near as I can tell, we don't document any of the existing type extensions anywhere (e.g.
.Countonobject[]).This terminology was picked up from LINQ which referred to query methods like
where()as "operators".I don't understand this statement. What "double duty"? You seem to be making some artificial distinction here. The PowerShell API is part of the regular PowerShell user's experience. Advanced experiences perhaps but not different.
No. It was entirely intentional.
In query scenarios, methods are simpler and compose more naturally (again see LINQ).
Operators aren't commands. Operators have operator semantics, not command semantics. Operators don't stream.
mklement0 commentedon Apr 4, 2018
That's a fair point: the regular documentation makes no mention of
.Where()and.ForEach(), except for the seemingly random cameo I've mentioned.I initially discovered them here (an article by Kirk Munro (@KirkMunro)), and have been using them ever since.
So, given their lack of user documentation and how hard it is to discover them with reflection, perhaps their esoteric nature spares regular PowerShell users puzzlement over:
System.Collections.ObjectModel.Collection`1)[psobject]) - the usually behind-the-scenes type that causes issues when it surfaces publicly (see Why is [pscustomobject] the same as [psobject], even though a distinct [System.Management.Automation.PSCustomObject] type exists? #4344, -as operator does not recognize System.Management.Automation.PSCustomObject instances as such #4343, Objects are situationally invisibly [psobject]-wrapped, sometimes causing unexpected behavior. #5579, Preference variable $OutputEncoding in child scopes misbehaves with encodings created with New-Object / commands rather than expressions #5763, ConvertTo-Json: unexpected behavior with objects that have ETS properties (NoteProperty, ScriptProperty) #5797)Seemingly exactly as designed for API use, but awkward for in-PowerShell use (more on that below).
However, I do now understand the point you were trying to make with:
That's a helpful distinction, thank you - and the kind of basic tenet that I wish were documented somewhere.
For in-PowerShell use (not from C#), methods are an awkward fit, due to the different argument syntax, as I've tried to argue here:
Of course, I now have a better understanding of perhaps the main reason for their not gaining traction, as discussed above.
I think the distinction is real, both conceptually and pragmatically:
the API is for controlling PowerShell from the outside (even though you can also use PowerShell scripting to do so; the more typical use case is to use C#, however, methinks)
as a regular PowerShell user, you can spend your entire PowerShell life blissfully ignorant of even the existence of the API: you typically don't need it to call cmdlets and write scripts, and the regular
Get-Helpbased help system makes no mention of it.Hence my suggestion to surface
.Where()and.ForEach()as operators-whereand-foreach, ideally with[object[]]output for consistency - even though that is clearly implies performance hit, which takes us back to the discussion of fundamentally changing PowerShell's collection data type.KirkMunro commentedon Apr 4, 2018
FWIW, >10 years into PowerShell, and I don't believe method syntax to be a pain point for PowerShell users. I certainly haven't heard it broadly identified as a pain point like you describe from the community members I have spoken with over the years. Some, sure. But few, to be honest. Further, I find the idea that cmdlets should always be used in place of methods is preposterous, not to mention a nightmare. In some cases it makes great sense, but in oh so many others it does not.
mklement0 commentedon Apr 4, 2018
Kirk Munro (@KirkMunro):
As a comparatively inexperienced user, I can tell you that switching between argument mode and method syntax still trips me up on occasion.
It's not that cmdlets should always be used, it's about ideally having the majority of use cases covered by cmdlets, so that less savvy users have their needs met without having to learn about specific .NET types and switching back and forth between conflicting syntax forms and, not least, so as to benefit from the higher level of abstraction that cmdlets usually provide.
As I've said before: that you have the option to call methods from PowerShell is a great blessing and gives PowerShell its virtually unlimited power, but it is an advanced use case.
mklement0 commentedon Apr 5, 2018
I've decided to create a new issue to focus on the operator proposal: #6576