首页 > 解决方案 > 在 Powershell 中,如何找到包含文本的文件名或其中包含文本的文件

问题描述

我正在递归地搜索目录。我想查找包含我要查找的文本的文件,或者该文本在文件的内容中。

例如,如果我搜索“hello”,我通常会这样做:

查找匹配的文件名:

get-childitem -filter "*hello*"

查找其中包含文本的文件:

get-childitem -recurse | select-string -pattern "*hello*"

但我想同时做这两件事。这意味着您可以拥有名称中没有“hello”但它确实出现在文件内容中的文件。或者反之亦然。

编辑:我考虑将 where-object 与 -or 一起使用,但无法弄清楚如何正确构建它。

编辑:我的错误,意味着在示例中包含选择字符串。

想法?

谢谢

标签: powershell

解决方案


我认为它不可能使用-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)
{
    ...
}

推荐阅读