user1697933
user1697933

Reputation: 11

Powershell hash table compare and append

I have a csv file like this :

userid;memberof
user1;groupid1
user2;groupid3
user1;groupid7
user2;groupid8

and I want to create csv a file like this :

user1;groupid1|groupid7
user2;groupid3|groupid8

I've seen on this forum that this could be done with hashtables but I couldn't succeed at it.

I have to say I'm new to powershell so excuse the question.

Upvotes: 1

Views: 1350

Answers (2)

dugas
dugas

Reputation: 12453

$original = Import-Csv .\a.csv -Delimiter ';'
$expression = {[string]::Join('|', ($_.Group | Select -expand memberof))}
$original | Group-Object userid | Select-Object @{n="userid";e={$_.Name}}, @{n="memberof";e=$expression} | Export-Csv ./b.csv -NoTypeInformation -Delimiter ';'

Upvotes: 0

Jaykul
Jaykul

Reputation: 15824

No need for excuses, that's a pretty tricky one ;)

Import-CSV YourFile.txt -Delim ";" | Group-Object userid | 
   Select-Object @{ name="UserId"
                    expr={$_.Name}},
                 @{ name="MemberOf"
                    expr={($_.Group |% { $_.memberof }) -join "|" }} |
   Export-CSV YourNewFile.txt -Delim ";" -NoTypeInformation

Note, that's going to include the header row "UserId;MemberOf" so if you really don't want that, then you should arrange to chop it off.

Instead of Export-CSV, use ConvertTo-CSV, assign it to a variable, and then write it out something like this:

 $output = ... | 
    ConvertTo-CSV -Delim ";" -NoTypeInformation 
 Set-Content YourNewFile.txt $output[1..($output.count)]

Upvotes: 1

Related Questions