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";
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With