Faster Get-ChildItem -Include N-amount of values

Hello!

I have several dynamically constructed arrays with different lengths that look something like this:

$SearchIncludes = '*.sln', '*.csproj', '*.vbproj', '*.fsproj', 'packages.props', 'global.json', 'nuget.config', 'packages.config'

which I use in the following search:

Get-ChildItem -Include $SearchIncludes -Recurse -File | etc.

I found out that this search is very slow and when I have to do it several times in a roll, it takes quite some time.

The following search does the same, but a lot faster

Get-ChildItem -Recurse -File | Where-Object { $PSItem.PSChildName -like '*.sln' -or $PSItem.PSChildName -like '*.csproj' -or etc. }

However I am not sure how to use the array with the $PSItem.PSChildName -like example. I tried it with a simple foreach, but it doesn’t seem to work.

Is there a way to do it with the array AND the $PSItem.PSChildName -like example ?
Is there any other way to conduct these searches faster than the -Include variant ?

Can you try to replace the $PSItem. with a $_. ? I think you will get what you are looking for then.

Same outcome.

For some reason, the item from the array inside the foreach is not respected and seems to return an empty value like this

foreach ( $item in $array) { $_.PSChildName -like "$item" }

is interpreted as

$_.PSChildName -like ""

where it should be interpreted as

$_.PSChildName -like "*.sln"

Can you try this?

Get-ChildItem -Recurse -File | Where-Object { $_.PSChildName -like '*.sln' -or $_.PSChildName -like '*.csproj' -or etc. }

I would drop the asterisk for the file extensions and try something like this:

$SearchIncludes = '.sln', '.csproj', '.vbproj', '.fsproj', 'packages.props', 'global.json', 'nuget.config', 'packages.config'
Get-ChildItem -Recurse -File | Where-Object {$_.Extension -in $searchIncludes -or $_.Name -in $searchIncludes}
3 Likes

Thanks Matt.

That’s much cleaner.

-Include search = 2:21
your variant = 0:20

Awesome, thank you! :slight_smile:

1 Like