Powershell 中 Get-ChildItem cmdlet 的不明确行为

Ambiguous behavior by Get-ChildItem cmdlet in Powershell

我正在尝试获取本地文件夹中所有 txt 文件的列表。

$dir = "C:\report\"
Get-ChildItem -Path $dir -File -Include "*.txt"

上面的代码 returns 什么都没有,但是当我在路径前面添加通配符 * 时,该命令按预期工作并且 returns txt 文件列表。

$dir = "C:\report\*"
Get-ChildItem -Path $dir -File -Include "*.txt"

没有 -Include "*.txt" 参数,在这两种情况下我都会得到所有文件的列表(System.IO.FileInfo 对象)

我想知道为什么添加 -Include "*.txt" 会导致这种不明确的行为? 我是 PowerShell 的新手,我使用的是 Powershell 7。 提前致谢。

Include 参数在与 Recurse 开关组合时起作用,或者正如您通过将 \* 附加到路径所注意到的那样,这意味着递归。

如果您不希望 cmdlet 在子文件夹中递归,请改用 -Filter '*.txt'