owners
我的输出中的键(请参阅OutputFile)我期望作为行分隔的数组,但它作为单行空格分隔的对象/字符串输出
脚本:
function Add-ApplicationOwner
{
param (
[string] $App,
[object] $OutputObject
)
# add values to our json output
$owners = (Get-AzureAdApplicationOwner -ObjectId $App).UserPrincipalName
$OutputObject | Add-Member -MemberType NoteProperty -Name owners -Value $owners
}
$inputFile = Get-Content -Path "AppInput.json" -Raw | ConvertFrom-Json
$outputFile = New-Object -TypeName PsObject
foreach ($object in $inputFile.PSObject.Properties)
{
$outputAppList = New-Object -TypeName PsObject
foreach ($app in $inputFile.New.PsObject.Properties)
{
# create app
$appRegistration = New-AzureADApplication -DisplayName "TestSPN1"
#add application info into json object
$outputAppValues = [PsCustomObject]@{
app_id = $appRegistration.AppId
}
#add application owners by object id
Add-ApplicationOwner -App $appRegistrationObjectId -OutputObject $outputAppValues
$outputAppList | Add-Member -MemberType NoteProperty -Name "TestSPN1" -Value $outputAppValues
}
# add all created apps into json output file
$outputFile | Add-Member -MemberType NoteProperty -Name "New Applications" -Value $outputAppList
}
$outputFile | ConvertTo-Json | Out-File "AzADAppRegistrationInfo.json" -Append
输出文件:
{
"New Applications": {
"TestSPN1": {
"app_id": "dsfadfdafa-3afadfdafadsfasd-343",
"owners": "user1 user2 user3"
}
}
}
所需输出:
{
"New Applications": {
"TestSPN1": {
"app_id": "dsfadfdafa-3afadfdafadsfasd-343",
"owners": [
"user1",
"user2",
"user3"
]
}
}
}
检查 $owners 变量:
$owners
user1
user2
user3
$owners.gettype()
IsPublic IsSerial Name BaseType
-------- -------- ---- --------
True True Object[] System.Array
当我查看 $outputFile.'New Applications' 时,它符合预期
$outputFile.'New Applications' | convertto-json
{
"TestSPN1": {
"app_id": "asdfdsfad",
"owners": [
"user1",
"user2",
"user3"
]
}
}
当我查看 $outputFile 时,它被展平了
$outputFile | convertto-json
{
"New Applications": {
"TestSPN1": {
"app_id": "cc6dgfsdgdsgfsdgfdsa5562614",
"owners": "user1 user2 user3"
}
}
}
最佳答案
对您的问题最令人喜欢的解释是 -Depth
使用默认值。对于下面的示例,我已将 $outputFile.'New Applications'
存储在 $json
变量中。
[pscustomobject]@{
'New Applications' = $json
} | ConvertTo-Json
结果:
WARNING: Resulting JSON is truncated as serialization has exceeded the set depth of 2.
{
"New Applications": {
"TestSPN1": {
"app_id": "asdfdsfad",
"owners": "user1 user2 user3"
}
}
}
值得指出的是,警告消息仅在较新版本的 PowerShell 上显示(准确地说是 PS 7.1+,感谢 mklement0 指出)。 Windows PowerShell 默认截断 JSON,且不发出任何警告。
但是,如果我们添加 1 个深度级别(默认 -Depth
值为 2):
[pscustomobject]@{
'New Applications' = $json
} | ConvertTo-Json -Depth 3
结果:
{
"New Applications": {
"TestSPN1": {
"app_id": "asdfdsfad",
"owners": [
"user1",
"user2",
"user3"
]
}
}
}
关于json - PowerShell - JSON/PsCustomObject - 为什么我的数组会被展平为单个对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71729183/