Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to export powershell's hashtable into CSV file using Export-Csv?

How to export powershell's hashtable into CSV file using Export-Csv ?

PS C:\>$UsersAndGroups
Name                           Value                                                                                                                                                             
----                           -----                                                                                                                                                             
user1                          {Group2}                                                                                                                    
user2                          {Group1, Group2, Group3}                                                                                                                                   
user3                          {Group3, Group4}     

I want to get this into CSV file where each key-value pair is in new line. First column should allways be key and next columns should be values.

Like this:

|col1    col2    col3    col4   
 +------------------------------  
1|User1  Group2  
2|User2  Group1  Group2  Group3 
3|User3  Group3  Group4

Thank you very much.

like image 404
Primoz Avatar asked Oct 12 '22 16:10

Primoz


1 Answers

Try something like this:

PS> $ht = @{user1=,'Group2';user2='Group1','Group2','Group3';
            user3='Group3','Group4'}

PS> $ht.GetEnumerator() | 
     Foreach {$obj = new-object psobject -prop @{col1=$_.Name}; $_.Value | 
        Foreach {$i=2} `
                {Add-Member NoteProperty "col$i" $_ -Inp $obj; $i++} {$obj} } | 
     Sort {$_.psobject.properties.count} -desc | ConvertTo-Csv -NoTypeInformation

"col1","col2","col3","col4"
"user2","Group1","Group2","Group3"
"user1","Group2",,
"user3","Group3","Group4",
like image 193
Keith Hill Avatar answered Oct 18 '22 01:10

Keith Hill