使用“-filter”时:Get-ChildItem -file -filter "*.txt" | foreach-object { write-host $_.FullName
}
我得到了当前文件夹中 4 个 .txt 文件的列表。
我尝试使用“-include”
Get-ChildItem -file -include *.txt | foreach-object { write-host $_.FullName }
Get-ChildItem -file -include *txt | foreach-object { write-host $_.FullName }
我什么也得不到。我尝试了使用和不使用“-file”参数,它没有区别。
我查看了各种指南/示例(ss64.com/TechNet 等),据说我做得对。
有什么想法我可能做错了吗?谢谢!
最佳答案
来自 Get-Help
Get-ChildItem
的页面:
The
-Include
parameter is effective only when the command includes the-Recurse
parameter or the path leads to the contents of a directory, such asC:\Windows*
, where the "*
" wildcard character specifies the contents of theC:\Windows
directory.
您会注意到,如果您指定
-include
,则不会出现语法错误。并且不要指定 -recurse
尽管它所做的一切实际上都是未定义的。您还会注意到 C:\Windows*
不是“C:\Windows
目录中的所有文件”的普通通配符表达式。它是一个通配符表达式,表示“C:\
目录中所有以 'Windows' 开头并且可能有也可能没有扩展名的项目”。我不知道 Get-ChildItem
的作者是什么认为这个参数应该做的。他们在记录和实现它方面做得非常糟糕。因此,我避免使用
-Include
参数损坏/记录不全。我不知道它应该做什么 -Filter
没有。我读过关于它到底做什么的文章。它以某种方式“将值传递给底层提供者以在该级别进行过滤”。我不知道他们为什么认为系统管理员会知道这意味着什么。我的理解是调用 DirectoryInfo.GetFiles()
之间的区别在每个目录项上并调用 DirectoryInfo.GetFiles('*.txt')
在每个目录项上,但大多数系统管理员不会知道这意味着什么。但是,它的行为非常奇怪,以至于我不信任它,所以即使我对它的作用有 95% 的把握……我仍然从不使用它。相反,我只是通过管道发送到
Where-Object
:Get-ChildItem -file | Where-Object Extension -eq '.txt' | [...]
另请注意
Get-ChildItem
被 -LiteralPath
打破, -Recurse
和 -Include
在某些版本的 PowerShell 中,将返回所有项目。比较:
Get-ChildItem -LiteralPath $PSHOME *.exe -Recurse # works
Get-ChildItem -Path $PSHOME -Include *.exe -Recurse # works
Get-ChildItem -LiteralPath $PSHOME -Include *.exe -Recurse # does NOT work
报告的问题 here对于 v6。
关于powershell - Windows10/Powershell : How to use -include parameter when using Get-Childitem?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47048045/