Do you use the .Foreach() and .where() operators?

Do you use the .foreach() and .where() operators? I find them very convenient for assigning the output of the foreach construct to a variable.

$Output = $Array.where{FilterExpression}.foreach{ActionExpression}

Being able to chain them like methods makes it very easy for me to follow. Especially when I was first learning. They really made the light bulb go off for how functions interact with each other.

Additionally, for console base Administration it makes single line execution terse and convenient.

$Array.where{FilterExpression}.id is functionally easier for me to type/tab complete through than ($array | where {FilterExpression}).id, which if you are like me and forget to type an opening parenthesis a lot, it can be a frustrating and regularly wasted keystroke. It also conveniently outputs to a Generic Collection, which you can add and remove items from. I personally don’t write code that finds much use for this ever, but it is a thing.

I’m just curious if anyone else has anything to say about the benefits or drawbacks other than differences in execution time.

Alternatively please convince me not to use these anymore if I shouldn’t :sweat_smile:.

I’ll give these try in sequence like you demonstrated. I remember reading that the .foreach() method is more efficient then the ForEach-Object cmdlet.

Thanks for sharing.

As Thomas found out on another thread, the where method has a useful “split” mode. Each of these have their place. But as you also found out, Sean, there are sometimes minor differences or things that don’t work as expected.

Late to the party, sorry. This looks interesting, and I thought I’d run it through Measure-Command

First I created an array: $Tags = 1…199 | foreach {"Tag$_"}

Then I measured how long it took:
Measure-Command {$Tags|ForEach{$_}}
This took TotalMilliseconds : 12.8882

And Measure-Command {$Tags.ForEach{$_}} which took TotalMilliseconds : 13.9521.

Upping it to $Tags = 0…1999999 | foreach {"Tag$"} the results are different:
Measure-Command {$Tags|ForEach{$
}} is Milliseconds : 316
Measure-Command {$Tags.ForEach{$_}} is Milliseconds : 276

Obviously, use what you’re comfortable with, but if you are writing something that takes a while, it’s worth checking how long commands take to run.

I only use them occasionally. I like the ‘until’ feature of the where method. Foreach and where remind me of map and filter in javascript (but no reduce).

where({ $_ -match 'match'},'until')


Foreach() and Where() methods are more concise and more performant for many cases. Where() method offers different modes for data filtering and more iteration control. I have personally seen some object types that have issues with these methods even when those objects were singular or part of an array. But those same objects have no issues with Foreach-Object or Where-Object.