在Powershell中从json获取节点值

时间:2019-04-04 12:37:48

标签: json powershell

我在powershell变量中有json主体,想从中获取价值。

Json身体:

"value":  [
                  {
                      "id":  1,
                      "scope":  "3e93f9e6-f427-48e1-b37b-994d196e1121",
                      "name":  "Default",
                      "isHosted":  false,
                      "poolType":  "automation",
                      "size":  3
                  },
                  {
                      "id":  2,
                      "scope":  "3e93f9e6-f427-48e1-b37b-994d196e1121",
                      "name":  "Hosted",
                      "isHosted":  true,
                      "poolType":  "automation",
                      "size":  10
                  },
                  {
                      "id":  4,
                      "scope":  "3e93f9e6-f427-48e1-b37b-994d196e1121",
                      "name":  "Hosted VS2017",
                      "isHosted":  true,
                      "poolType":  "automation",
                      "size":  10
                  }]

我想获取id值,其中name =托管VS2017,即4

powershell:

Write-Host "json body:" $projects
$id = $projects.value | where { $_.name -eq "Hosted VS2017" }
Write-Host "id :" $id

1 个答案:

答案 0 :(得分:1)

您需要先将JSON转换为powershell对象,然后才能使用它:

$projects = $projects | ConvertFrom-Json

然后您可以访问其成员:

#requires -Version 3

$projects.value | ? name -eq 'Hosted VS2017'