JohnDoe
JohnDoe

Reputation: 13

How do I group and sum CSV rows by shared column value?

I'm new with powershell and I am currently stuck with an issue.

I import a CSV file with 2 columns (ServerName, and Size) like this :

Server | Size
-------------
SRV1   | 140

SRV2   | 120

SRV1   | 100

SRV1   | 140

SRV2   | 200

I want to add all Size values for each server, for example:

SRV2 = 120+200
SRV1 = 140+100+140

I have no idea how to do it. I tried with a for loop, but the operation is done for each line, so my results are false. Could anyone help me ?

Upvotes: 1

Views: 4330

Answers (2)

mklement0
mklement0

Reputation: 438263

Use:

Import-Csv file.csv | Group-Object Server | 
  Select-Object Name, @{ n='Size'; e={ ($_.Group | Measure-Object Size -Sum).Sum } }

If you want the first output column to be named Server, replace Name with @{ n='Server'; e='Name' }

With your sample data, the above yields:

Name Size
---- ----
SRV1  380
SRV2  320

Upvotes: 4

guiwhatsthat
guiwhatsthat

Reputation: 2434

Here is an example how you could do it:

$Data = Import-Csv -Path "yourfilepath" -Delimiter ";"

$SortedData = $Data | Group {$_.server}
$Hashtable = @{}
$SortedData.group | ForEach-Object {
    if ($Hashtable.Contains($_.server)) {
        $Hashtable[$_.server] += ",$($_.size)"
    } else {
        $Hashtable.Add($_.server,$_.size)
    }
}

You need to change your delimiter in your case

Upvotes: 0

Related Questions