powershell 解析多个关键字并将输出发送到文本文件

powershell Parsing for multiple keywords and sending output to a text file

我正在尝试编写一个 powershell cmdlet 来在文件的行中查找多个单词。例子。我需要解析 "word1", "word2", "word3" 在一个文件的同一行。我做错了什么,因为我试过没有成功:

(gci -File -Filter FileName | Select-String -SimpleMatch word1, word2,word3) > outputFileName.txt

其中 FileName = 文件名,outputFileName = 我搜索这三个词生成的文件。谢谢。

Select-String 没有任何我能想到的组合运算符。如果你的话总是按那个顺序,那么你可以做 -Pattern 'word1.*word2.*word3' 作为你的匹配,但如果它们可以按任何顺序排列,那么很快就会变得复杂。相反,我会看看

.. | Select-String 'word1' | Select-String 'word2' | Select-String 'Word3'

所以,所有匹配word1的行。其中,那些在某处匹配 word2 的。在那个更小的结果中,那些也匹配 word3.

试试这个:

$wordlist=@("word1", "word2", "word3")

Get-ChildItem "c:\temp\" -file |  %{$currentfile=$_.FullName; Get-Content $_.FullName | 
                    %{
                        $founded=$true
                        foreach ($item in $wordlist)
                        {
                            if (!$_.Contains($item))
                            {
                                $founded=$false
                                break
                            }
                        }

                        if ($founded)
                        {
                            $currentfile
                        }


                    }
}