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

Azure Pipeline向PowerShell脚本传递JSON变量失败求助

解决Azure Pipeline传递JSON到PowerShell脚本的参数错误

问题现象

在Azure Pipeline中尝试将变量文件中的JSON对象传递给PowerShell脚本时,触发错误:找不到接受参数‘accounts: [ { userID: 111111111 } ] }’的位置参数。已确认JSON格式合法,但替换为普通字符串变量时脚本运行正常。

错误原因

JSON字符串包含双引号,当通过"$(usersJson)"形式传递参数时,PowerShell/CMD会将JSON内部的双引号解析为参数分隔符,导致原本的单个字符串参数被拆分成多个位置参数,脚本无法识别这些零散的参数。

解决方案

方案1:用单引号包裹变量传递

修改Azure Pipeline任务的arguments配置,使用单引号包裹JSON变量。PowerShell中,单引号不会解析内部的双引号,能保证整个JSON作为完整字符串传递:

- task: AzureCLI@2
  inputs:
    azureSubscription: ${{ parameters.sub }}
    scriptType: ps
    scriptLocation: scriptPath
    scriptPath: resources/TestScript.ps1
    arguments: >
      -usersJson '$(usersJson)'
    failOnStderr: true

方案2:转义变量中的双引号

在变量文件testingJson.yml中,对JSON内部的双引号进行转义(添加反斜杠\),确保传递时不会被拆分:

variables:
  usersJson: '{
                \"accounts\": [
                  {
                    \"userID\": \"111111111\",
                    \"UPN\": \"test@gmail.com\"
                  }
                ]
              }'

方案3:改用内联脚本调用

将AzureCLI任务改为内联脚本形式,直接通过PowerShell的调用语法传递参数,避免参数解析问题:

- task: AzureCLI@2
  inputs:
    azureSubscription: ${{ parameters.sub }}
    scriptType: ps
    scriptLocation: inlineScript
    inlineScript: |
      & "$(System.DefaultWorkingDirectory)/resources/TestScript.ps1" -usersJson '$(usersJson)'
    failOnStderr: true

验证

修改后重新运行Pipeline,PowerShell脚本将能正确接收完整的JSON字符串参数,不再触发位置参数错误。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.21 07:24:18