Get Azure pipeline variable value dynamically

Viewed 282

I have defined a variable for my pipeline that looks like this

My Username-key

with some value that is not important. My Username here is the name for my account, and is equal to the result of $(build.QueuedBy).

I want to reference it inside my task that looks like this:

- task: PowerShell@2 #CmdLine@2 
  inputs:
    targetType: inline
    script: |
      $key= "$(build.QueuedBy)".replace(" ","") + '-KEY'
      echo $key | Invoke-Expression

What I get is an error that looks like this:

Invoke-Expression : The term 'MyUsername-KEY' is not recognized as the name of a cmdlet, function, script
...

How can I dynamically get the value of the variable in the example above in the same way that I could get it if I directly executed

echo $(MyUsername-KEY)
1 Answers

The variable expressions in form of $(MyUsername-KEY) are evaluated before the script is executed. So there's no way to use them in that form dynamically. But you can take advantage of the fact that pipeline variable are also exposed as env variables. You can get the value of environment variable dynamically like this:

(get-item "env:$key").value

If you need to debug it, you can get a list of all env variables:

ls env:
Related