So I have been trying to solve this problem for a couple of days and just can't seem to find anything that works, so I am hoping you may be able to help or point me in the right direction.
I am creating a powershell script that creates service accounts in Active Directory, at the very end of the script the username and password and then stored in an Enterprise Password Vault. A REST Api is used to store the credentials within this Vault. I am having a slight issue converting my powershell into nested Json, without the nested it works fine...
The JSON output I need to get to is this:
{
"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"},
]
}
}
and this is my Powershell excluding nesting of "properties" which works fine.
$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
The problems start when I try to add to my powershell
"properties":
[
{"Key":"Title", "Value":"Test Account"},
{"Key":"Description", "Value":"REQ0000001"},
]
I think my first problem is that the word Key is also a powershell keyword.
I have tried a lot of different combinations and tried lots of things from other articles I have found, but the majority of things I am finding are to do with parsing a nested Jason back via Powershell.
Hope that all makes sense.
The code below works for me (PS v4) and seems to return json in the format you want.
$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
the output of the above...
{
"account": {
"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"
}
]
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With