powershell - 在 Powershell 中,如何找到包含文本的文件名或其中包含文本的文件
问题描述
我正在递归地搜索目录。我想查找包含我要查找的文本的文件,或者该文本在文件的内容中。
例如,如果我搜索“hello”,我通常会这样做:
查找匹配的文件名:
get-childitem -filter "*hello*"
查找其中包含文本的文件:
get-childitem -recurse | select-string -pattern "*hello*"
但我想同时做这两件事。这意味着您可以拥有名称中没有“hello”但它确实出现在文件内容中的文件。或者反之亦然。
编辑:我考虑将 where-object 与 -or 一起使用,但无法弄清楚如何正确构建它。
编辑:我的错误,意味着在示例中包含选择字符串。
想法?
谢谢
解决方案
我认为它不可能使用-Filter
,因为您可能会排除那些内容可能包含您要查找的单词的文件。
我能想到的一种简单方法是递归遍历所有文件$startPath
,如果文件名中包含该单词,则转到下一次迭代,continue
或者break
如果您想在第一次查找时停止循环,当然,使用-Raw
对于Get-Content
:
$startPath = 'C:\path\to\startFolder'
$magicWord = 'hello'
foreach($file in Get-ChildItem $startPath -Recurse -File)
{
if($file.Name -match $magicWord)
{
$file
continue
# or break here if you want to stop the loop
}
if((Get-Content $file.FullName -Raw) -match $magicWord)
{
$file
# break here if you want to stop the loop
}
}
不确定使用它是否会更快:
if([system.io.file]::ReadAllText($file.FullName) -match $magicWord)
{
...
}
推荐阅读
- excel - 根据另一个表中的参数过滤结果
- strapi - 获取所有可用的语言环境,Strapi
- xcode - 如何创建键盘快捷键以在 Mac 上启动 xcode
- azure-active-directory - Microsoft 演示租户中的用户限制
- c# - 有没有办法确保页面重定向在 IIS 上有效
- azure-appservice - Azure 应用服务自定义域限制
- postgresql - 如何提高仅在 varchar(5000) 字段上具有索引且大小为 7.5GB 的表的性能?
- python - 使用子进程从另一个调用一个 py 脚本
- python - ImportError:无法从“imgaug.augmentables.segmaps”导入名称“SegmentationMapsOnImage”
- python - Python 的 Minzinc 路径是什么?