How to transform multiple objects with same name into one object with the sum?

Viewed 54

Drawing a weird blank here as i'm sure i've done this before. I have these objects:

Name01 Capacity0
------ ---------
P1234       4096
P1234       4096
P1234       4096

How do i turn it into only one object containing the sum of all 'capacity0' like this? :

Name01 Capacity0
------ ---------
P1234       12288

I know how to get the sum for example:

... Select Name01,Capacity0 | Measure-Object -Property Capacity0 -sum

but then i lose the 'name01' property if i pipe it like that.

What's the best way? Something with group-object maybe? Struggling with the logic i should use. Much appreciated.

1 Answers

Yes, group by Name01 first, then select the grouped Sum:

... | Select Name01, Capacity0 `
| Group-Object -Property Name01 `
| Select `
    @{Label = "Name01"; Expression={$_.Name}}, 
    @{Label = "Sum"; Expression = {($_.Group | Measure-Object -Property Capacity0 -Sum).Sum}}

Result:

Name01   Sum
------   ---
P1234  12288
Related