【问题标题】:extract value between two square braces提取两个方括号之间的值
【发布时间】:2019-05-08 16:19:53
【问题描述】:

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

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

在 line: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.'}

【问题讨论】:

  • 你得到了什么输出?
  • 在 line:2 char:17 + $result = $cmd |([(?:[??[^[]*?])) + ~~~~~~~~~~ ~~~~~~~~~~~ 表达式只允许作为管道的第一个元素。 + CategoryInfo : ParserError: (:) [], ParentContainsErrorRecordException + FullyQualifiedErrorId : ExpressionsMustBeFirstInPipeline
  • 不要把信息放到cmets中,edit下次自己出题
  • $cmd 包含您通过管道传送到 WHAT 的输出?正则表达式需要一个运算符和引号。
  • infadev: 总是该块的一部分吗?如果是这样,它会使事情更加简单。 [咧嘴]

标签: powershell


【解决方案1】:

这是对这个想法的另一种看法。 [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

【讨论】:

    【解决方案2】:

    您可以使用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]
    ...
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-05-13
      • 2013-08-15
      • 1970-01-01
      • 2011-02-01
      • 1970-01-01
      • 1970-01-01
      • 2022-08-19
      相关资源
      最近更新 更多