使用 PowerShell 循环和搜索 JSON

Looping and searching through JSON using PowerShell

我有一个 JSON 文件,其中包含以下内容:

{
  "status": "UP",
  "details": {
    "graphDBCheck": {
      "status": "UP"
    },
    "ds": {
      "status": "UP",
      "details": {
        "total": 100,
        "free": 50,
        "threshold": 30
      }
    },
    "db": {
      "status": "UP",
      "details": {
        "ADS": {
          "status": "UP",
          "details": {
            "database": "Influx",
            "hello": "Hello"
          }
        },
        "EARDS": {
          "status": "UP",
          "details": {
            "database": "Oracle",
            "hello": "Hello"
          }
        },
        "EFRDS": {
          "status": "UP",
          "details": {
            "database": "Sybase",
            "hello": "Hello"
          }
        }
      }
    }
  }
}

我需要能够将其转换为 CSV 文件,其中每个元素的名称为 header,其状态或值作为下一行。首先 "status" 会有列名 "API_Status"

例如:

API_Status,graphDBCheck,ds,db,ADS,EARDS,EFRDS
UP,UP,UP,UP,UP,UP,UP

这里的挑战是使其动态化,以便输出将始终包含添加的任何其他元素,其中包含 "status"。

我试过这个并且它有效,但我需要一个动态的方法来做到这一点:

$x = Invoke-RestMethod $url -Verbose:$VerbosePreference

[pscustomobject][ordered]@{
'API_Status' = $x.status
'db' = $x.details.db.status
'ds' = $x.details.diskspace.status
'ds_Total' = $x.details.ds.details.total
'ds_Free' = $x.details.ds.details.free
'graphDBCheck' = $x.details.graphDBCheck.status
'ADS' = $x.details.db.details.auroraDataSource.status
'EARDS' = $x.details.db.details.EARDS.status
'EFRDS' = $x.details.db.details.edsFirstRowsDataSource.status
}

在理想情况下,json 的结构应该是这样的,作为具有统一属性的可扩展数组。

[
  {
    "name": "API_Status",
    "status": "UP"
  },
  {
    "name": "graphDBCheck",
    "status": "UP"
  },
  {
    "name": "ds",
    "status": "UP"
  },
  {
    "name": "db",
    "status": "UP"
  },
  {
    "name": "ADS",
    "status": "UP"
  },
  {
    "name": "EARDS",
    "status": "UP"
  },
  {
    "name": "EFRDS",
    "status": "UP"
  }
]

或作为 csv:

name,status
API_Status,UP
graphDBCheck,UP
ds,UP
db,UP
ADS,UP
EARDS,UP
EFRDS,UP

还有很多关于循环遍历 powershell 属性的其他帖子 or looping through json properties: