如何使用Export-Csv将powershell的哈希表导出为CSV文件?

时间:2011-02-21 22:38:01

标签: powershell export hashtable export-to-csv

如何使用Export-Csv将powershell的哈希表导出为CSV文件?

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

我希望将其转换为CSV文件,其中每个键值对都在新行中。第一列应该是关键,下一列应该是值。

像这样:

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

非常感谢。

2 个答案:

答案 0 :(得分:3)

尝试这样的事情:

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",

答案 1 :(得分:0)

一种方式:

 $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