Skip to content

Expose the .ForEach() and .Where() methods as regular PowerShell operators #6576

Closed

Description

Note:


The hidden and effectively undocumented .Where() and .ForEach methods available on every object exposed by PowerShell were introduced to support DSC in v4 and provide functionality similar to the Where-Object and ForEach-Object cmdlets, but (a) in a more performant way (albeit in an all-in-memory way) and (b) with more features. The most comprehensive documentation that I'm aware of is this blog post by @KirkMunro.

While they could simple be documented (and made more discoverable), I suggest surfacing them as bona fide PowerShell operators -foreach and -where:

  • No native PowerShell features that I am aware of are exposed as methods: instead, functionality is surfaced as commands (cmdlets/functions) and operators.

    • Methods belong to a different realm, to which Get-Help about_Methods is the portal (albeit one that, unfortunately, currently doesn't discuss syntax pitfalls and doesn't even reference Get-Help about_Parsing); it's a powerful realm and definitely worth knowing about, but it is a different realm, distinct from how PowerShell itself surfaces its functionality.
  • The .Where() and .ForEach() methods were introduced as such for the benefit of DSC - of necessity, I presume, given that the DSC DSL doesn't allow use of pipelines (see comments below).

    • Despite their general availability inside PowerShell itself, they're effectively undocumented, and many people may not even be aware of their existence (since tab completion doesn't help (see comments below), and neither Get-Member nor .psobject.Methods find them, you simply have to know of their existence).

    • Even if fully documented (and, as discussed, this is currently even lacking in the DSC context, and overall Kirk's blog post is still the most complete documentation), these methods make awkward tools in general PowerShell use, due to their method syntax and output data types.

Hence my suggestion to surface them as operators with [object[]] output, which would make them discoverable interactively (-<tab>) , and they would be documented alongside the existing operators.

They'd make concise complements to their cmdlet counterparts; -foreach would make the foreach loop unnecessary in many situations and with its use of $_ reduce the existing confusion between the loop and the cmdlet (see MicrosoftDocs/PowerShell-Docs#1514 and a rejected attempt to harmonize the two, #3830):

$var = 1, 2, 3 -foreach { $_ + 1 }  # wishful thinking

# vs.

$var = foreach ($i in 1, 2, 3) { $i + 1 }
# or (slower)
$var = 1, 2, 3 | ForEach-Object { $_ + 1 }

#  ---

$var = 1, 2, 3 -where { $_ -gt 1 } # wishful thinking

# vs.
# (slower)
$var = 1, 2, 3 | Where-Object { $_ -gt 1 }
# or
$var = foreach ($i in 1, 2, 3)  { if ($i -gt 1) { $i } }

Arguably, even DSC could benefit from the cleaner operator syntax; contrast the following:

# Note that this example, taken from https://docs.microsoft.com/en-us/powershell/dsc/separatingenvdata
# doesn't even use `()` around the script-block argument, so the use of Where() 
# isn't even readily recognizable as a *method* call.
Node ($AllNodes.Where{$_.Role -eq "WebServer"}).NodeName { ...

# vs.

Node ($AllNodes -where {$_.Role -eq "WebServer"}).NodeName { ...  # wishful thinking

Environment data

Written as of:

PowerShell Core v6.0.2

Activity

  1. BrucePay commented on Apr 5, 2018

    @BrucePay
    Collaborator

    Michael Klement (@mklement0) Please open an RFC. I think it will be much easier to manage commenting through that mechanism.

  2. added
    Issue-Enhancement
    on Apr 5, 2018
  3. BrucePay commented on Apr 5, 2018

    @BrucePay
    Collaborator

    Michael Klement (@mklement0) Some (ok many) comments. But please proceed with the RFC.

    The most comprehensive documentation that I'm aware of is this blog post by Kirk Munro (@KirkMunro).

    Please open a doc bug for .foreach{} and .where{}.

    No native PowerShell features that I am aware of are exposed as methods

    Methods are a native PowerShell feature, supported directly in the language. At one point we had something like

    Invoke-Member $obj memberName arg1, arg2, arg3
    

    but decided to have native support in the language because we knew we'd never get all the coverage we wanted.

    Methods belong to a different realm, to which Get-Help about_Methods is the portal (albeit one that, unfortunately, currently doesn't discuss syntax pitfalls and doesn't even reference Get-Help about_Parsing);

    What pitfalls and why should it reference about_Parsing?

    The .Where() and .ForEach() methods were introduced as such for the benefit of DSC

    While the proximate cause for adding .where{} and .foreach{} was DSC configuration data, they are general purpose functionality.

    of necessity, I presume, given that the DSC DSL doesn't allow use of pipelines.

    This is incorrect.

    Despite their general availability inside PowerShell itself, they're effectively undocumented,

    Again, please open a doc bug.

    and many people may not even be aware of their existence (since tab completion doesn't help, and neither Get-Member nor .psobject.Methods find them, you simply have to know of their existence).

    Tab-completion does complete these methods.

    PS[1] (32) > (1,2,3).F<tab>
    PS[1] (32) > (1,2,3).ForEach(
    

    They'd make concise complements to their cmdlet counterparts; -foreach would make the foreach loop unnecessary in many situations and with its use of $_ reduce the existing confusion between the loop and the cmdlet - see #3830:

    I'd actually be concerned about increasing the confusion considering that the user can do either

    Get-Process -where { $_.CPU -gt 100}
    

    or

    Get-Process |where { $_.CPU -gt 100 }
    

    which appear to do the same thing but doesn't (quite) and whose notation differs only by a single character. How do you explain that to a novice user?

    Finally, in the last examples, there are unnecessary parens in the .where{} case. The corrected example is

    Node $AllNodes.Where{$_.Role -eq "WebServer"}.NodeName 
    { ...
    

    And again your proposed alternative example

    Node ($AllNodes -where {$_.Role -eq "WebServer"}).NodeName
    { ... 
    

    can just be written as

    Node ($AllNodes |where {$_.Role -eq "WebServer"}).NodeName
    { ... 
    

    Given the only syntactic difference is '|' before where instead of '-', I don't see an advantage in this scenario. So - going back to basics, - the scenario that .where{} was intended to address was the deep extraction of data using compact expressions with minimal syntactic noise. For example

    $procs.where{ $_.cpu -gt 100 }.modules.where{ $_.modulename -match "ntdll"}.count # zero parens
    

    or

    write-output $n.foreach{ $_ * 2 } 
    

    Writing the first example using -foreach would look something like

    (((gps) -where { $_.cpu -gt 100 }).modules -where{ $_.modulename -match "ntdll"}).count
    

    This has a lot of nested parens and that is exactly what we were trying to get away from.

    So - from an RFC perspective I'd be looking for at least:

    • target audience (novice, advanced, ...)
    • compelling scenarios (how this makes PowerShell better e.g. opening up new scenarios, making existing ones more efficient, ...)
    • significant examples where these scenarios are addressed (we had this conversation in the committee meeting this week - too few of the RFC's have significant (or any!) examples.)
    • risks (?)
  4. mklement0 commented on Apr 6, 2018

    @mklement0
    ContributorAuthor

    Tab-completion does complete these methods.

    Thanks for clarifying that. I had tried with a scalar, where it doesn't work: $v = 1; $v.f<tab>

    On the command line, tab completion decides based on the whether the variable value is array-valued whether to offer the method.

    By contrast, the VSCode extension isn't smart enough to detect potentially array-valued variables, such as $v = Get-ChildItem; $v.f<tab>

    Arguably, tab completion of these methods should be offered on both scalars and collections, because they truly are available on both - that would also simplify the logic.

    Either way, these problems are certainly surmountable.

  5. mklement0 commented on Apr 6, 2018

    @mklement0
    ContributorAuthor

    I'd actually be concerned about increasing the confusion considering that the user can do either

    Get-Process -where { $_.CPU -gt 100}
    or

    Get-Process |where { $_.CPU -gt 100 }

    which appear to do the same thing but doesn't (quite) and whose notation differs only by a single
    character.

    More than 1 character difference: your first example wouldn't work, because you're missing the (...) around Get-Process:

     # Get-Process needs (...) to allow its output to participate in the expression
    (Get-Process) -where { $_.CPU -gt 100}  

    How do you explain that to a novice user?

    The same way you explain the existing difference between ... | foreach { ... } and foreach (...) { ... }:

    Ideally, create a new conceptual help topic that discusses the tradeoffs between those constructs:

    • pipeline syntax: one-by-one as-output-is-produced processing: memory-throttling, but slow

    • operator syntax: up-front output-collecting, then iterating: memory-intensive, but fast

    Even without introducing the proposed operator these tradeoffs are worth documenting with respect to ... | foreach { ... } vs. foreach (...) { ... }.

    The new -foreach operator would have the added advantage of eliminating the confusion around $_ use in foreach loops.

    From a syntax perspective, the -foreach vs. ... | foreach dichotomy strikes me as cleaner and easier to explain. (The foreach loop will still have its place for more elaborate loops.)

  6. mklement0 commented on Apr 6, 2018

    @mklement0
    ContributorAuthor

    there are unnecessary parens in the .where{} case.

    Yes, you can write (1, 2).Where{ $_ -gt 1 } instead of using regular method syntax, (1, 2).Where({ $_ -gt 1 }), but the parens-free variant is without precedent in PowerShell and is so unfamiliar that it almost looks like a mistake.

    You may be tempted to then insert whitespace - (1, 2).Where { $_ -gt 1 } only to find that that breaks.

    These are methods, so I would recommend always calling them as such: (1, 2).Where({ $_ -gt 1 }) is a call to method Where with 1 argument that is a script block.

    Similarly, the tab completion we've discussed expands (1, 2).f<tab> to (1, 2).ForeEach( - with a parenthesis.

  7. mklement0 commented on Apr 6, 2018

    @mklement0
    ContributorAuthor

    Re DSC use:

    Good to know that you can use pipelines.

    Yes,

    Node ($AllNodes -where {$_.Role -eq "WebServer"}).NodeName

    doesn't offer much syntactic advantage over:

    Node ($AllNodes  |where {$_.Role -eq "WebServer"}).NodeName

    except that once -foreach and -where are established as general-purpose operators, they are also the logical and more performant choice here, given that $AllNodes is a preexisting in-memory collection.

  8. mklement0 commented on Apr 6, 2018

    @mklement0
    ContributorAuthor

    deep extraction of data using compact expressions with minimal syntactic noise. For example
    $procs.where{ $_.cpu -gt 100 }.modules.where{ $_.modulename -match "ntdll"}.count # zero parens

    Again, I wouldn't drop the method-call parentheses:[1]

    $procs.where({ $_.cpu -gt 100 }).modules.where({ $_.modulename -match "ntdll"}).count

    vs.

    (($procs -where { $_.cpu -gt 100 }).modules -where { $_.modulename -match "ntdll"}).count

    Ultimately the same number of parentheses (though the nesting adds complexity), and also whitespace to clarify the structure, and the parentheses only come into play when property / method access is needed as well.

    A fluent API (method chaining) certainly has its charms, but it doesn't strike me as PowerShell-like.
    That said, people who wish to use it still can.


    [1] Let's not forget that both .ForEach() and .Where() can accept multiple arguments, in which case the parentheses are mandatory:
    (1, 2).ForEach({ $_ + $args[0] }, 1)

  9. mklement0 commented on Apr 6, 2018

    @mklement0
    ContributorAuthor

    Methods are a native PowerShell feature, supported directly in the language. At one point we had
    something like

    Invoke-Member $obj memberName arg1, arg2, arg3
    but decided to have native support in the language because we knew we'd never get all the coverage we wanted.

    Yes, and the direct access to methods is great.

    But there is a difference between enabling direct access to features from a different realm (.NET) and PowerShell's own of surfacing functionality (commands and operators).

    An example would be PowerShell's -split operator as a (superior) analog to String.Split() - yes, you can call the latter, but why would you? There's the familiar syntax of a PowerShell operator, the implicit conversion of the LHS to string, the support for regexes, ...

    Similarly, .Where() and .ForEach() - as unique PowerShell features that act like operators - should be operators.

  10. mklement0 commented on Apr 6, 2018

    @mklement0
    ContributorAuthor

    What pitfalls and why should it reference about_Parsing?

    Methods calls are like command/function calls at a certain level of abstraction, so users can get confused between the distinct syntax requirements:

    From the perspective of a shell user mostly familiar with command syntax (argument mode), the tricky differences are:

    • parentheses are required (vs. whitespace in argument mode)
    • arguments must be ,-separated (vs. whitespace in argument mode, where , constructs arrays)
    • bareword arguments (unquoted strings) aren't allowed

    Conversely, for someone coming from the developer world, calling your own helper functions such as function foo ($bar, $baz) { ... } as foo('one', 'two') is a real temptation, with a rude awakening.

  11. vexx32 commented on Apr 6, 2018

    @vexx32
    Collaborator

    I think this is likely to be a good idea, even if only to reduce the syntactic irregularities that .ForEach({}) and .Where({}) introduce. Additionally, if -foreach were to be implemented, I would further recommend that | foreach {} be removed as an alias for ForEach-Object.

    The presence of | foreach {} alongside foreach($obj in $col) {} is the source of a lot of confusion for beginners, and even some more advanced users who aren't aware of the | foreach {} alias.

    The alternative -foreach {} is a significantly simpler syntax, but I must wonder if the intent is to replace .ForEach({}) then we must have some way of supporting the multiple parameters of .ForEach({}) with the operator, and from what I've seen I don't think any operators typically extend beyond unary or binary -- having support for something like $collection -foreach {} {} {} would be very unusual indeed, and potentially be quite syntactically confusing.

    I'd think it might be best to have -foreach only support the one script block argument.

  12. mklement0 commented on Apr 6, 2018

    @mklement0
    ContributorAuthor

    Rain Sallow (/u/ta11ow) (@vexx32):

    I would further recommend that | foreach {} be removed as an alias for ForEach-Object

    While this would be great if we still had the chance, I think doing so now would result in a riot, understandably so.

    must wonder if the intent is to replace .ForEach({})

    Similarly, backward-compatibility concerns alone would prevent that, but fortunately there is no problem with retaining them - more C#-/developer-minded users may still prefer them.

    I don't think any operators typically extend beyond unary or binary

    They do, even though it isn't common (e.g., -split, -replace).
    I do think we should strive for supporting all arguments, although we'd certainly have to look at the specifics.

    For instance, here's the -split operator's syntax diagram (one of its binary forms):

     <String> -Split <Delimiter>[,<Max-substrings>[,"<Options>"]]
    
  13. vexx32 commented on Apr 6, 2018

    @vexx32
    Collaborator

    Those are still binary operators, though; their second operand is simply an array with optional elements.

    What I was thinking about is how ForEach-Object takes input like this: $array | ForEach-Object {"Begin"} {"Process"} {"End"} -- which it does by having them assigned to separate parameters. I suppose a similar thing could be done with a -foreach {'begin'},{'process'},{'end'} but personally I prefer to avoid overcomplicating the syntax. Some of PS's best stuff is in its clarity, and this would... not be super clear, I feel.

  14. mklement0 commented on Apr 6, 2018

    @mklement0
    ContributorAuthor

    Rain Sallow (/u/ta11ow) (@vexx32):

    Those are still binary operators, though; their second operand is simply an array with optional elements.

    Absolutely.

    What I was thinking about is how ForEach-Object takes input like this: $array | ForEach-Object {"Begin"} {"Process"} {"End"}

    This mostly makes sense in a pipeline context - I agree that it's not needed in an operator context, which would allow us to focus on using the array elements to provide the optional .Where() and .ForEach() arguments.

  15. mklement0 commented on Apr 8, 2018

    @mklement0
    ContributorAuthor

    Bruce Payette (@BrucePay): I've created the following docs issues:

    On a meta note: I've griped about the state of PowerShell's documentation before, but it truly is disheartening whenever I take a closer look. Let's hope that will change for the better with help from the community.

    I will create an RFC soonish.

  16. changed the title [-]Expose the largely hidden .ForEach() and .Where() methods as regular PowerShell operators[/-] [+]Expose the .ForEach() and .Where() methods as regular PowerShell operators[/+] on Apr 8, 2018
  17. mklement0 commented on Apr 8, 2018

    @mklement0
    ContributorAuthor

    Bruce Payette (@BrucePay): The RFC draft is at PowerShell/PowerShell-RFC#126.
    Closing this.

  18. added
    Resolution-External
    on Apr 11, 2018
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

    Issue-EnhancementResolution-External

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions