Search code examples
powershellcsvjoingroup

How do I Join Cells from different rows in PowerShell


I am fairly new to PowerShell and just trying to get plug some gaps with my main support role using PowerShell, so far its been great however I am currently stuck on trying to find a solution for the following.

Here is a sample of the input data:

"Group Name","User ID"
"GROUP1","X9998988"
"GROUP1","X9982293"
"GROUP1","X9953089"
"GROUP1","X9952998"
"GROUP1","X9209289"
"GROUP1","X9205093"
"GROUP1","X9208889"
"GROUP1","X9292353"
"GROUP1","X9293330"
"GROUP1","X9229034"
"GROUP1","X9222338"
"GROUP2","X9205298"
"GROUP3","X9953800"
"GROUP3","X9933359"
"GROUP3","X9993288"

Here is an example of how I would like that data to look:

"Group Name","User ID"
"GROUP1","X9998988,X9982293,X9953089,X9952998,X9209289,X9205093,X9208889,X9292353,X9293330"
"GROUP2","X9205298"
"GROUP3","X9953800,X9933359,X9993288"

This is the code I have created so far, hopefully I am on the right track:

$csv_file = Import-Csv 'C:\Test\Other_Managers.csv' | 
    Group-Object 'Group Name' | ForEach-Object { 
        $groups = $_.Group.'Group Name'
        $users = $_.Group.'User ID'
    }

foreach ($row In $groups) {
    $output = $row | Select-Object @{Name = 'Group'; Expression = { $groups } },
    @{Name = 'Users'; Expression = { ($users -join ',') } }

    $output | Export-Csv -Path 'C:\Test\Other_Managers_out.csv' -NoTypeInformation
}

The Result:

"Group","Users"
"GROUP3 GROUP3 GROUP3","X9953800,X9933359,X9993288"

Solution

  • In your current code, right after Group-Object you're iterating over each group of objects and assigning the value of Group Name and User Id to those variables however that value is being re-assigned with each loop iteration leaving you with just the last object, this is why in your result you always see the last group (Group 3). In this case that ForEach-Object should be completely removed.

    Then in your next loop, @{Name = 'Group'; Expression = { $groups }} should be @{Name = 'Group'; Expression = 'Name' }, the name of the groups is represented by the .Name property. And the user Ids you want to join should be @{ N = 'User Id'; E = { $_.Group.'User Id' -join ',' }}.

    If you want to streamline the process this is how the code would look:

    Import-Csv 'C:\Test\Other_Managers.csv' |
        Group-Object 'Group Name' |
        Select-Object @(
            @{ N = 'Group Name'; E = 'Name' }
            @{ N = 'User Id'; E = { $_.Group.'User Id' -join ',' }}) |
        Export-Csv -Path 'C:\Test\Other_Managers_out.csv' -NoTypeInformation