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

使用PowerShell替换JSON文件字符串失败,请求技术协助

问题解决:替换JSON中的$APIConnectionName字符串

原JSON文件(InitialApiConnectionTemplateFile.json)

{
    "$schema": "https://schema.management.azure.com/schemas/2019-04-01/deploymentTemplate.json#",
    "contentVersion": "1.0.0.0",
    "parameters": {
        "connections_$APIConnectionName_name": {
            "defaultValue": "$APIConnectionName",
            "type": "String"
        }
    },
    "variables": {},
    "resources": []
}

无效的PowerShell脚本

$JsonData = Get-Content $(System.DefaultWorkingDirectory)\InitialApiConnectionTemplateFile.json | ConvertFrom-Json

$JsonData -replace '$APIConnectionName', 'TestValue'

$JsonDataNew = $JsonData | ConvertTo-Json -depth 100

Write-Host "$JsonDataNew "

问题原因

  1. ConvertFrom-Json会将JSON转换成PowerShell自定义对象,直接对对象使用-replace只会修改对象的字符串表示,不会改变对象内部的属性值,原对象根本没被修改。
  2. 字符串$APIConnectionName中的$是正则表达式的特殊字符(表示行尾匹配),直接用-replace无法正确匹配目标内容。

解决方案

方案一:直接操作JSON字符串(全局替换)

不需要解析成对象,直接对文件内容做字符串替换,适合不需要精准控制替换位置的场景:

# 读取文件为单字符串(-Raw参数避免换行拆分)
$JsonString = Get-Content $(System.DefaultWorkingDirectory)\InitialApiConnectionTemplateFile.json -Raw

# 使用[regex]::Escape处理特殊字符$,确保准确匹配
$JsonStringReplaced = $JsonString -replace [regex]::Escape('$APIConnectionName'), 'TestValue'

# 输出结果
Write-Host $JsonStringReplaced

# 若需保存到新文件,执行:
# $JsonStringReplaced | Out-File "UpdatedApiConnectionTemplate.json" -Encoding utf8

方案二:操作JSON对象(精准修改)

解析成对象后针对性修改参数键名和默认值,避免误替换其他内容,适合需要精确控制修改位置的场景:

# 读取并解析JSON为对象
$JsonData = Get-Content $(System.DefaultWorkingDirectory)\InitialApiConnectionTemplateFile.json | ConvertFrom-Json

# 定位并修改参数的键名
$oldParamKey = $JsonData.parameters.PSObject.Properties.Name | Where-Object { $_ -contains '$APIConnectionName' }
$paramValue = $JsonData.parameters.$oldParamKey
$JsonData.parameters.PSObject.Properties.Remove($oldParamKey)
$newParamKey = $oldParamKey -replace [regex]::Escape('$APIConnectionName'), 'TestValue'
$JsonData.parameters | Add-Member -MemberType NoteProperty -Name $newParamKey -Value $paramValue

# 修改参数的defaultValue属性
$JsonData.parameters.$newParamKey.defaultValue = 'TestValue'

# 转换回JSON并输出
$JsonDataNew = $JsonData | ConvertTo-Json -Depth 100
Write-Host $JsonDataNew

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.27 16:42:41