Where-Object and .Where()

by Mar 15, 2017

Beginning in PowerShell 4, you can use the Where() and Foreach() methods in place of Where-Object and ForEach-Object whenever you do not want to use the streaming mechanism of the pipeline.

So if you already loaded all data into a variable, the non-streaming mechanism can be faster:

$Services = Get-Service

# streaming
$Services | Where-Object { $_.Status -eq 'Running' }
# non-streaming
$Services.Where{ $_.Status -eq 'Running' }

To save resources, the most efficient way remains the streaming pipeline mode, and not using variables:

Get-Service | Where-Object { $_.Status -eq 'Running' }

Note that Where-Object and .Where() use different array types, so their output is technically speaking not identical:

PS C:\> (1..19 |  Where-Object { $_ -gt 10 }).GetType().FullName
PS C:\>  ((1..19).Where{ $_ -gt 10 }).GetType().FullName
System.Collections.ObjectModel.Collection`1[[System.Management.Automation.PSObject, System.Management.Automation, Version=, Culture=neutral,  PublicKeyToken=31bf3856ad364e35]]

Twitter This Tip! ReTweet this Tip!