PowerShell 的嵌套数据类型输出

标签 powershell

我正在尝试根据某些输入创建嵌套数据结构并最终将其转换为 JSON,但一旦它变得太深,我就会遇到麻烦。

该结构将是一个哈希数组,其中一项是另一个哈希数组。

这设置了两个哈希数组 $baz1$baz2

PS D:\> $baz1 = @(@{foo="foo1"; bar="bar1"};@{foo="foo2";bar="bar2"};@{foo="foo3";bar="bar3"})
PS D:\> $baz2 = @(@{foo="foo1"; bar="bar1"};@{foo="foo2";bar="bar2"};@{foo="foo3";bar="bar3"})

如您所见,一切都在板上:

PS D:\> $baz1

Name                           Value
----                           -----
bar                            bar1
foo                            foo1
bar                            bar2
foo                            foo2
bar                            bar3
foo                            foo3


PS D:\> $baz1|ConvertTo-Json
[
    {
        "bar":  "bar1",
        "foo":  "foo1"
    },
    {
        "bar":  "bar2",
        "foo":  "foo2"
    },
    {
        "bar":  "bar3",
        "foo":  "foo3"
    }
]
PS D:\>

但是当我将数组添加到 $fuz 时,一切都变成了梨形:

PS D:\> $fuz = @(@{foo="bar"; bash=$baz1};@{foo="beep";bash=$baz2})
PS D:\> $fuz

Name                           Value
----                           -----
foo                            bar
bash                           {System.Collections.Hashtable, System.Collections.Hashtable, System.Collections.Hashtable}
foo                            beep
bash                           {System.Collections.Hashtable, System.Collections.Hashtable, System.Collections.Hashtable}


PS D:\> $fuz|ConvertTo-Json
[
    {
        "foo":  "bar",
        "bash":  [
                     "System.Collections.Hashtable",
                     "System.Collections.Hashtable",
                     "System.Collections.Hashtable"
                 ]
    },
    {
        "foo":  "beep",
        "bash":  [
                     "System.Collections.Hashtable",
                     "System.Collections.Hashtable",
                     "System.Collections.Hashtable"
                 ]
    }
]

即使没有 $baz1 步骤

PS D:\> @(@{foo="bar"; bash=@(@{foo="foo1"; bar="bar1"};@{foo="foo2";bar="bar2"};@{foo="foo3";bar="bar3"})};@{foo="beep";bash=$baz2})

Name                           Value
----                           -----
foo                            bar
bash                           {System.Collections.Hashtable, System.Collections.Hashtable, System.Collections.Hashtable}
foo                            beep
bash                           {System.Collections.Hashtable, System.Collections.Hashtable, System.Collections.Hashtable}


PS D:\>

非常感谢这里的一些帮助!

最佳答案

使用 ConvertTo-Json cmdlet 上的 -Depth 参数来展开子属性值。

关于PowerShell 的嵌套数据类型输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21264136/

相关文章:

string - Powershell子串切割

xml - 需要帮助在XML FILE中插入子节点

powershell - 获取未在特定日期范围内写入的文件/文件夹

C# 从 powershell 脚本获取变量

string - 如何使用多个字符的字符串在 PowerShell 中 "split"字符串?

xml - 使用 powershell 将文件夹结构转换为 XML 文件

powershell - 管道和 $_ 在 PowerShell 中如何工作?

exception - 防止第三方 dll 使 PowerShell 崩溃

rest - 如何使用用户名和密码(无应用程序 ID)向 Azure REST API 进行身份验证

powershell - 如何在 Powershell 类中抑制 "Unapproved verbs"