Home > Software design >  Using Get-Variable to retrieve variables from library in Azure Pipelines
Using Get-Variable to retrieve variables from library in Azure Pipelines

Time:09-28

I have a HelloWorld variable library in Azure DevOps containing the variable $foo=bar.

I want to read it in my pipeline using Get-Variable but regardless of the scope I give to my search, the variable is nowhere to be found. It is however, accessible "directly" (as shown below):

variables:
  - group: HelloWorld

stages:
  - stage: test
    jobs:
    - job:
      displayName: Retrieve variables
      steps:
        - task: Powershell@2
          displayName: Variable retrieval
          inputs:
            targetType: inline
            verbose: true
            script: |
              # This works
              Write-Host "Direct access: $(foo)"
              # All of the following returns nothing
              $indirectAccess = Get-Variable -Name "foo" -ValueOnly -ErrorAction SilentlyContinue
              $indirectAccess = Get-Variable -Name "foo" -ValueOnly -ErrorAction SilentlyContinue -Scope Global
              $indirectAccess = Get-Variable -Name "foo" -ValueOnly -ErrorAction SilentlyContinue -Scope Script
              Write-Host "Indirect access: $indirectAccess"

Can I in any way retrieve library variables with Get-Variable?

The reason it's so important for me to know whether it's possible is because I need to retrieve values with variables which name is a variable itself... And so far I haven't found a way to do it except than with Get-Variable.

CodePudding user response:

  • $(foo) is Azure's macro expansion syntax, meaning that the value of the variable is injected into the script, so the script doesn't know the name of the variable whose value was used.

  • From what I understand, Azure also defines variables as environment variables, with the original name transformed to all-uppercase, with . replaced with _, if applicable. Thus, try accessing the variable as:

    • $env:FOO (direct access)
    • $name = 'FOO'; Get-Content env:$name (indirect access)

Note that Get-Variable only works for regular (PowerShell-only) variables, not for environment variables; the latter must be accessed via the env: drive, as shown above.

  • Related