Powershell - 路径中的 Get-ChildItem 星号通配符 - 使用参数 -File 时出现奇怪的行为

Jan*_*jci 3 windows powershell path asterisk

当我使用 Get-ChildItem cmdlet 时,我发现了一种奇怪的行为

文件夹结构:

d:\test\fooA\foo\1-9.txt files
d:\test\fooB\foo\1-9.txt files
d:\test\fooC\foo\1-9.txt files
d:\test\fooD\foo\1-9.txt directories
Run Code Online (Sandbox Code Playgroud)

当我使用以下语法时,我将从所有递归文件夹中获取所有 1-9.txt 文件和目录。它按预期工作。

Get-ChildItem -Filter *.txt -Path D:\test\*\foo -Recurse
Run Code Online (Sandbox Code Playgroud)

当我添加参数 -Directories 时,我仅从示例中的最后一个文件夹中获取目录。它也按预期工作。

Get-ChildItem -Directory -Filter *.txt -Path D:\test\*\foo -Recurse
Run Code Online (Sandbox Code Playgroud)

当我添加参数 -File 而不是 -Directories 时,我什么也得不到。我预计我只会得到文件。

Get-ChildItem -File -Filter *.txt -Path D:\test\*\foo -Recurse
Run Code Online (Sandbox Code Playgroud)

当我使用参数 -File 和 -Directory 时,我也什么也得不到。

Get-ChildItem -Directory -File -Filter *.txt -Path D:\test\*\foo -Recurse
Run Code Online (Sandbox Code Playgroud)

我在不同的 Windows 系统上测试了 PowerShell 版本 5.1 和 7。从我的角度来看,它看起来更像是错误,而不是代码中的问题,或者我对这个 cmdlet 用法的理解,有人可以仔细检查和评论吗?我可以通过额外的编码来解决我的问题,但我不明白为什么它适用于文件夹而不适用于文件。

非常感谢您的任何评论。

Cpt*_*ale 5

这是 Powershell 的文件系统提供程序的一个已知错误。在指定或参数Get-ChildItem时使用它。由于存在破坏现有内容的风险,它可能永远不会被修复:-File-Name

https://github.com/PowerShell/PowerShell/issues/9014

推荐的选项是通过管道连接到Where-Object过滤器,例如:

# Exclude directories
Get-ChildItem -Filter *.txt  -Path 'D:\test\*\foo' -Recurse | Where { -not $_.PSIsContainer }
Run Code Online (Sandbox Code Playgroud)