Search code examples
arrayspowershellgroup-byforeachsum

PowerShell group object Cumulative / Running total


My data looks like below

 Name   Numbers
 Bob    1
 Bob    1
 Bob    0
 Tom    1
 Tom    0
Steve   0
Steve   1

Would like the end result to look like this:

Name    Numbers Total numbers
Bob     1        1
Bob     1        2
Bob     0        2
Tom     1        1
Tom     0        1
Steve   0        0
Steve   1        1

I have tried group Object -

Import-Csv 'C:\New folder\test.txt' | Group-Object Pitcher |
Select-Object Name, Numbers, @{ n='Total numbers'; e={ ($_.Group.Numbers) } }

And also this:

$csvfile='C:\New folder\test.txt'
$csvlength = (Get-Content "C:\New folder\test.txt").length
[int]$Sum = 0`
$csv=Import-csv -Path $csvfile -ea 0 | Sort-Object Name
for($i=0; $i -lt $csvlength; $i++) {``foreach($row in $csv){ 
    if($previous){
        if($previous.Name -eq $row.Name){
            $Sum += $row.Numbers
        }
    }
    $previous = $row
}

Solution

  • Assuming this is a Csv you can use a hash table to keep track of each Total Count for each value in Name then construct a new object using a calculated property:

    $map = @{}
    Import-Csv $csvPath | ForEach-Object {
        $map[$_.Name] += $_.Numbers -as [int]
        $_ | Select-Object *, @{N='Total numbers'; E={ $map[$_.Name] }}
    }
    

    Output should look like this using the example data:

    Name  Numbers Total numbers
    ----  ------- -------------
    Bob   1                   1
    Bob   1                   2
    Bob   0                   2
    Tom   1                   1
    Tom   0                   1
    Steve 0                   0
    Steve 1                   1