PrePostDeploymentScript.ps1中ConvertFrom-Json执行失败求助
我使用Azure DevOps的AzurePowerShell@5任务执行ADF部署后启动触发器的操作,脚本如下:
- task: AzurePowerShell@5 displayName: 'ADF Post-Deployment Script' inputs: azureSubscription: 'SC-Azure-Dev-Subscription' ## 该输入不支持变量,必须硬编码 ScriptType: 'FilePath' ScriptPath: '$(Pipeline.Workspace)/ArmTemplates/PrePostDeploymentScript.ps1' ScriptArguments: '-armTemplate "$(Pipeline.Workspace)/ArmTemplates/ARMTemplateForFactory.json" -ResourceGroupName $(resourceGroupName) -DataFactoryName $(dataFactoryName) -predeployment $false -deleteDeployment $true' azurePowerShellVersion: LatestVersion pwsh: true
执行时在脚本第680行| ConvertFrom-Json -Depth 10处报错:
##[error] Conversion from JSON failed with error: Bad JSON escape sequence: \s. Path 'properties.pipelines[0].parameters.pVMSQLUserName', line 31, position 36. from Line: 680
##[error]Conversion from JSON failed with error: Bad JSON escape sequence: \s. Path 'properties.pipelines[0].parameters.pVMSQLUserName', line 31, position 36.
##[error]PowerShell exited with code '1'.
已尝试使用PowerShell Core,问题依旧。
问题原因
JSON规范仅允许特定转义序列(如\"、\\、\/、\b、\f、\n、\r、\t),\s不属于合法的JSON转义字符,因此ConvertFrom-Json无法解析该JSON内容。错误指向pVMSQLUserName参数值中存在无效的\s转义。
解决步骤
手动修复JSON文件
打开ARMTemplateForFactory.json,定位到properties.pipelines[0].parameters.pVMSQLUserName的字符串值:- 若
\s是误输入(实际应为空格):将所有\s替换为普通空格。 - 若需要保留
\s作为值的一部分:将\s替换为\\s(JSON中\必须转义为\\)。
- 若
自动化预处理JSON(可选)
如果模板是自动生成的,可在部署脚本前添加预处理逻辑,自动修复无效转义:$jsonPath = "$(Pipeline.Workspace)/ArmTemplates/ARMTemplateForFactory.json" $jsonContent = Get-Content -Path $jsonPath -Raw # 根据需求选择替换规则,示例:将\s替换为空格 $fixedContent = $jsonContent -replace '\\s', ' ' Set-Content -Path $jsonPath -Value $fixedContent -Force也可以把这段逻辑集成到
PrePostDeploymentScript.ps1中,放在读取ARM模板后、ConvertFrom-Json执行前。检查模板生成/导出流程
如果ARM模板来自ADF导出,检查导出过程是否存在参数转义错误,确保生成的JSON符合标准规范。
内容的提问来源于stack exchange,提问作者Akash Nigam

