powershell performance: Get-ChildItem -Include vs. Get-ChildItem | Where-Object

Viewed 1226

I tried a few options to iterate my directories and get a huge performance difference between the following commands:

Slow:

Get-ChildItem -Directory -Force -Recurse -Depth 3 -Include '$tf'

Fast:

Get-ChildItem -Directory -Force -Recurse -Depth 3 | Where-Object Name -eq '$tf'

Could someone explain me why the first statement is much slower than the second?

1 Answers

Get-ChildItem is a provider cmdlet - that means that a bulk of its actual work is offloaded to an underlying provider, likely the FileSystem provider in your case.

The provider itself doesn't actually support the -Include/-Exclude parameters, that's one of the few things that the cmdlet takes care off - and for the file system provider this is ultra heavy double-work, because the cmdlet needs to recurse down through the file system hierarchy to figure out whether it needs to apply an exclusion or an inclusion based on a parent directory name, you can see how this is implemented here.

So by using -Include against the file system provider, you're asking PowerShell to do an immense amount of double work.

Related