如何在PowerShell中对对象中的多个项目求和?

时间:2011-05-14 05:07:17

标签: powershell

我有:

$report.gettype().name
Object[]

echo $report

Item                       Average
--                         -------
orange                     0.294117647058824
orange                    -0.901960784313726
orange                    -0.901960784313726
grape                      9.91335740072202
grape                      0
pear                       3.48736462093863
pear                      -0.0324909747292419
pear                      -0.0324909747292419
apple                     12.1261261261261
apple                     -0.0045045045045045

我想创建一个变量$ total,(例如哈希表),其中包含每个项目的“Average”列的总和,例如,

echo $total

orange  -1.5097
grape    9.913
pear     3.423
apple   12.116

现在我正在考虑循环播放$报告,但这很难看,而且我正在寻找比以下起点更优雅的东西(不完整):

$tmpPrev = ""
foreach($r in $report){
    $tmp = $r.item
    $subtotal = 0
    if($tmp <> $tmpPrev){
        $subtotal += $r.average
    }

我怎么能这样做?

3 个答案:

答案 0 :(得分:52)

Cmdlet Group-ObjectMeasure-Object有助于以PowerShell方式解决任务:

代码:

# Demo input
$report = @(
    New-Object psobject -Property @{ Item = 'orange'; Average = 1 }
    New-Object psobject -Property @{ Item = 'orange'; Average = 2 }
    New-Object psobject -Property @{ Item = 'grape'; Average = 3 }
    New-Object psobject -Property @{ Item = 'grape'; Average = 4 }
)

# Process: group by 'Item' then sum 'Average' for each group
# and create output objects on the fly
$report | Group-Object Item | %{
    New-Object psobject -Property @{
        Item = $_.Name
        Sum = ($_.Group | Measure-Object Average -Sum).Sum
    }
}

输出:

Sum Item
--- ----
  3 orange
  7 grape

答案 1 :(得分:9)

我有更多的命令行解决方案。

给出$ report

$groupreport = $report | Group-Object -Property item -AsHashTable

Name     Value
----     -----
grape    {@{Item=grape; Average=9.91335740072202}, @{Item=grape; Average=0}}
orange   {@{Item=orange; Average=0.294117647058824}, @{Item=orange; Average=-0.901960784313726...
apple    {@{Item=apple; Average=12.1261261261261}, @{Item=apple; Average=-0.0045045045045045}}
pear     {@{Item=pear; Average=3.48736462093863}, @{Item=pear; Average=-0.0324909747292419}, @...

然后

$tab=@{}
$groupreport.keys | % {$tab += @{$_ = ($groupreport[$_] | measure-object -Property average -sum)}}

给出

PS> $tab["grape"]

Count    : 2
Average  :
Sum      : 9,91335740072202
Maximum  :
Minimum  :
Property : Average

PS> $tab["grape"].sum
9,91335740072202

看似简短且可用。

<强>摘要

$groupreport = $report | Group-Object -Property item -AsHashTable
$tab = @{}
$groupreport.keys | % {$tab += @{$_ = ($groupreport[$_] | measure-object -Property average -sum)}}
$tab.keys | % {write-host $_ `t $tab[$_].sum}

答案 2 :(得分:5)

我不知道你是否可以摆脱循环。怎么样:

$report | % {$averages = @{}} {
    if ($averages[$_.item]) {
        $averages[$_.item] += $_.average
    }
    else {
        $averages[$_.item] = $_.average
    }
} {$averages}