Get-Foo -Filter "bar" OR | ?{$_.bar}

What is quicker/better/best practice as statement?;

-Filter “bar”

or

| Where {$_.Name -eq “bar”}

It depends pretty much on the cmdlet you’re about to use. As a general recommendation you should filter as far left as possible in your pipeline. So if the cmdlet provides the option to filter - do it. :wink:

Imagine you have 10k users when you do Get-ADUser -Filter *. When you do this:

Get-ADUser -Filter * | Where{$_.SamAccountName -eq 'rob'}

That is returning all 10k records, storing it memory and then using the pipeline to pipe it to the Where-Object cmdlet for filtering. This is just to get a single person. Now, when you do this:

Get-ADUser -Filter {SamAccountName -eq 'rob'}

We are returning 1 record. Is it faster to return 1 record or 10k records? You can see there is obvious performance and memory consumption benefits to filtering as soon as possible (e.g. filter left).

Thanks guys that makes sense to me!

You can verify it’s faster yourself with measure-command. Depending on the situation, the difference can be dramatic.

PS C:\Users\admin> measure-command { Get-CimInstance Win32_Directory -filter 'name = "c:\\"' }


Days              : 0
Hours             : 0
Minutes           : 0
Seconds           : 0
Milliseconds      : 26
Ticks             : 264383
TotalDays         : 3.05998842592593E-07
TotalHours        : 7.34397222222222E-06
TotalMinutes      : 0.000440638333333333
TotalSeconds      : 0.0264383
TotalMilliseconds : 26.4383



PS C:\Users\admin> measure-command { Get-CimInstance Win32_Directory | where name -eq c:\ }


Days              : 0
Hours             : 0
Minutes           : 1
Seconds           : 2
Milliseconds      : 371
Ticks             : 623710351
TotalDays         : 0.000721886980324074
TotalHours        : 0.0173252875277778
TotalMinutes      : 1.03951725166667
TotalSeconds      : 62.3710351
TotalMilliseconds : 62371.0351