powershell - Windows10/Powershell : How to use -include parameter when using Get-Childitem?

标签 powershell

使用“-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 等),据说我做得对。

有什么想法我可能做错了吗?谢谢!

enter image description here

最佳答案

来自 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 as C:\Windows*, where the "*" wildcard character specifies the contents of the C:\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/

相关文章:

powershell - VS Code - Powershell 模块 - 命令无法识别

powershell - 如何确定命令输出对象?

Powershell - 在文本文件的开头添加文本字符串

powershell - 替换文件中的字符串,并获得有关所做操作的一些反馈

sorting - 使用自定义排序表达式进行 Powershell 排序

.net - 从 powershell 执行单向 wcf 服务操作

Powershell UseDefaultCredentials 在远程 session 中不起作用

powershell - PowerShell 是否有官方文字/保留符号引用?

其他用户的 Powershell gwmi

powershell - 使用Azure Powershell执行.sql文件