PowerShell多文件多关键词搜索:仅返回匹配项及对应文件名
PowerShell 文件搜索解决方案
直接用这条单行命令就能满足你的需求,只返回匹配的数组元素和对应文件名:
Get-ChildItem . | Select-String -Pattern $data | Select-Object -Property Filename, Pattern -Unique
为什么原来的命令不行?
- 你之前用
Get-ChildItem -name只返回纯文件名,不是完整的文件对象,后续Get-Content会丢失文件关联信息 Select-String可以直接接收Get-ChildItem输出的文件对象,不用先读取内容,既高效又能保留文件元数据
可选优化
如果想让输出更整齐,改成表格格式:
Get-ChildItem . | Select-String -Pattern $data | Select-Object -Property Filename, Pattern -Unique | Format-Table -AutoSize
如果需要搜索子目录里的文件,给Get-ChildItem加-Recurse参数:
Get-ChildItem . -Recurse | Select-String -Pattern $data | Select-Object -Property Filename, Pattern -Unique
内容的提问来源于stack exchange,提问作者sf2k
相关产品推荐
相关产品推荐

