如何用PowerShell向JSON配置文件指定位置添加连接配置
问题
我有一个作为配置文件的JSON,内容如下:
{ "managedApiConnections": { "Testoffice365_Connection_1": { "api": { "id": "/subscriptions/.../office365" }, "authentication": { "type": "ManagedServiceIdentity" }, "connection": { "id": "/subscriptions/.../Test_Connection_1" }, "connectionRuntimeUrl": "https://.../office365/xxx3501" }, "Testsql_Connection_1": { "api": { "id": "/subscriptions/xxx/providers/Microsoft.Web/locations/eastasia/managedApis/sql" }, "authentication": { "type": "ManagedServiceIdentity" }, "connection": { "id": "/subscriptions/xxxx/resourceGroups/xxxx/providers/Microsoft.Web/connections/sql_SIT" }, "connectionProperties": { "authentication": { "audience": "https://database.windows.net/", "type": "ManagedServiceIdentity" } }, "connectionRuntimeUrl": "https://8xxxx.02.common.logic-eastasia.azure-apihub.net/apim/sql/xxxx1b" } }, "serviceProviderConnections": { "Testblob_Connection_1": { "displayName": "blobxxx", "parameterSetName": "ManagedServiceIdentity", "parameterValues": { "authProvider": { "Type": "ManagedServiceIdentity" }, "blobStorageEndpoint": "@appsetting('blob_url_test')" }, "serviceProvider": { "id": "/serviceProviders/AzureBlob" } }, "Testsql_Connection_2": { "displayName": "SQL_xxxx", "parameterSetName": "ManagedServiceIdentity", "parameterValues": { "authProvider": { "Type": "ManagedServiceIdentity" }, "databaseName": "xxxx ", "managedIdentityType": "SystemAssigned", "serverName": "xxxx.database.windows.net" }, "serviceProvider": { "id": "/serviceProviders/sql" } } } }
现在需要实现自动化新增Office 365连接实例:使用给定的JSON模板(移除最外层大括号),替换占位符后,将新连接配置添加到managedApiConnections下的Testoffice365_Connection_1节点之前。模板内容如下:
{ "<APIConnectionName>_<DeployENV>": { "api": { "id": "/subscriptions/<subscriptionsID>/providers/Microsoft.Web/locations/eastasia/managedApis/office365" }, "authentication": { "type": "ManagedServiceIdentity" }, "connection": { "id": "/subscriptions/<subscriptionsID>/resourceGroups/<resourceGroups>/providers/Microsoft.Web/connections/<APIConnectionName>_<DeployENV>" }, "connectionRuntimeUrl": "https://xxxx/office365/<connectionRuntimeUrl>" } }
请问如何用PowerShell脚本实现该需求?
解决方案
实现步骤
- 定义占位符参数,替换模板中的变量
- 将模板转换为有序结构,保证插入位置可控
- 读取原始配置并转为有序字典,维持原有键的顺序
- 在指定节点前插入新连接配置
- 将修改后的内容序列化回JSON并写入文件
PowerShell脚本示例
# 1. 配置核心参数 $configPath = "path/to/your/config.json" # 替换为实际配置文件路径 $apiConnectionName = "NewOffice365" # 替换为实际API连接名称 $deployEnv = "Prod" # 替换为实际部署环境 $subscriptionId = "your-subscription-id" # 替换为实际订阅ID $resourceGroup = "your-resource-group" # 替换为实际资源组名称 $connectionRuntimeUrl = "new-runtime-url" # 替换为实际连接运行时URL # 2. 生成替换后的连接配置 $newConnKey = "$apiConnectionName`_$deployEnv" $newConnection = [System.Collections.Specialized.OrderedDictionary]::new() $newConnection[$newConnKey] = [ordered]@{ api = [ordered]@{ id = "/subscriptions/$subscriptionId/providers/Microsoft.Web/locations/eastasia/managedApis/office365" } authentication = [ordered]@{ type = "ManagedServiceIdentity" } connection = [ordered]@{ id = "/subscriptions/$subscriptionId/resourceGroups/$resourceGroup/providers/Microsoft.Web/connections/$newConnKey" } connectionRuntimeUrl = "https://xxxx/office365/$connectionRuntimeUrl" } # 3. 读取并解析原始配置为有序结构 $configContent = Get-Content -Path $configPath -Raw | ConvertFrom-Json -AsHashtable # 将managedApiConnections转为有序字典,保证键顺序可控 $orderedManagedApis = [System.Collections.Specialized.OrderedDictionary]::new() foreach ($key in $configContent.managedApiConnections.Keys) { $orderedManagedApis[$key] = $configContent.managedApiConnections[$key] } # 4. 在指定位置插入新连接 $targetKey = "Testoffice365_Connection_1" $keys = $orderedManagedApis.Keys.ToArray() $insertIndex = [Array]::IndexOf($keys, $targetKey) $updatedManagedApis = [System.Collections.Specialized.OrderedDictionary]::new() if ($insertIndex -ge 0) { # 先添加目标键之前的原有配置 for ($i = 0; $i -lt $insertIndex; $i++) { $updatedManagedApis[$keys[$i]] = $orderedManagedApis[$keys[$i]] } # 添加新连接 $updatedManagedApis[$newConnKey] = $newConnection[$newConnKey] # 添加目标键及之后的原有配置 for ($i = $insertIndex; $i -lt $keys.Count; $i++) { $updatedManagedApis[$keys[$i]] = $orderedManagedApis[$keys[$i]] } } else { # 目标键不存在时,直接追加到末尾 $updatedManagedApis = $orderedManagedApis $updatedManagedApis[$newConnKey] = $newConnection[$newConnKey] } # 5. 更新配置并写回文件 $configContent.managedApiConnections = $updatedManagedApis $configContent | ConvertTo-Json -Depth 10 | Set-Content -Path $configPath -Encoding UTF8 Write-Host "新连接已成功添加到指定位置"
脚本说明
- 使用
OrderedDictionary确保JSON键的顺序,严格实现"插入到指定节点之前"的需求 - 通过
-AsHashtable解析JSON,方便直接操作键值对 - 设置
-Depth 10避免嵌套JSON结构被截断 - 兼容目标节点不存在的边界情况,此时自动追加到
managedApiConnections末尾
内容的提问来源于stack exchange,提问作者Joy
相关产品推荐
相关产品推荐

