powershell - 与 Get-ChildItem cmdlet 的 -Include 参数混淆

标签 powershell include get-childitem

从文档:

-Include

Retrieves only the specified items. The value of this parameter qualifies the Path parameter. Enter a path element or pattern, such as "*.txt". Wildcards are permitted.

The Include parameter is effective only when the command includes the Recurse parameter or the path leads to the contents of a directory, such as C:\Windows*, where the wildcard character specifies the contents of the C:\Windows directory.



我的第一个理解是:
c:\test\a.txt
c:\test\b.txt

所以为了得到 'a.txt' 和 'b.txt' 我可以这样写:
gci -Path "c:\test\*" -Include "*.txt"

这有效。但现在考虑这样的层次结构:
c:\test\a.txt
c:\test\b.txt
c:\test\c.txt\c.txt

相同的命令返回:
a.txt, b.txt, c.txt

实际的逻辑似乎是:

-Include used to match all entities specified by -Path. If matched element is a file - return it. If matched element is a folder, look inside and return matching first level children.



另外,文档说:

The Include parameter is effective only when the command includes the Recurse parameter or the path leads to the contents of a directory...



这也是错误的。例如
gci -Path "c:\test" -Include "*.txt"

它什么都不返回,而没有 -Include 我得到文件夹内容。所以 -Include 绝对是“有效的”。这里到底发生了什么? -Path 指定“c:\test”,而 -Include 尝试匹配此路径。由于“*.txt”与“test”不匹配,所以没有返回。但是看看这个:
gci -Path "c:\test" -Include "*t"

它返回 a.txt、b.txt 和 c.txt 作为“*t”匹配“test”并匹配所有子项。

毕竟,即使现在知道 Include 是如何工作的,我也不明白什么时候使用它。为什么我需要它查看子文件夹内部?为什么要这么复杂?

最佳答案

您混淆了 -include 的使用。 -include 标志应用于路径,而不是路径的内容。如果不使用递归标志,唯一有问题的路径就是您指定的路径。这就是为什么您给出的最后一个示例有效的原因,路径 c:\test路径中有一个 t,因此匹配 "*t" .

您可以通过尝试以下操作来验证这一点

gci -path "c:\test" -in *e*

这仍然会产生目录中的所有 child ,但它不匹配他们的名字。

-include 对 recurse 参数更有效的原因是您最终将通配符应用于层次结构中的每个路径。

关于powershell - 与 Get-ChildItem cmdlet 的 -Include 参数混淆,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/790796/

相关文章:

powershell - 如何使用相对路径调用另一个 PowerShell 脚本?

powershell - foreach 循环的写入进度问题

android - 嵌套的preferences.xml

variables - Powershell-使用通配符搜索文件名

powershell - 您必须在 '-'运算符的右侧提供一个值表达式

python - 使用 numpy 扩展的 C 程序的 Makefile

c++ - 将项目分为.h和.cpp

powershell - 如何使用 Get-ChildItem 返回没有扩展名的文件?

powershell - Get-ChildItem递归排除不排除文件夹

function - 函数调用自身以枚举嵌套的组成员身份