3
votes

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

2 Answers

2
votes

It works. This is example from my build task:

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

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)