如何在PowerShell中向多段JSON的Server模块添加新对象?
给JSON的Server节点CustomModules数组添加元素的方法
问题根源
你用ConvertFrom-Json解析出来的数组是固定长度的不可变数组,Add-Member是用来给对象添加新属性的,没法直接修改数组内容,所以得换个思路操作。
具体操作步骤
- 读取解析JSON(你的原有代码没问题,直接沿用):
$jsonfile = "你的JSON文件路径" $json = Get-Content $jsonfile | Out-String | ConvertFrom-Json
- 创建要添加的模块对象:
得把哈希表转成和原有数组元素一致的PSCustomObject,避免类型不匹配:
$newModule = [PSCustomObject]@{ Name = "Test Server Module 3" Tag = "Server" Action = "Option I want" Image_Path = "C:/User/TestUser" Admin_Only = $true }
- 合并数组并赋值:
直接把新对象追加到原有数组,再重新赋值给Server.CustomModules:
# 两种写法任选其一 $json.Server.CustomModules += $newModule # 或者 $json.Server.CustomModules = $json.Server.CustomModules + $newModule
- 写回JSON文件:
记得加-Depth参数,防止嵌套结构被截断(默认深度仅为2,按需调大):
$json | ConvertTo-Json -Depth 10 | Set-Content $jsonfile
补充说明
如果你的CustomModules原本是空数组,上述方法同样适用,+=操作会自动生成包含新元素的数组。
内容的提问来源于stack exchange,提问作者Joe
相关产品推荐
相关产品推荐

