如何在PowerShell中对对象中的多个项目求和? [英] How to sum multiple items in an object in PowerShell?
本文介绍了如何在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"列的总和,例如,
I want to create a variable, $total, (such as a hash table) which contains the sum of the 'Average' column for each item, for example,
echo $total
orange -1.5097
grape 9.913
pear 3.423
apple 12.116
现在我正在考虑遍历 $report,但它太丑了,我正在寻找比以下起点更优雅的东西(不完整):
Right now I'm thinking of looping through the $report, but it's hell ugly, and I am looking for something more elegant than the following starting point (incomplete):
$tmpPrev = ""
foreach($r in $report){
$tmp = $r.item
$subtotal = 0
if($tmp <> $tmpPrev){
$subtotal += $r.average
}
我怎么能这样做?
推荐答案
Cmdlets Group-Object 和 Measure-Object 有助于以 PowerShell-ish 方式解决任务:
Cmdlets Group-Object and Measure-Object help to solve the task in a PowerShell-ish way:
代码:
# 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
这篇关于如何在PowerShell中对对象中的多个项目求和?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文