Select-字符串,只显示匹配的行而不是整个对象

Select-String to only show the line that matches not entire object

我怎样才能让它只显示单行,而不是整个对象,就像 bash 中的 grep 一样。 Out-String -Stream 应该将其转换为字符串,我有大量的 jsons 结构,目前我在 python onelines

中过滤
Get-Service | Select-Object -Property Name | Where-Object -Property Name -Match "Winrm" |\
ConvertTo-Json | Out-String -Stream | Select-String -SimpleMatch 'Name'

{
    "Name":  "WinRM"
}

Python oneliner有点不方便:-) :

Get-Service | ConvertTo-Json | \
python.exe -c "import sys,re;[sys.stdout.write(l) for l in sys.stdin if re.search(r'WinRM', l)]"                                
        "ServiceName":  "WinRM",
        "Name":  "WinRM",

Select-String 适用于字符串数组,return 是与模式匹配的元素。您的 JSON 字符串仍然是单个字符串,但是如果您在换行符上拆分它,则可以使用 Select-String 命令仅获取包含 Name 的行并省略大括号。以下示例有助于说明这一点。

$TestJSON = @'
{
    "Name":  "WinRM"
}
'@

$TestJSON | Select-String -Pattern 'Name'
# {
#     "Name":  "WinRM"
# }


($TestJSON.Split([Environment]::NewLine) | Select-String -Pattern 'Name' | Out-String).Trim() # Note that 'Trim' removes whitespace around your desired value
# "Name":  "WinRM"

因此,为了将它们放在一起,您可以获得 Name 属性 并且它的值具有 JSON 格式,但没有使用以下一行的大括号。

Get-Service | Where-Object { $_.Name -eq "WinRM" } | Select-Object -Property Name | ConvertTo-Json | ForEach-Object { $_.Split([Environment]::NewLine) } | Select-String -Pattern "Name" | Out-String | ForEach-Object { $_.Trim() }
# "Name":  "WinRM"

并通过这个...

  • 我们得到所有的服务
  • 我们过滤掉 WinRM 服务
  • 我们selectName属性
  • 我们将其转换为 JSON
  • 我们在每个换行符上拆分 JSON 输出以生成一个字符串数组
  • 我们return包含Name
  • 的字符串数组的元素
  • 我们将管道中的任何内容转换为字符串
  • 我们使用Trim函数去除字符串周围的空格