从变量中搜索字符串并仅打印其上方的3行

时间:2016-09-26 12:16:56

标签: regex powershell

我有一个输出类似于此的变量:

Volume 1
logical disk tag = 0x207e799987
Name = test
disk state = OFF

我可能有100个卷,但变量只返回状态为“OFF”的磁盘。

$chk = "some command"
$off = "some command"
$offChk = $Chk | Select-String -Pattern $off -Context 1

我正在尝试将每个'失败/关闭'磁盘的'逻辑磁盘标记'推送到另一个阵列中。

对此有何提示?

1 个答案:

答案 0 :(得分:3)

您已使用-Context参数,但必须将值更改为3,0,这意味着您可以在匹配项上方捕获3行,并在下方输入零。然后你必须访问上下文:

(Select-String -Path 'yourFilePath' -Pattern 'disk state = OFF' -Context 3,0).Context.PreContext
相关问题