以键为列标题将哈希表导出为 CSV [英] Export hashtable to CSV with the key as the column heading

查看:35
本文介绍了以键为列标题将哈希表导出为 CSV的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个脚本来创建一个哈希表,以用户名为键,以一组用户组为值.

I have a script to create a hashtable with usernames as the key and an array of their groups as the value.

这是它的样子:

Name                           Value
----                           -----
user1                          {Domain Users, group2, group3}
user2                          {Domain Users, group4}
user3                          {Domain Users, group2, group3, group4}

如何使用用户名作为标题将其导出到 CSV 文件中?

How can I export this into a CSV file using the username as the heading?

当我将 CSV 文件导入 Excel 时,我希望它看起来像这样:

When I import the CSV file into Excel I want it to look like this:

     A              B             C
  -------------------------------------------
1 | user1         user2         user3
2 | Domain Users  Domain Users  Domain Users
3 | group2        group4        group2
4 | group3                      group3
5 |                             group4

我玩过 Export-Csv,但无法让它适用于这种类型的哈希表.

I have played around with Export-Csv but cannot get it to work for this type of hashtable.

推荐答案

为了能够将数组作为列,您需要转置"您的哈希表,这意味着您需要构建具有用户名(哈希表)作为属性.您需要创建的对象数量由数组中的最大元素数定义.

To be able to get the arrays as columns you need to "transpose" your hashtable, meaning you need to build individual objects that have the usernames (the keys of the hashtable) as properties. The number of objects you need to create is defined by the maximum number of elements in the arrays.

基本上,您需要将哈希表分成多个哈希表,其中每个哈希表的所有键都只有一个字符串值,而不是字符串数组.本质上,您需要对此进行转换:

Basically, you need to chop up your hashtable into multiple hashtables where each hashtable has all keys with just a single string value instead of an array of strings. In essence, you need to transform this:

@{
  'user1' = 'Domain Users', 'group2', 'group3'
  'user2' = 'Domain Users', 'group4'
  'user3' = 'Domain Users', 'group2', 'group3', 'group4'
}

进入这个:

@{'user1' = 'Domain Users'; 'user2' = 'Domain Users'; 'user3' = 'Domain Users'}
@{'user1' = 'group2'; 'user2' = 'group4'; 'user3' = 'group2'}
@{'user1' = 'group3'; 'user2' = ''; 'user3' = 'group3'}
@{'user1' = ''; 'user2' = ''; 'user3' = 'group4'}

并从这些单独的哈希表创建对象.

and create objects from these individual hashtables.

$ht = @{
  'user1' = 'Domain Users', 'group2', 'group3'
  'user2' = 'Domain Users', 'group4'
  'user3' = 'Domain Users', 'group2', 'group3', 'group4'
}

# list array lengths and get highest number
$cnt  = $ht.Values |
        ForEach-Object { $_.Count } |
        Sort-Object |
        Select-Object -Last 1
$keys = $ht.Keys | Sort-Object

0..($cnt-1) | ForEach-Object {
  $props = [ordered]@{}
  foreach ($key in $keys) {
    $props[$key] = $ht[$key][$_]
  }
  New-Object -Type PSObject -Property $props
} | Export-Csv 'C:path	ooutput.csv' -NoType

这篇关于以键为列标题将哈希表导出为 CSV的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆