PowerShell

PowerShell: Filtering Objects vs Where-Object

In this article I am going to compare the filter parameter with where-object. The teaching says, that filtering is more efficient.  In the case of where-object, all objects must be retrieved first and then filtering is performed. This takes time. If filtered first, only the filtered objects are retrieved. In this article we’ll look at this using Measure-Command.

Get-Childitem and Where-Object

Measure-Command {Get-Childitem -Path C:\ -File -Recurse -ErrorAction SilentlyContinue | Where-Object {$_.Extension -eq ".txt"}}

1.PNG

37 seconds is not bad. I have a SSD.

Get-Childitem with Filter

Measure-Command {Get-Childitem -Path C:\ -File -Recurse -ErrorAction SilentlyContinue -Filter *.txt}

2.PNG

8 seconds is much faster.

Conclusion

Filtering is much faster. But not all commands offer the possibility to filter. In many posts I use where-object instead of the filter parameter. Why? I’m used to it. I think i have to change. 😉 See also my article Measure-Command: A speed comparison (Foreach vs. Foreach-Object).

Categories: PowerShell

Tagged as: ,

Leave a comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.