PowerShell Where() Method vs. Where-Object Cmdlet

In my last post I mentioned attempting to speed up a slow PowerShell script by swapping out Out-Null for > $null. Well, I’m back at it and trying to speed up the script a bit more.

I’m using several Where-Object cmdlets to find items that match a string using -like. The collections are rather large (40,000+ items) so it takes a while to find matching items.

PowerShell version 4 introduced a new Where() method that operates on arrays. The Where() method can be quite a bit faster compared to the Where-Object cmdlet. It can, however, use quite a bit more memory and in some cases might be slower, so as usual – your mileage may vary.

Example:

$files = Get-ChildItem -Path C:\ -Recurse -ErrorAction Ignore
In this case, Where() shaved 10 seconds off compared to Where-Object.

Leave a Reply

Your email address will not be published. Required fields are marked *

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