简体   繁体   中英

how to set variable and pass between different task in classic devop (not yaml)?

In my devop's powershell task in classic pipeline (not yaml), I am trying to set value to a variable and pass to different task later. However, even in the same task, seems I am not setting it correct. When I output it, it is just empty. What am I doing wrong?

##vso[task.setvariable variable=NugetVersion]hello-alpha

Write-Host "start";
Write-Host $NugetVersion;
Write-Host $($NugetVersion);
Write-Host "finish";

Your set variable code is fine but needs to be wrapped by with Write-Host .

Write-Host "##vso[task.setvariable variable=NugetVersion]hello-alpha" )

And syntax while printing seems to be incorrect. Should be:

Write-Host $(NugetVersion)

Refer Runtime expression syntax

The syntax you used to set the variable is correct, provided you set it with:

Write-Host "##vso[task.setvariable variable=NugetVersion]hello-alpha"

(I mention this because your code snippet shows the task.setvariable , but it wasn't clear that you were writing this to the task output).

I want to focus on your statement that you can't access the variable you just set in the same task. This is where a lot of people get caught with task.setvariable .

The purpose of task.setvariable is to communicate variables to other tasks, jobs, and stages. The way that it works is that the pipeline runs your Powershell or Bash script, and you write the value you want to set in that script. The pipeline picks up the variable you asked to set by looking at the console output and parsing the variable name and value.

This has to happen after your task completes, because the pipeline has no way to pick up the change on the fly and inject it back into a running script as an environment variable.

So, having picked up that variable setting during the script run, it now has a value it can pass along to other tasks and jobs.

TL;DR - within the task you need to put the value that you put into task.setvariable into a script variable. For example,

$NVersion = "hello-alpha"
Write-Host "##vso[task.setvariable variable=NugetVersion]$NVersion"

will let you access the value and pass it to other tasks and jobs.

Edit: One last thing. Adding ;isOutput=true to your command is what makes the variable available to other jobs and stages. This is what the docs recommend you do, it's also been my experience. If you look at the LoggingCommandFunctions.ps1 library for the Azure Pipelines task library project, it says

截屏

Which is not terribly helpful, because they both go to the host, so I've had to take that with a grain of salt.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM