Repository navigation
Description
Note:
- This proposal arose out of the discussion in Collection operators .Where() and .ForEach() do not unwrap single-item results #6512
- An RFC would have to be written, but I first want to see if there's a fundamental willingness to implement this.
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_Methodsis the portal (albeit one that, unfortunately, currently doesn't discuss syntax pitfalls and doesn't even referenceGet-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.
- Methods belong to a different realm, to which
-
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 neitherGet-Membernor.psobject.Methodsfind 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 thinkingEnvironment data
Written as of:
PowerShell Core v6.0.2
Activity
BrucePay commentedon Apr 5, 2018
Michael Klement (@mklement0) Please open an RFC. I think it will be much easier to manage commenting through that mechanism.
BrucePay commentedon Apr 5, 2018
Michael Klement (@mklement0) Some (ok many) comments. But please proceed with the RFC.
Please open a doc bug for .foreach{} and .where{}.
Methods are a native PowerShell feature, supported directly in the language. At one point we had something like
but decided to have native support in the language because we knew we'd never get all the coverage we wanted.
What pitfalls and why should it reference about_Parsing?
While the proximate cause for adding .where{} and .foreach{} was DSC configuration data, they are general purpose functionality.
This is incorrect.
Again, please open a doc bug.
Tab-completion does complete these methods.
I'd actually be concerned about increasing the confusion considering that the user can do either
or
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 isAnd again your proposed alternative example
can just be written as
Given the only syntactic difference is '|' before
whereinstead 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 exampleor
Writing the first example using
-foreachwould look something likeThis 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:
mklement0 commentedon Apr 6, 2018
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.
mklement0 commentedon Apr 6, 2018
More than 1 character difference: your first example wouldn't work, because you're missing the
(...)aroundGet-Process:The same way you explain the existing difference between
... | foreach { ... }andforeach (...) { ... }: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
-foreachoperator would have the added advantage of eliminating the confusion around$_use inforeachloops.From a syntax perspective, the
-foreachvs.... | foreachdichotomy strikes me as cleaner and easier to explain. (Theforeachloop will still have its place for more elaborate loops.)mklement0 commentedon Apr 6, 2018
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 methodWherewith 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.mklement0 commentedon Apr 6, 2018
Re DSC use:
Good to know that you can use pipelines.
Yes,
doesn't offer much syntactic advantage over:
except that once
-foreachand-whereare established as general-purpose operators, they are also the logical and more performant choice here, given that$AllNodesis a preexisting in-memory collection.mklement0 commentedon Apr 6, 2018
Again, I wouldn't drop the method-call parentheses:[1]
vs.
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)mklement0 commentedon Apr 6, 2018
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
-splitoperator as a (superior) analog toString.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.mklement0 commentedon Apr 6, 2018
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:
,-separated (vs. whitespace in argument mode, where,constructs arrays)Conversely, for someone coming from the developer world, calling your own helper functions such as
function foo ($bar, $baz) { ... }asfoo('one', 'two')is a real temptation, with a rude awakening.vexx32 commentedon Apr 6, 2018
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-foreachwere to be implemented, I would further recommend that| foreach {}be removed as an alias forForEach-Object.The presence of
| foreach {}alongsideforeach($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
-foreachonly support the one script block argument.mklement0 commentedon Apr 6, 2018
Rain Sallow (/u/ta11ow) (@vexx32):
While this would be great if we still had the chance, I think doing so now would result in a riot, understandably so.
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.
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
-splitoperator's syntax diagram (one of its binary forms):vexx32 commentedon Apr 6, 2018
Those are still binary operators, though; their second operand is simply an array with optional elements.
What I was thinking about is how
ForEach-Objecttakes 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.mklement0 commentedon Apr 6, 2018
Rain Sallow (/u/ta11ow) (@vexx32):
Absolutely.
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.mklement0 commentedon Apr 8, 2018
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.
[-]Expose the largely hidden .ForEach() and .Where() methods as regular PowerShell operators[/-][+]Expose the .ForEach() and .Where() methods as regular PowerShell operators[/+]mklement0 commentedon Apr 8, 2018
Bruce Payette (@BrucePay): The RFC draft is at PowerShell/PowerShell-RFC#126.
Closing this.
Reject RFC0034 for .ForEach() and .Where() methods as regular PowerSh…