提取两个方括号之间的值

时间:2019-05-08 16:19:53

标签: powershell

我需要从命令输出中的特定行中提取两个方括号之间的值。这是命令的输出。

C:\Informatica\PowerCenter\isp\bin> .\infacmd.bat ping -dn Infadomain -nn Node01
[INFACMD_10052] Node [Node01] Domain [Infadomain] Host:Port [infadev:6005] was successfully pinged.
[INFACMD_10470] Kerberos authentication is [disabled] and secure communication is [disabled] in the Informatica domain [Infadomain].
Command ran successfully.

从上面的输出中,我需要从上面的命令结果中提取值'infadev'。我尝试使用正则表达式函数来提取值,但是代码不起作用。

$cmd = Invoke-Command -ScriptBlock {& cmd.exe /c "infacmd.bat ping" -dn "Infadomain" -nn "Node01"}  | Where-Object {$_ -ne 'Command ran successfully.'}
$result = $cmd |(\[(?:\[??[^\[]*?\]))
write-host $result
  

在第2行:char:17 + $ result = $ cmd |([(?:[?? [^ [] *?]]))+ ~~~~~~~~~~~~~~ ~~~~~~仅允许将表达式作为管道的第一个元素。 + CategoryInfo:ParserError:(:) [],ParentContainsErrorRecordException + FullyQualifiedErrorId:ExpressionsMustBeFirstInPipeline

invoke-command -ScriptBlock {& cmd.exe /c "infacmd.bat ping" -dn "InfaDomain" -nn "Node01"} | Where-Object {$_ -ne 'Command ran successfully.'}

2 个答案:

答案 0 :(得分:0)

与使用Where -match相比,您可以使用$Matches[i]获取结果数组。

$cmd = Invoke-Command -ScriptBlock {& cmd.exe /c "infacmd.bat ping" -dn "Infadomain" -nn "Node01"}  | Where-Object {$_ -ne 'Command ran successfully.'}
$cmd | Where {$_ -match "(\[(?:\[??[^\[]*?\]))" }

$result0 = $Matches[0]
$result1 = $Matches[1]
...

答案 1 :(得分:0)

这是对该想法的另一种看法。 [ grin ]它使用命名的捕获组来捕获Host:Port文本之后的第一组带括号的数据。

$Cmd = @'
[INFACMD_10052] Node [Node01] Domain [Infadomain] Host:Port [infadev:6005] was successfully pinged.
[INFACMD_10470] Kerberos authentication is [disabled] and secure communication is [disabled] in the Informatica domain [Infadomain].
Command ran successfully.
'@ -split [environment]::NewLine

$Null = $Cmd.ForEach({$_ -match 'Host:Port \[(?<HostPortInfo>.+)\]'})

$Matches.HostPortInfo

输出...

infadev:6005