PowerShell 5.1
Library variable name in Group: test.DEV
Azure DevOps Parameter value: config
I want to build the variable name test.DEV
and then get the value for it that is stored in Library variables of Azure DevOps. For the output, I’m getting the variable name instead of the variable value. Is this even possible?
steps:
- powershell: |
$myVar = "test.${{ parameters.config }}"
'$($myVar)'
Output:
test.DEV
Expected the value for test.DEV
instead of variable name
2
Answers
Yes, it is possible to name a variable, or set a string variable’s value, to the name of a variable itself. I did this on purpose recently as I wanted to create and maintain some dynamically named variables.
Using
-f
and string placement in that fashion seems to work:WPS 5.1:
I think it auto-converts to a string here because we’re using
-f
.For naming a variable programmatically (or with reserved characters like dots) you can use the
New-Variable
cmdlet:Here I had to convert it to a string manually, otherwise it sets the value to the specified object.
New-Variable
is very useful in this context, I think, because you can do all the string mangling you want for both the-name
and-value
switches without funny escaping. It’s a bit verbose, but it’s both readable and explicit, which I tend to prefer.From your description, you need to use nested variable in Azure Pipeline.
Example:
$($myVar)
I am afraid that there is no built-in method in Azure pipeline can achieve this.
To meet your requirement, you can use the Variable Set task from extension: Variable Toolbox.
Here is an example:
Variable Group:
Pipeline YAML:
Result: