5

如何使用 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

非常感谢你。

4

2 回答 2

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",
于 2011-02-22T01:34:47.773 回答
1

单程:

 $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
于 2011-02-22T01:32:33.360 回答