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

如何用PowerShell将source.json最新ID复制到target.json的backupRunId

PowerShell实现JSON字段值替换方案

完整实现代码

# 读取source.json并解析为可操作对象
$sourceJson = Get-Content -Path ".\source.json" -Raw | ConvertFrom-Json
# 提取items数组首个元素的id值
$targetBackupRunId = $sourceJson.items[0].id

# 读取target.json并解析为可操作对象
$targetJson = Get-Content -Path ".\target.json" -Raw | ConvertFrom-Json
# 替换restoreBackupContext下的backupRunId字段值
$targetJson.restoreBackupContext.backupRunId = $targetBackupRunId

# 将修改后的对象转换回JSON格式并覆盖保存到target.json
$targetJson | ConvertTo-Json -Depth 10 | Set-Content -Path ".\target.json"

关键步骤说明

  • JSON解析与对象操作:用Get-Content -Raw读取完整JSON文本,通过ConvertFrom-Json转换成PowerShell对象,直接通过属性访问操作字段,比文本替换更精准,避免JSON格式破坏。
  • 目标ID提取:通过$sourceJson.items[0].id直接获取source文件中首个备份运行的ID,数组索引从0开始对应首个元素。
  • JSON回写:修改完成后用ConvertTo-Json -Depth 10转换回JSON(指定-Depth是为了避免嵌套层级过深导致的数据截断),最后用Set-Content覆盖原文件。

注意事项

  • 如果文件不在当前工作目录,需将路径替换为完整路径(例如C:\backup\source.json)。
  • 若JSON嵌套层数超过10,需调整-Depth参数的值匹配实际层级,防止转换时丢失嵌套数据。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.04 08:01:02