You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

在PowerShell中格式化输出嵌套字典并转换为CSV表格

PowerShell嵌套哈希表的美观格式化输出与CSV转换

一、美观格式输出

要实现预期的对齐式表格输出,可通过遍历顶级键和子键,结合字符串格式化控制对齐:

$testHashMap = @{
    'feature1' = @{
        'Audit'  = 1
        'Space'  = 2
        'Usage' = 3
    }
    'feature2' = @{
        'Audit'  = 4
        'Space'  = 5
        'Usage' = 3
    }
}

# 获取排序后的特性名称和子项键
$features = $testHashMap.Keys | Sort-Object
$subKeys = $testHashMap[$features[0]].Keys | Sort-Object

# 定义列宽,确保内容对齐
$columnWidth = 18

# 输出表头
"$(' ' * ($columnWidth - $features[0].Length))$($features[0]) | $($features[1])"
# 输出分隔线
"-" * $columnWidth + "|" + "-" * $columnWidth

# 遍历子键,逐行生成内容
foreach ($key in $subKeys) {
    $val1 = $testHashMap[$features[0]][$key]
    $val2 = $testHashMap[$features[1]][$key]
    # 格式化每行,保证键名和值对齐
    "$($key.ToLower()):$(' ' * ($columnWidth - $key.Length - 2))$val1 | $(' ' * ($columnWidth - $val2.ToString().Length - 1))$val2"
}

执行后输出符合预期的对齐表格:

feature1  | feature2 
------------------|----------------
audit:     1      |   4
space:     2      |   5
usage:     3      |   3

二、转换为CSV表格

要将嵌套哈希表转为可导出的CSV格式,需先把嵌套结构扁平化为标准对象,再执行导出:

# 初始化存储CSV行的数组
$csvData = @()

# 遍历每个子键,生成一行数据
foreach ($key in $subKeys) {
    # 创建自定义对象,子键作为"Item"列
    $row = [PSCustomObject]@{
        'Item' = $key.ToLower()
    }
    # 为每个特性添加对应的列和值
    foreach ($feature in $features) {
        $row | Add-Member -MemberType NoteProperty -Name $feature -Value $testHashMap[$feature][$key]
    }
    $csvData += $row
}

# 在控制台预览表格
$csvData | Format-Table -AutoSize

# 导出到CSV文件(无类型信息)
$csvData | Export-Csv -Path ".\features_summary.csv" -NoTypeInformation

导出的CSV内容示例:

Item,feature1,feature2
audit,1,4
space,2,5
usage,3,3

内容的提问来源于stack exchange,提问作者Ichigo Kurosaki

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.20 18:40:18