0
votes

I have the following table (names are one column and colors are another column):

  1. Bob green
  2. Bob red
  3. Frank blue
  4. Frank yellow

that I need to be like this:

  1. Bob green, red
  2. Frank blue, yellow

I've attempted to use group-object in PowerShell but it just gives me the fields in an array. Essentially, I need to grab reach element in the second column (grouped by column 1) and add them as one row with a delimiter.

There's got to be a simple way of doing this that I'm missing.

2

2 Answers

1
votes

I'll go with Group-Object. Borrowing mjolinor's table here, this is the code I have that produces the same results:

$table = @(
[PSCustomObject]@{Name='Bob';Color='Green'}
[PSCustomObject]@{Name='Bob';Color='Red'}
[PSCustomObject]@{Name='Frank';Color='Blue'}
[PSCustomObject]@{Name='Frank';Color='Yellow'}
)

$Table | Group Name | ForEach{$_.Name + " " + ($_.Group.Color -join ",")}
0
votes

I'd use a hash table:

$table = @(
[PSCustomObject]@{Name='Bob';Color='Green'}
[PSCustomObject]@{Name='Bob';Color='Red'}
[PSCustomObject]@{Name='Frank';Color='Blue'}
[PSCustomObject]@{Name='Frank';Color='Yellow'}
)

$ht = @{}

$Table | 
 foreach { $ht[$_.Name] += @($_.Color) }

 $ht.GetEnumerator() |
  foreach {'{0} {1}' -f $_.Name,($_.Value -join ',') }

Bob Green,Red
Frank Blue,Yellow