从一个变量中搜索一个字符串,只打印上面的3行

时间:2021-09-23 21:46:35

I've a variable with output similar to this:

我有一个输出类似这样的变量:

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

I may have 100 volumes but the variable returns only the disk with status "OFF".

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

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

I'm trying to push each 'failed / off' disk's 'logical disk tag' into another array.

我正在尝试将每个“失败/失败”磁盘的“逻辑磁盘标记”推入另一个数组。

Any hints on this please?

有什么提示吗?

1 个解决方案

#1


3  

You are already using the -Context parameter but you have to change the value to 3,0 which means that you capture 3 lines above the match and zero below. Then you have to access the context:

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

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

#1


3  

You are already using the -Context parameter but you have to change the value to 3,0 which means that you capture 3 lines above the match and zero below. Then you have to access the context:

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

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