从文本文件中的数组中搜索字符串

时间:2018-02-05 21:29:33

标签: windows powershell

我想在文本文件中搜索多个字符串。如果我找到至少1个字符串(我重复,我只需要找到一个字符串,而不是所有字符串)我希望程序停止并创建一个文件,我将在其中找到文本:“found” 这是我的代码不能正常工作:

$f = 'C:\users\datboi\desktop\dump.dmp'

$text = 'found'

$array = "_command",".command","-
command","!command","+command","^command",":command","]command","[command","#command","*command","$command","&command","@command","%command","=command","/command","\command","command!","command@","command#","command$","command%","command^","command&","command*","command-","command+","command=","command\","command/","command_","command.","command:"

$len    = 9
$offset = 8

$data = [IO.File]::ReadAllBytes($f)


for ($i=0; $i -lt $data.Count - $offset; $i++) {
$slice = $data[$i..($i+$offset)]
$sloc = [char[]]$slice

  if ($array.Contains($sloc)){
    $text > 'command.log'
    break 
}
}

当我说它不能正常工作时我的意思是:它运行,没有错误,但即使文件包含数组中的至少一个字符串,它也不会创建我想要的文件。

2 个答案:

答案 0 :(得分:1)

这就是为Select-String cmdlet创建的字面意思。您可以使用正则表达式来简化搜索。对于RegEx,我会使用:

[_\.-!\+\^:]\[\#\*\$&@%=/\\]command|command[_\.-!\+\^:\#\*\$&@%=/\\]

归结为[]括号中的任何字符后跟单词'command',或单词'command'后跟[]括号中的任何字符。然后将其传递到ForEach-Object循环,输出到您的文件并中断。

Select-String -Path $f -Pattern '[_\.-!\+\^:]\[\#\*\$&@%=/\\]command|command[_\.-!\+\^:\#\*\$&@%=/\\]' | ForEach{
    $text > 'command.log'
    break
}

答案 1 :(得分:1)

首先,我建议使用正则表达式,因为您可以大大缩短代码。

其次,PowerShell擅长模式匹配。

示例:

$symbolList = '_\-:!\.\[\]@\*\/\\&#%\^\+=\$'
$pattern = '([{0}]command)|(command[{0}])' -f $symbolList
$found = Select-String $pattern "inputfile.txt" -Quiet
$found

$symbolList变量是一个正则表达式模式,包含您希望在搜索字符串中的“命令”一词之前或之后找到的字符列表。

$pattern变量使用$symbolList来创建模式。

如果在文件中找到模式,$found变量将为$true