Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 222
Borek Bernard Avatar asked Apr 03 '12 14:04

Borek Bernard


People also ask

How do I search for a specific file in PowerShell?

Get-ChildItem cmdlet in PowerShell is used to get items in one or more specified locations. Using Get-ChildItem, you can find files. You can easily find files by name, and location, search file for string, or find file locations using a match pattern.

What is the parameter for querying folders and subfolders using Get-ChildItem?

The Get-ChildItem cmdlet uses the Path parameter to specify the Cert: provider. The Recurse parameter searches the directory specified by Path and its subdirectories.

Can Get-ChildItem find hidden files?

The get-childitem cmdlet allows you to force information about hidden files or folders to be displayed. To display hidden files or folders, use the Force parameter with the get-childitem cmdlet. the hidden folders RECYCLER and System Volume Information are displayed in the results.

How do I get a list of files in a directory in PowerShell?

PowerShell utilizes the “Get-ChildItem” command for listing files of a directory. The “dir” in the Windows command prompt and “Get-ChildItem” in PowerShell perform the same function.


1 Answers

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

gci .\topfolder -rec -filter *foo* | where { $_.psiscontainer } | gci
like image 162
Shay Levy Avatar answered Nov 16 '22 00:11

Shay Levy