将 Powershell 转换为嵌套的 Json

A.L*_*say 3 powershell json

所以我已经尝试解决这个问题几天了,但似乎找不到任何有效的方法,所以我希望你能帮助我或指出正确的方向。

我正在创建一个在 Active Directory 中创建服务帐户的 powershell 脚本,在脚本的最后是用户名和密码,然后存储在 Enterprise Password Vault 中。REST Api 用于在此 Vault 中存储凭据。我在将我的 powershell 转换为嵌套的 Json 时遇到了一个小问题,没有嵌套它工作正常......

我需要得到的 JSON 输出是这样的:

{
"account":{
    "safe":"Test_safe",
    "platformID":"WindowsDomainAccount",
    "address":"ad.local",
    "password":"password",
    "username":"test",
    "disableAutoMgmt":"true",
    "disableAutoMgmtReason":"test",
    "properties":
    [
    {"Key":"Title", "Value":"Test Account"},
    {"Key":"Description", "Value":"REQ0000001"},
    ]
  }
}
Run Code Online (Sandbox Code Playgroud)

这是我的 Powershell,不包括工作正常的“属性”嵌套。

   $hash = [ordered]@{
        account = [ordered]@{
            safe="ServiceAccounts"; 
            platformID="WindowsDomainAccount";
            address="ad.local";
            password="Password1";
            username="svc-test";
            disableAutoMgmt="true";
            disableAutoMgmtReason="testing";
        }
   }

$json = $hash | ConvertTo-Json

$invoke = Invoke-Webrequest -Uri $url -Method "POST" -Body $json -ContentType "application/json" -Header @{"Authorization" = $header} -ErrorAction Stop -ErrorVariable WebError
Run Code Online (Sandbox Code Playgroud)

当我尝试添加到我的 powershell 时,问题就开始了

"properties":
    [
    {"Key":"Title", "Value":"Test Account"},
    {"Key":"Description", "Value":"REQ0000001"},
    ]
Run Code Online (Sandbox Code Playgroud)

我想我的第一个问题是 Key 这个词也是一个 powershell 关键字。

我尝试了很多不同的组合,并尝试了我发现的其他文章中的很多内容,但我发现的大部分内容与通过 Powershell 解析嵌套的 Jason 相关。

希望一切都有意义。

Tec*_*pud 5

下面的代码适用于我(PS v4)并且似乎以您想要的格式返回json。

$hash = [ordered]@{
    account = [ordered]@{
        safe="ServiceAccounts"; 
        platformID="WindowsDomainAccount";
        address="ad.local";
        password="Password1";
        username="svc-test";
        disableAutoMgmt="true";
        disableAutoMgmtReason="testing";

        properties = @(
            @{"Key"="Title"; "Value"="Test Account"},
            @{"Key"="Description"; "Value"="REQ0000001"}
        )

    }
}

$json = $hash | ConvertTo-Json -Depth 99
$json
Run Code Online (Sandbox Code Playgroud)

上面的输出...

$hash = [ordered]@{
    account = [ordered]@{
        safe="ServiceAccounts"; 
        platformID="WindowsDomainAccount";
        address="ad.local";
        password="Password1";
        username="svc-test";
        disableAutoMgmt="true";
        disableAutoMgmtReason="testing";

        properties = @(
            @{"Key"="Title"; "Value"="Test Account"},
            @{"Key"="Description"; "Value"="REQ0000001"}
        )

    }
}

$json = $hash | ConvertTo-Json -Depth 99
$json
Run Code Online (Sandbox Code Playgroud)

  • `-Depth 99` 就是我一直在寻找的:) (2认同)