You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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 -Recurse parameter tells Get-ChildItem to 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:

  1. First, PowerShell resolves the ** wildcard, which matches the only direct subdirectory of TestRecurse: dir1.
  2. Here's the key quirk: when -Recurse combines with ** that only matches direct first-level subdirectories, PowerShell implicitly includes the parent directory (TestRecurse itself) in the traversal. This happens because ** can technically match "zero levels of subdirectories" (i.e., the current directory).
  3. The command ends up traversing two paths:
    • TestRecurse: returns b.txt (from the root) and a.txt (from dir1)
    • dir1: returns a.txt
  4. After deduplication, you get both b.txt and a.txt.

Scenario 2: a.txt is in dir1\dir2

Your updated directory structure:

TestRecurse
|---b.txt
|---dir1
|------dir2
|---------a.txt

Running the same command:

  1. Now, ** matches two subdirectories: dir1 and dir1\dir2 (since ** targets all depth levels).
  2. When -Recurse kicks in, it only traverses the directories explicitly matched by **—the implicit inclusion of the parent TestRecurse directory no longer applies.
  3. The command traverses:
    • dir1: recurses into dir2 and returns a.txt
    • dir1\dir2: directly returns a.txt
  4. Since the parent TestRecurse isn't being traversed, b.txt never 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.27 06:50:21