PowerShell中GCI加Recurse与通配符返回结果异常问题
Why does
Get-ChildItem 'path\**' -Recurse return unexpected files based on subfolder depth? Great question—this behavior boils down to the tricky interaction between PowerShell's ** recursive wildcard and the -Recurse parameter. Let's break it down step by step:
First, clarify the core behaviors
- The
**wildcard (PowerShell 3.0+) is designed to match any depth of subdirectories under a target path. By default, it targets directories, not files. - The
-Recurseparameter tellsGet-ChildItemto traverse all levels of subdirectories under the specified path and return all contained items.
Walk through your two scenarios
Scenario 1: a.txt is directly in dir1
Your directory structure:
TestRecurse |---b.txt |---dir1 |------a.txt
When you run gci 'C:\temp\TestRecurse\**' -Recurse:
- First, PowerShell resolves the
**wildcard, which matches the only direct subdirectory ofTestRecurse:dir1. - Here's the key quirk: when
-Recursecombines with**that only matches direct first-level subdirectories, PowerShell implicitly includes the parent directory (TestRecurseitself) in the traversal. This happens because**can technically match "zero levels of subdirectories" (i.e., the current directory). - The command ends up traversing two paths:
TestRecurse: returnsb.txt(from the root) anda.txt(fromdir1)dir1: returnsa.txt
- After deduplication, you get both
b.txtanda.txt.
Scenario 2: a.txt is in dir1\dir2
Your updated directory structure:
TestRecurse |---b.txt |---dir1 |------dir2 |---------a.txt
Running the same command:
- Now,
**matches two subdirectories:dir1anddir1\dir2(since**targets all depth levels). - When
-Recursekicks in, it only traverses the directories explicitly matched by**—the implicit inclusion of the parentTestRecursedirectory no longer applies. - The command traverses:
dir1: recurses intodir2and returnsa.txtdir1\dir2: directly returnsa.txt
- Since the parent
TestRecurseisn't being traversed,b.txtnever shows up in the results.
Wrap-up
This isn't a bug—it's an edge case of how PowerShell handles the combination of ** and -Recurse. The implicit parent directory inclusion only triggers when ** matches only direct, first-level subdirectories. Once ** matches deeper subdirectories, that implicit behavior drops off, and only the matched subdirectories are traversed.
内容的提问来源于stack exchange,提问作者Brady S
相关产品推荐
相关产品推荐

