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

如何在PowerShell中向多段JSON的Server模块添加新对象?

给JSON的Server节点CustomModules数组添加元素的方法

问题根源

你用ConvertFrom-Json解析出来的数组是固定长度的不可变数组,Add-Member是用来给对象添加新属性的,没法直接修改数组内容,所以得换个思路操作。

具体操作步骤

  1. 读取解析JSON(你的原有代码没问题,直接沿用):
$jsonfile = "你的JSON文件路径"
$json = Get-Content $jsonfile | Out-String | ConvertFrom-Json
  1. 创建要添加的模块对象:
    得把哈希表转成和原有数组元素一致的PSCustomObject,避免类型不匹配:
$newModule = [PSCustomObject]@{
    Name = "Test Server Module 3"
    Tag = "Server"
    Action = "Option I want"
    Image_Path = "C:/User/TestUser"
    Admin_Only = $true
}
  1. 合并数组并赋值:
    直接把新对象追加到原有数组,再重新赋值给Server.CustomModules:
# 两种写法任选其一
$json.Server.CustomModules += $newModule
# 或者
$json.Server.CustomModules = $json.Server.CustomModules + $newModule
  1. 写回JSON文件:
    记得加-Depth参数,防止嵌套结构被截断(默认深度仅为2,按需调大):
$json | ConvertTo-Json -Depth 10 | Set-Content $jsonfile

补充说明

如果你的CustomModules原本是空数组,上述方法同样适用,+=操作会自动生成包含新元素的数组。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.17 12:25:33