You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用PowerShell为JSON添加顶层ManagedIdentity键并整合脚本

问题

现有如下结构的JSON数组:

[
  {
    "DisplayName": "Title1",
    "SignInName": null,
    "RoleDefinitionName": "Name1",
    "RoleDefinitionId": "1111",
    "ObjectId": "0111",
    "ObjectType": "ServicePrincipal",
    "CanDelegate": false,
    "Description": null,
    "ConditionVersion": null,
    "Condition": null
  },
  {
    "DisplayName": "Title2",
    "SignInName": null,
    "RoleDefinitionName": "Name2",
    "RoleDefinitionId": "1111",
    "ObjectId": "02222",
    "ObjectType": "ServicePrincipal",
    "CanDelegate": false,
    "Description": null,
    "ConditionVersion": null,
    "Condition": null
  },
  {
    "DisplayName": "Title3",
    "SignInName": null,
    "RoleDefinitionName": "Name3",
    "RoleDefinitionId": "33333",
    "ObjectId": "03333",
    "ObjectType": "ServicePrincipal",
    "CanDelegate": false,
    "Description": null,
    "ConditionVersion": null,
    "Condition": null
  }
]

需要通过PowerShell脚本在顶层添加ManagedIdentity键,将原数组作为该键的值,最终得到如下结构:

{
"ManagedIdentity": [
  {
    "DisplayName": "Title1",
    "SignInName": null,
    "RoleDefinitionName": "Name1",
    "RoleDefinitionId": "1111",
    "ObjectId": "0111",
    "ObjectType": "ServicePrincipal",
    "CanDelegate": false,
    "Description": null,
    "ConditionVersion": null,
    "Condition": null
  },
  {
    "DisplayName": "Title2",
    "SignInName": null,
    "RoleDefinitionName": "Name2",
    "RoleDefinitionId": "1111",
    "ObjectId": "02222",
    "ObjectType": "ServicePrincipal",
    "CanDelegate": false,
    "Description": null,
    "ConditionVersion": null,
    "Condition": null
  },
  {
    "DisplayName": "Title3",
    "SignInName": null,
    "RoleDefinitionName": "Name3",
    "RoleDefinitionId": "33333",
    "ObjectId": "03333",
    "ObjectType": "ServicePrincipal",
    "CanDelegate": false,
    "Description": null,
    "ConditionVersion": null,
    "Condition": null
  }
]
}

要求将此功能整合到现有管道脚本Get-AzRoleAssignment -ObjectId 02222 | ConvertTo-Json中,在单个脚本块内完成处理。

解决方案

推荐两种简洁的实现方式:

方式一:哈希表直接构造(更高效)

@{ ManagedIdentity = Get-AzRoleAssignment -ObjectId 02222 } | ConvertTo-Json -Depth 10

方式二:管道对象包装

Get-AzRoleAssignment -ObjectId 02222 | ConvertTo-Json -Depth 10 | ConvertFrom-Json | Select-Object @{Name='ManagedIdentity'; Expression={$_}} | ConvertTo-Json -Depth 10

关键说明

  • 添加-Depth 10参数是为了规避PowerShell默认JSON序列化深度限制,防止嵌套结构被截断;
  • 方式一直接通过哈希表定义键值对,将命令输出作为ManagedIdentity的值,再转为JSON,逻辑更直观,执行效率更高;
  • 方式二通过管道先序列化再反序列化对象,用计算属性包装成目标结构后再次序列化,适合需要对中间对象做额外处理的场景。

内容的提问来源于stack exchange,提问作者Peter

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.21 00:06:23