Skip to content

Collection operators .Where() and .ForEach() do not unwrap single-item results #6512

Closed

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

  1. BrucePay commented on Mar 27, 2018

    @BrucePay
    Collaborator

    Michael Klement (@mklement0) The Where() and Foreach() methods always return Collection[PSObject] by design. This is intended to match the signatures of other methods in the PowerShell API, for example:

    PS[1] (13) > [powershell]::Create().Invoke
    
    OverloadDefinitions
    -------------------
    System.Collections.ObjectModel.Collection[psobject] Invoke()
    System.Collections.ObjectModel.Collection[psobject] Invoke(System.Collections.IEnumerable input)
    System.Collections.ObjectModel.Collection[psobject] Invoke(System.Collections.IEnumerable input,
    System.Management.Automation.PSInvocationSettings settings)
    :
    
  2. added
    Resolution-By Design
    on Mar 27, 2018
  3. mklement0 commented on Mar 27, 2018

    @mklement0
    ContributorAuthor

    Bruce Payette (@BrucePay):

    [powershell]::Create().Invoke is 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-Object and Where-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 Needed on our hands - Steve Lee (@SteveL-MSFT)?

  4. BrucePay commented on Mar 27, 2018

    @BrucePay
    Collaborator

    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.

  5. mklement0 commented on Mar 28, 2018

    @mklement0
    ContributorAuthor

    The key point is that they are methods, not _commands_and should behave like methods, not commands.

    That is indeed an important clarification.

    Methods don't stream so there is no ambiguity as to whether the result should be a collection or not.

    On a side note: That's perhaps the most commendably succinct rationale for pipeline-output behavior I've ever come across.

    They return Collection both for performance reasons

    Understood. I've addressed the performance aspect in my proposal.

    and because this matches the return type other methods in the PowerShell API.

    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:

    Was (b) incidental?

    Either way, how about surfacing these API methods as bona fide operators?

    So, instead of:

    (1, 2, 3).Where({ $_ -gt 1 })

    implementing something like:

    1, 2, 3 -where { $_ -gt 1 }

    (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.

  6. BrucePay commented on Mar 28, 2018

    @BrucePay
    Collaborator

    .Where() and .Foreach are 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. .Count on object[]).

    at least internally terming them operators

    This terminology was picked up from LINQ which referred to query methods like where() as "operators".

    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

    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.

    Was (b) incidental?

    No. It was entirely intentional.

    how about surfacing these API methods as bona fide operators?

    In query scenarios, methods are simpler and compose more naturally (again see LINQ).

    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.

    Operators aren't commands. Operators have operator semantics, not command semantics. Operators don't stream.

  7. mklement0 commented on Apr 4, 2018

    @mklement0
    ContributorAuthor

    documented in the context for which they were designed: processing DSC ConfigurationData

    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:

    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:

    Operators aren't commands. Operators have operator semantics, not command semantics. Operators don't stream.

    That's a helpful distinction, thank you - and the kind of basic tenet that I wish were documented somewhere.


    This terminology was picked up from LINQ which referred to query methods like where() as "operators".
    In query scenarios, methods are simpler and compose more naturally (again see LINQ).

    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:

    Property access comes naturally in PowerShell, method calls do not.

    Ideally, you never need to call methods - that's what cmdlets are for.

    The context switching between PowerShell's argument mode and .NET method syntax is a perennial > pain point, even for experienced users.
    [...]
    Instead, PowerShell uses operators to provide convenient abstractions: Much of what requires method calls in, say, C#, is provided via operators such as -join, -split, -replace, ...
    [...]
    As an aside: consider how PowerShell's one foray into method syntax has fared; the (confusingly named) .ForEach() and .Where() collection operators never gained traction.

    Of course, I now have a better understanding of perhaps the main reason for their not gaining traction, as discussed above.

    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.

    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-Help based help system makes no mention of it.

    Hence my suggestion to surface .Where() and .ForEach() as operators -where and -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.

  8. KirkMunro commented on Apr 4, 2018

    @KirkMunro
    Contributor

    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.

  9. mklement0 commented on Apr 4, 2018

    @mklement0
    ContributorAuthor

    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.

  10. mklement0 commented on Apr 5, 2018

    @mklement0
    ContributorAuthor

    I've decided to create a new issue to focus on the operator proposal: #6576

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

    Resolution-By Design

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions