Powershell:通过字符串数组过滤文件的内容

JMa*_*sch 17 powershell

谜我这个:

我有一个数据文本文件.我想读它,并且只输出包含搜索词数组中找到的任何字符串的行.

如果我只找一个字符串,我会做这样的事情:

get-content afile | where { $_.Contains("TextI'mLookingFor") } | out-file FilteredContent.txt
Run Code Online (Sandbox Code Playgroud)

现在,我只需要将"TextI'mLookingFor"作为字符串数组,其中如果$ _包含数组中的任何字符串,则将其传递到管道外的文件.

我该怎么做(而且顺便说一下,我是程序员黑客攻击这个powershell脚本,所以如果有更好的方法来完成我的匹配而不是使用.Contains(),请告诉我!)

Fro*_* F. 34

试试Select-String.它允许一系列模式.例如:

$p = @("this","is","a test")
Get-Content '.\New Text Document.txt' | Select-String -Pattern $p -SimpleMatch | Set-Content FilteredContent.txt
Run Code Online (Sandbox Code Playgroud)

请注意,我使用-SimpleMatch这样Select-String忽略特殊的正则表达式字符.如果你想在你的模式中使用正则表达式,那就删除它.

对于单个模式,我可能会使用它,但您必须在模式中转义正则表达式字符:

Get-Content '.\New Text Document.txt' | ? { $_ -match "a test" }
Run Code Online (Sandbox Code Playgroud)

Select-String 对于单个模式来说,它也是一个很棒的cmdlet,编写^^只需要几个字符


mjo*_*nor 5

有什么帮助吗?

$a_Search = @(
    "TextI'mLookingFor",
    "OtherTextI'mLookingFor",
    "MoreTextI'mLookingFor"
    )


[regex] $a_regex = ‘(‘ + (($a_Search |foreach {[regex]::escape($_)}) –join “|”) + ‘)’

(get-content afile) -match $a_regex 
Run Code Online (Sandbox Code Playgroud)