Powershell聚合嵌套数组值

时间:2019-07-31 15:50:12

标签: powershell

如何获取“平均值”列以收集平均值?

我拥有的最接近的东西是:

$metric_result | Format-Table -Property @{label='Name';e={$_.Name.Value}},Unit,@{label='Average';e={$_.Data.Average}}

Name                               Unit Average
----                               ---- ---
Percentage CPU                  Percent {$null, $null, $null, $null…}
Disk Read Operations/Sec CountPerSecond {$null, $null, $null, $null…}

我想要一个最终的输出,看起来像:

Name                               Unit Average
----                               ---- ----
Percentage CPU                  Percent 0.234
Disk Read Operations/Sec CountPerSecond 0.043

我有一个Powershell System.Array $metric_result,看起来像这样:

Id         : /my/special/id
Name       :
                LocalizedValue : Percentage CPU
                Value          : Percentage CPU

Type       : Microsoft.Insights/metrics
Unit       : Percent
Data       : {Microsoft.Azure.Commands.Insights.OutputClasses.PSMetricValue…}
Timeseries : {Microsoft.Azure.Management.Monitor.Models.TimeSeriesElement}

Id         : /my/special/id2
Name       :
                LocalizedValue : Disk Read Operations/Sec
                Value          : Disk Read Operations/Sec

Type       : Microsoft.Insights/metrics
Unit       : CountPerSecond
Data       : {Microsoft.Azure.Commands.Insights.OutputClasses.PSMetricValue…}
Timeseries : {Microsoft.Azure.Management.Monitor.Models.TimeSeriesElement}

$metric_result.Data字段是一个值的集合,如下所示:

TimeStamp : 7/30/2019 11:39:00 PM
Average   : 0.292142857142857
Minimum   :
Maximum   :
Total     :
Count     :

2 个答案:

答案 0 :(得分:1)

尝试这样的事情:

$metric_result | ForEach-Object {
    [PSCustomObject]@{
        ID      = $_.ID
        Name    = $_.Name.LocalizedValue
        Unit    = $_.Unit
        Average = "{0:N3}" -f ($_.Data.Average|Measure -Ave).Average 
    }
}

答案 1 :(得分:1)

尝试了一些先前的答案并阅读了here,有关为每个InputObject创建计算的属性之后,这就是我要做的工作

$average = @{l="Average";e={($_.Data.Average | Measure-Object -Average).Average}}
$local_name = @{l='Name';e={$_.Name.LocalizedValue}}

$metric_result | Select-Object -Property $local_name,Unit,$average


Name                               Unit Average
----                               ---- ----
Percentage CPU                  Percent 0.234
Disk Read Operations/Sec CountPerSecond 0.043