How to find files in directories with certain name using Get-ChildItem?

Borek Bernard picture Borek Bernard · Apr 3, 2012 · Viewed 42.7k times · Source

I have a project folder called topfolder and I want to find all files in all subfolders that match a certain pattern, e.g. when the folder contains foo anywhere in its name, I want to list all files inside it.

I tried something like:

gci .\topfolder -rec -filter *foo*

but it has two problems:

  1. Only files actually containing foo will be listed (I want any file in foo-like folder).
  2. Directories matching this filter will be part of the result set too.

Then I tried this:

gci .\topfolder\*foo* -include *.*

but that doesn't work at all - apparently wildcards match only a single segment of a path so that pattern will match topfolder\foobar but not topfolder\subfolder\foobar.

The only way I've found so far was to use Get-ChildItem twice, like this:

gci .\topfolder -rec -include *foo* | where { $_.psiscontainer } | gci

This works but it seems like a waste to call gci twice and I hope I just didn't find a right wildcard expression for something like -Path, -Filter or -Include.

What is the best way to do that?

Answer

Shay Levy picture Shay Levy · Apr 3, 2012

I would use the Filter parameter instead of Include, it performs much fatser

gci .\topfolder -rec -filter *foo* | where { $_.psiscontainer } | gci