如何在DevOps流水线中将YML对象传递给PowerShell脚本?
解决DevOps流水线向PowerShell脚本传递对象的问题
问题回顾
尝试从Azure DevOps流水线向PowerShell脚本传递对象时遇到两个核心问题:
convertToJson生成的JSON包含换行符,触发脚本参数报错:Line breaks are not allowed- JSON格式不一致,第二个
amount值未加引号(源于流水线参数的类型差异)
方案1:用压缩版JSON避免换行(简单直接)
步骤1:修正流水线参数的数值类型
确保所有amount值为纯数字,去掉多余空格(空格会让值被识别为字符串):
parameters: - name : objectTest type : object default: - fruit: apple amount: 1 - fruit: pear amount: 1
步骤2:生成单行压缩JSON作为参数
在AzurePowerShell任务中,给convertToJson添加compress选项生成无换行的单行JSON,并用双引号包裹避免解析异常:
- task: AzurePowerShell@5 name: testObject inputs: pwsh: true ScriptPath: test.ps1 scriptArguments: > -object "${{ convertToJson(parameters.objectTest, 'compress') }}"
步骤3:PowerShell脚本接收并转换对象
如果需要将JSON字符串转回PowerShell对象,使用ConvertFrom-Json处理:
[CmdletBinding()] param( [string]$object ) # 将JSON字符串转换为PowerShell对象 $targetObj = $object | ConvertFrom-Json Write-Host $targetObj
方案2:通过文件传递对象(适合复杂结构)
若对象层级复杂,参数传递易出问题,建议将JSON写入文件后让脚本读取:
步骤1:流水线中写入JSON文件
添加PowerShell任务将对象转为压缩JSON并写入文件:
- task: PowerShell@2 name: WriteJsonFile inputs: pwsh: true script: | $jsonContent = '${{ convertToJson(parameters.objectTest, 'compress') }}' $jsonContent | Out-File -FilePath $(System.DefaultWorkingDirectory)/object.json -Encoding utf8
步骤2:传递文件路径给PowerShell脚本
修改AzurePowerShell任务的参数为文件路径:
- task: AzurePowerShell@5 name: testObject inputs: pwsh: true ScriptPath: test.ps1 scriptArguments: > -jsonFilePath "$(System.DefaultWorkingDirectory)/object.json"
步骤3:PowerShell脚本读取文件内容
[CmdletBinding()] param( [string]$jsonFilePath ) # 读取文件并转换为对象 $targetObj = Get-Content -Path $jsonFilePath -Raw | ConvertFrom-Json Write-Host $targetObj
额外说明:JSON格式不一致的原因
流水线参数中第一个amount: 1 (末尾带空格)被识别为字符串类型,第二个amount: 1是数值类型,导致convertToJson生成的JSON中一个带引号一个不带。去掉第一个amount后的空格即可统一类型。
内容的提问来源于stack exchange,提问作者Swifting
相关产品推荐
相关产品推荐

