2011-05-14 76 views
18

我有:如何在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 

我想要創建一個變量$總,(如哈希表),其包含每個項目的「平均值」欄的總數,例如,

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 
    } 

我怎麼能這樣做?

回答

5

我不知道你是否可以擺脫循環。怎麼樣:

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

感謝EMPO ......我越來越:本潑灑操作「@」不能用於引用上expressi 變量。 '@averages'只能用作命令的參數。要在表達式中引用vari ables,請使用'$ averages'。 ....這是我的問題,還是代碼問題? – ted 2011-05-14 05:42:00

+0

@ted:對不起。這是一個錯誤代碼,現在已經糾正。我仍然有點困;-) – 2011-05-14 05:48:09

+0

感謝empo,現在工作。 – ted 2011-05-14 05:59:48

40

的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 
7

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

鑑於$報告

$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}, @... 

然後

[email protected]{} 
$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} 
相關問題