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.

PowerShell Out-Null vs. $null

It’s always the little things. I was recently troubleshooting a slow PowerShell script which required piping the output of a long-running command to Out-Null. Now there may have been other ways to avoid this, but that’s another story.

A quick Google search led to *tons* of articles and posts on why never to use Out-Null (OK, there are reasons, but my particular use was not one of them) and instead redirect to $null.

So I swapped out | Out-Null for > $null and sure enough problem solved.

Here’s a quick snippet that shows the speed difference: