【问题标题】:Select-String -Quiet not returning TrueSelect-String -Quiet 不返回 True
【发布时间】:2016-08-22 21:31:28
【问题描述】:

我的脚本应该获取 VNC 的 TCP 连接信息并告诉我连接状态何时为ESTABLISHED。使用Select-String -Quiet 时,我一直试图获得True 的返回值。

PS C:\> $vnc = netstat -ab | select-string "winvnc4.exe" -context 1,0
PS C:\> $vnc

    TCP    0.0.0.0:5800           User:0               LISTENING
>  [winvnc4.exe]
    TCP    0.0.0.0:5900           User:0               LISTENING
>  [winvnc4.exe]
    TCP    [::]:5800              User:0               LISTENING
>  [winvnc4.exe]
    TCP    [::]:5900              User:0               LISTENING
>  [winvnc4.exe]

PS C:\> $vnc | Select-String "LISTENING" -quiet

PS C:\> $vnc | Select-String -Pattern "LISTENING" -quiet

PS C:\> $vnc | Select-String "LISTENING" -simplematch -quiet

如您所见,我尝试了几个不同的参数来获得结果,但没有返回任何内容。

【问题讨论】:

  • 您的代码按预期工作:我看到返回“True”。你有没有遗漏任何代码,无论多么不重要?
  • 这就是一切。我什至关闭了 ISE 并以管理员身份重新打开(就像我第一次尝试一样),但它仍然没有返回任何内容。 PS C:\> get-host | select Version Version ------- 5.0.10586.494

标签: powershell netstat select-string


【解决方案1】:

您的第一个 Select-String 会生成一个 MatchInfo 对象列表。您需要的信息存储在这些的Context 属性中。您需要先扩展它,然后才能在其上运行另一个 Select-String

$vnc | Select-Object -Expand Context |
    Select-Object -Expand PreContext |
    Select-String 'LISTENING' -SimpleMatch -Quiet

在 PowerShell v3 和更新版本上,您可以使用 member enumeration 使其更紧凑:

$vnc | ForEach-Object { $_.Context.PreContext } |
    Select-String 'LISTENING' -SimpleMatch -Quiet

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-12-20
    • 2021-07-25
    • 2018-02-24
    • 2013-05-11
    • 2016-11-17
    • 2018-12-03
    • 2013-01-07
    相关资源
    最近更新 更多