【问题标题】:Calculate values from results of Invoke-RestMethod in PowerShell根据 PowerShell 中 Invoke-RestMethod 的结果计算值
【发布时间】:2021-08-10 13:00:24
【问题描述】:

我能够通过 Invoke-RestMethod 从提供以下格式的 API 取回数据:

    1612142668000000000 : @{peak_performance=29.18; current_utilization=19.15}
    1612146268000000000 : @{peak_performance=29.05; current_utilization=20.03}
    1612149868000000000 : @{peak_performance=29.07; current_utilization=18.86}

如果有帮助,上面的JSON格式是:

{
  "1612142668000000000": {
    "peak_performance": 29.18,
    "current_utilization": 19.15
  },
  "1612146268000000000": {
    "peak_performance": 29.05,
    "current_utilization": 20.03
  },
  "1612149868000000000": {
    "peak_performance": 29.07,
    "current_utilization": 18.86
  }
}

我希望能够计算并显示所有可用的peak-performancecurrent_utilization 值的平均值,但我不知道该怎么做。有什么想法吗?

【问题讨论】:

  • 有点笨拙,因为 API 返回的是嵌套对象而不是数组;这意味着您必须遍历属性。类似($response.PSObject.Properties.Value | Measure-Object -Property current_utilization,peak_performance -Average,必要时进行进一步处理。

标签: json powershell invoke-restmethod


【解决方案1】:

有很多解决方案:

$json = @"
{
  "1612142668000000000": {
    "peak_performance": 29.18,
    "current_utilization": 19.15
  },
  "1612146268000000000": {
    "peak_performance": 29.05,
    "current_utilization": 20.03
  },
  "1612149868000000000": {
    "peak_performance": 29.07,
    "current_utilization": 18.86
  }
}
"@

$jout = $json | ConvertFrom-Json
$result = $jout.PSObject.Properties.Value | Measure-Object -Property current_utilization,peak_performance -Average

foreach($v in $result){
    Write-Host $v.Property   " = "  $v.Average
}

结果:

current_utilization  =  19.3466666666667
peak_performance  =  29.1

【讨论】:

    猜你喜欢
    • 2015-02-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-06-20
    • 1970-01-01
    相关资源
    最近更新 更多