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

Welcome Forums General PowerShell Q&A Get-Foo -Filter "bar" OR | ?{$_.bar}

This topic contains 4 replies, has 4 voices, and was last updated by

js
 
Participant
3 weeks, 4 days ago.

  • Author
    Posts
  • #114591

    Participant
    Points: 0
    Rank: Member

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

    -Filter "bar"

    or

    | Where {$_.Name -eq "bar"}

  • #114600

    Participant
    Points: 135
    Helping Hand
    Rank: Participant

    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. 😉

  • #114610

    Participant
    Points: 159
    Helping Hand
    Rank: Participant

    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).

  • #114621

    Participant
    Points: 0
    Rank: Member

    Thanks guys that makes sense to me!

  • #114790
    js

    Participant
    Points: 207
    Helping Hand
    Rank: Participant

    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
    

You must be logged in to reply to this topic.