7

I have n number of variables that I need to assign as Azure DevOps variables in a Release pipeline, and it doesn't seem like I'm getting the syntax right.

The variables may have different values (variable names) such that they could be: - {guid 1} - {guid 2} ...

So I won't know them prior to runtime. The problem is that it seems all of the examples of vso[task.setvariable] use static variable names, but I need to set it dynamically.

Here's what should work but doesn't:

 Write-Host "##vso[task.setvariable variable=$($myVariable)]$($myValue)"

I've also tried just using [Environment]::SetEnvironmentVariable (with user) and it doesn't seem to persist across two different tasks in the same job.

[Environment]::SetEnvironmentVariable($myVariable, $myValue, 'User')

(Is null in subsequent task)

Is there some way that I can dynamically create release variables that persist between tasks? I've tried to search and found one question on the developer community but no answer to it.

2 Answers 2

6

It actually looks like the issue isn't that the variable isn't set, but that after using task.setvariable, the variable will only be available in subsequent tasks (and not the current one).

So I would say this is the best way to set variables in Azure DevOps:

When needing to use variables in the same task/script step, use:

[Environment]::SetEnvironmentVariable(...)

Or just use a variable in PowerShell.

When needing to use variables with multiple steps, use:

$myVariable = "some name"
$myValue = "some value"

# Note that passing in $($variableName) should work with this call
Write-Host "##vso[task.setvariable variable=$($myVariable)]$($myValue)"

# Note that trying to use a Write-Host for $env:myVariable will return empty except in tasks after this one
Write-Host "Setting $($myVariable) to $($myValue)
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks a lot, the tip "the variable will only be available in subsequent tasks (and not the current one)" was the key to my problem. I was using a unique cmd task to run the commands and the variable always returned an empty value, now with two tasks (one to create de variable and other to print the value) the problem is solved. :)
2

It works. This is example from my build task:

    $myVariableNewValue = '##vso[task.setvariable variable=myVariable]' + $newValue
    Write-Host $myVariableNewValue

1 Comment

Thanks, this was close! It looks like part of the issue was that I was trying to use GetEnvironmentVariable in the same script which turned up empty (I'll link to something that shows this too), but still can be consumed in a subsequent task.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.