在PowerShell中打印嵌套的Dictonary(将其转换为CSV)

zujrkrfu  于 2023-05-26  发布在  Shell
关注(0)|答案(1)|浏览(121)

我有一个嵌套字典,一个字典也包含一个字典。

  • 我怎么能写他们漂亮的格式,并将其转换为CSV表。(通过键使用forloop和foreach)
$testHashMap = @{
    'feature1' = @{
        'Audit'  = 1
        'Space'  = 2
        'Usage' = 3
    }
    'feature2' = @{
        'Audit'  = 4
        'Space'  = 5
        'Usage' = 3
    }
}

**Expected Output:**

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

sq1bmfud1#

您的示例(预期)表结构对于PowerShell表格式无效。
下面是你可以尝试的最简单的解决方案:

$testHashMap = [PSCustomObject][Ordered]@{
    'feature1' = [PSCustomObject][Ordered]@{
        'Audit'  = 1
        'Space'  = 2
        'Usage' = 3
    };
    'feature2' = [PSCustomObject][Ordered]@{
        'Audit'  = 4
        'Space'  = 5
        'Usage' = 3
    };
}

这将给予你一个测试过的表输出,如:

feature1                     feature2                    
--------                     --------                    
@{Audit=1; Space=2; Usage=3} @{Audit=4; Space=5; Usage=3}

如果你想在表格中显示特征名称,你可以引入一个新的列,如下所示:

($testHashMap | gm -MemberType NoteProperty).Name | %{ $FeatureName = $_; Select-Object -InputObject $testHashMap -ExpandProperty $_ -Property @{Name="FeatureName"; e={$FeatureName}} }

这将给予如下输出:

Audit Space Usage FeatureName
----- ----- ----- -----------
    1     2     3 feature1   
    4     5     3 feature2

相关问题