How to export powershell hash table to CSV file using Export-Csv?

How to export powershell hash table to CSV file using Export-Csv?

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

I want to get this in a CSV file, where each pair of keys and values ​​is on a new line. The first column should always be the key, and the next columns should be the values.

Like this:

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

Thank you very much.

+4
source share
2 answers

One of the methods:

  $usersandgroups = @{ user1 = @("group2") user2 = @("group1","group2","group3") user3 = @("groupt3","group4") } $exp = @("col1,col2,col3,col4") $usersandgroups.keys |%{ $exp += (@($_) + $usersandgroups.$_) -join "," } $exp $exp | out-file test.csv $imp = import-csv test.csv $imp | ft -auto col1,col2,col3,col4 user3,groupt3,group4 user1,group2 user2,group1,group2,group3 col1 col2 col3 col4 ---- ---- ---- ---- user3 groupt3 group4 user1 group2 user2 group1 group2 group3 
0
source

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", 
+3
source

Source: https://habr.com/ru/post/1340707/


All Articles