0

I'm trying to do this in PowerShell. I've got a CSV file that looks like the following (note the ... means any number of values):

Name,...,Value
Adam,...,1
Bob,...,2
Chris,...,3
Adam,...,4
Bob,...,5
Chris,...,6

I want to add all the values for each person together so it outputs the below:

Name,...,Value
Adam,...,5
Bob,...,7
Chris,...,9

I'm using Group-Object to get a hash table.

$table = Import-CSV "c:\input-file" | Group-Object -Property Name -AsHashTable -AsString

But I'm not sure how to proceed to add the values up and then output to a CSV. Can anyone help? Or does anyone have another solution?

1

2 Answers 2

1

Just combine Group-Object, Select-Object and Measure-Object cmdlets to get what you want:

Import-Csv -Path "c:\input-file" | Group-Object Name | 
    Select-Object Name, 
                  @{Name = '...'; Expression = {($_.Group.'...')[0]}}, 
                  @{Name = 'Value'; Expression = { ($_.Group | Measure-Object Value -Sum).Sum }}

Output:

Name  ... Value
----  --- -----
Adam  ...     5
Bob   ...     7
Chris ...     9

P.S. In your example Chris,...3,, the comma should be before 3 as in Chris,...,3

Sign up to request clarification or add additional context in comments.

2 Comments

Ah yes, good pick up on the comma. Corrected it now, thanks!
Yes, I know. I had to test it first ;)
0

Hard to guess what the ... represents; taking it literally:

$csvIn = @'
Name,...,Value
Adam,...,1
Bob,...,2
Chris,...,3
Adam,...,4
Bob,...,5
Chris,...,6
'@ | ConvertFrom-Csv -Delimiter ',' # instead of `Import-CSV`
$csvOu = [System.Collections.ArrayList]::new()
$csvGr = $csvIn | Group-Object -Property Name
$csvGr | ForEach-Object {
    [void]$csvOu.Add(
        [pscustomobject]@{
            Name  = $_.Name
            '...' = '...'
            Value = $_.Group |
                Measure-Object -Property Value -Sum |
                Select-Object -ExpandProperty Sum
        }
    )
}
$csvOu #| ConvertTo-Csv -Delimiter ',' -NoTypeInformation

Output: .\SO\64316986.ps1

Name  ... Value
----  --- -----
Adam  ...     5
Bob   ...     7
Chris ...     9

1 Comment

The ... means any number of items. Sorry, it's more of a math term than programming term.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.