且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何在Azure DevOps管道中将Json变量传递给命令行任务?

更新时间:2022-04-04 23:57:15

我无法获得resultJson的值.

I am not able to get the value of resultJson.

1.如果 resultJson

1.If the resultJson is the pipeline variable, you should use InputJSON: $(resultJSON) instead of InputJSON: $($resultJSON).

假设管道变量 resultJSON 的值为100,那么管道中的所有任务都可以获取其值100.您可以在 Task 范围内使用 $ env:RESULTJSON = $ json ,那么此变量的值就是该PS任务中 $ json 的值.

Assuming the value of pipeline variable resultJSON is 100, then all the tasks within the pipeline can get its value 100. You can modify its value in Task scope using $env:RESULTJSON=$json, then the value of this variable would be the value of $json in that PS task.

但是请注意:其他任务将获得100,而不是 $ json 的值.(区分管道范围和任务范围之间的区别)

But note: Other tasks would get 100 instead of value of $json. (Distinguish the difference between Pipeline Scope and Task Scope)

2.如果 resultJson 是PS任务中定义的变量,则其他任务无法访问其值,因为该变量仅在当前会话中有效.(您可以添加第二个PS任务进行测试)

2.If the resultJson is a variable defined in PS task, then other tasks can't access its value cause the variable is only valid in current session. (You can add second PS task to test it)

要在多个任务/步骤中定义变量,可以使用在脚本中设置变量.

To define a variable across multiple tasks/steps, you can use logging command in PS task, check Set variables in scripts .

logging命令不直接支持Json格式变量.因此,在定义变量之前,我们需要将其转换为一行:

The logging command doesn't support Json format variable directly. So we need to convert it into one line before defining the variable:

$json=$json| ConvertTo-Json -Compress
Write-host "##vso[task.setvariable variable=testJSON]$json"

更新2

另一个方向是通过文件传递json数据.例如,第一个PS任务使用 $ JSON |输出文件Test.json ,以将内容输出到Test.json文件中.下一个PS任务使用 $ Input = Get-Content Test.json Write-Host $ Input 来显示值.另外,第二个任务可以是cmd任务,它们的(PS任务,CMD任务)默认工作目录相同.

Update 2

Another direction is to pass the json data via a file. For example first PS task uses $JSON | Out-File Test.json to output the content into Test.json file. And the next PS task uses $Input = Get-Content Test.json and Write-Host $Input to display the value. Also, the second task could be cmd task, their(PS task, CMD task) default working directories are the same one.