Davor Josipovic
Davor Josipovic

Reputation: 5504

Wildcard matching in Get-ChildItem in PowerShell

Is there a way to determine how wildcard matching is done in Get-ChildItem?

Various articles (1, 2) suggest that it is done through the WildcardPattern class, but I don’t think this is the case. For example, suppose you have a file in C:\test\test2\testfile.txt. Then Get-ChildItem –Path “C:\*\testfile.txt” will not find the file while WildcardPattern::IsMatch will. Wildcard "*" matching in Get-ChildItem seems to be on directory level: so "\*\" will never match more than one level, like "\A\B\".

So if WildcardPattern class isn't used, then what is?

Upvotes: 1

Views: 3151

Answers (3)

Frode F.
Frode F.

Reputation: 54871

From what I know, it's using the WildcardPattern as you describe. However, the cmdlet Get-ChildItem limits it to the current directory (characters except \), so it won't conflict with the -Recurse switch that goes to unlimited levels.

Upvotes: 1

Adil Hindistan
Adil Hindistan

Reputation: 6605

Either would work:

gci c:\test\*\testfile.txt

or

gci c:\*\testfile.txt -recurse

Example:

PS C:\temp\test2> dir


    Directory: C:\temp\test2


Mode                LastWriteTime     Length Name
----                -------------     ------ ----
-a---          4/4/2013  10:41 PM          0 testfile.txt


PS C:\temp\test2> cd \
PS C:\> gci c:\*\testfile.txt -recurse -ea SilentlyContinue


    Directory: C:\Temp\test2


Mode                LastWriteTime     Length Name
----                -------------     ------ ----
-a---          4/4/2013  10:41 PM          0 testfile.txt

Upvotes: 0

Shay Levy
Shay Levy

Reputation: 126722

With "C:\*\testfile.txt", the asterisk plays a role just for the first level directory (e.g test). The file you're looking for is not there and the output you get is expected. Add another asterisk for the second level and you'll get the desired output (e.g "C:\*\*\testfile.txt"). You can also add the Recurse switch to start searching from the current location, all the way downwards.

Upvotes: 0

Related Questions