48

I would like to search for a folder in a specific directory and subdirectorys.

I tried googling it, but didn't really find any usefull examples.

1
  • 1
    Have you looked at the -recurse switch on Get-ChildItem? Commented Sep 30, 2013 at 10:32

2 Answers 2

84
Get-ChildItem C:\test -recurse | Where-Object {$_.PSIsContainer -eq $true -and $_.Name -match "keyword"}

I believe there's no dedicated cmdlet for searching files.

Edit in response to @Notorious comment: Since Powershell 3.0 this is much easier, since switches -Directory and -File were added to Get-ChildItem. So if you want it short you've got:

ls c:\test *key* -Recurse -Directory

With command alias and tab-completion for switches it's a snap. I just missed that the first time.

Sign up to request clarification or add additional context in comments.

5 Comments

For those less Powershell familiar, the expression '$_.PSIsContainer -eq $true' is the test for the current object being a folder.
@NotoriousPet0 Please see the edit for shorter version. Besides that popular commands usually have aliases you're familiar with from *nix or cmd, long command names system has it's advantages. You can easily grasp new module thanks to verb-noun convention, and find commands: get-command -Noun item; Get-Command -Verb convertto.
this makes no sense to me. Which part of ls c:\test *key* -Recurse -Directory do I replace with the directory name I want to find?
@Robin *key* is a filter for directory name that you expect to be somewhere in c:\test.
-Directory works only in newer versions of powershell. Also Get-ChildItem == ls == gci for any newbs
9

Here is my version, which is only slightly different:

gci -Recurse -Filter "your_folder_name" -Directory -ErrorAction SilentlyContinue -Path "C:\"

some more info:

-Filter "your_folder_name"

From documentation: Filters are more efficient than other parameters. The provider applies filter when the cmdlet gets the objects rather than having PowerShell filter the objects after they're retrieved. The filter string is passed to the .NET API to enumerate files. The API only supports * and ? wildcards.

-Directory 

Only examine directories, also could be -File

-ErrorAction SilentlyContinue 

Silences any warnings

-Path "C:\"

Specifies a path to start searching from

https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.management/get-childitem?view=powershell-7

1 Comment

For newbs like my self: The -ErrorAction SilintlyContinue is very important. Some of Windows files are locked. They are locked even if you run as admininistrator. So if searching for files and folders recursively, it can be problematic and the command just stops with and error message.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.