skip to Main Content

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


  1. 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:

    PS C:pwsh> $testVar = "test.{0}" -f $psversiontable.CLRVersion
    PS C:pwsh> $testVar
    test.4.0.30319.42000
    

    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:

    PS C:pwsh> New-Variable -name "testVar3.stuff" -value $psversiontable.CLRVersion.toString()
    PS C:pwsh> ${testVar3.stuff}
    test.4.0.30319.42000
    

    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.

    Login or Signup to reply.
  2. 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:

    enter image description here

    Pipeline YAML:

    parameters:
      - name: config
        type: string
        
    pool:
      vmImage: ubuntu-latest
    variables:
      - group: test
    steps:
    - task: VariableSetTask@3
      inputs:
        variableName: 'myVar'
        value: '$(test.${{ parameters.config }})'
    - powershell: |
       
        echo $(myVar)
    

    Result:

    enter image description here

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search