Powershell - add results when 2 fields match -
Powershell - add results when 2 fields match -
i have input info this:
type site count ====================== copper site1 10 copper site1 7 bronze site1 3 bronze site1 9 copper site2 32 copper site2 1 bronze site2 3 bronze site2 13
what have output this
type site count ====================== copper site1 17 bronze site1 12 copper site2 33 bronze site2 16
i have next code:
function getindex($location) { for($j = 0; $j -lt $result.count; $j++) { if($result[$j].location -contains "$location") { $index=$j break; } } homecoming $index } ($i=0; $i -lt $outarray.length; $i++) { $loc=$outarray[$i].location $pcount=$outarray[$i].'count' $ltype=$outarray[$i].'license type' if(!($result | where-object {$_.location -eq "$loc"})) { $result+=new-object psobject -property @{'location' = $loc; 'count' = $pcount; 'license type' = $ltype} } else { $index=getindex($loc) $result[$index].'count' = $result[$index].'count' + $pcount } }
but code produces output containing 1 type , miscounted figures count. attempted refine function modifying this:
function getindex($location) { for($j = 0; $j -lt $result.count; $j++) { if($result[$j].location -contains "$location" -and $result[$j].'license type' -contains "$item.licensetype") { $index=$j break; } } homecoming $index }
which results in index operation failing due array index beingness evaluated null. sense i'm missing simple here, can't figure out. help appreciated! thanks!
i used group-object , measure-object accomplish wanted. first grouping type, , assign variable current type used later in custom object. grouping site, , each site sum of counts, , output type, site, , sum custom object. setup test info array of objects have them in post. named $array
.
$array | grouping type | %{ $type = $_.name $_.group | grouping site | %{ [pscustomobject]@{ type=$type site=$_.name count=($_.group|measure-object count -sum).sum } } }
this outputs wanted:
type site count ---- ---- ----- copper site1 17 copper site2 33 bronze site1 12 bronze site2 16
powershell
Comments
Post a Comment