Search code examples
azureazure-pipelinesazure-powershell

how to reference a environment variable from azure pipeline to a powershell script


I have a pipeline variable called envUpper and assigned the value DEV.

enter image description here

how would i call this in a powershell script. would it be $envUpper = $env:envUpper or $envUpper =$env:ENVUPPER or $envUpper = "$(envUpper)"

What is the correct way of doing this?


Solution

  • If you set 'envUpper' to be a general pipeline variable not secret variable, by default, it will be automatically mapped as an environment variable (ENVUPPER) on the agent.

    enter image description here

    • In 'Inline' type PowerShell script, you can call the variable directly by any of the following ways.

      Write-Host "env:ENVUPPER = ${env:ENVUPPER}"
      Write-Host "env:ENVUPPER = $env:ENVUPPER"
      Write-Host "envUpper = $(envUpper)"
      

      enter image description here

    • In 'File Path' type PowerShell script, you should call the environment variable.

      Write-Host "env:ENVUPPER = ${env:ENVUPPER}"
      Write-Host "env:ENVUPPER = $env:ENVUPPER"
      

      If you directly call the variable use the expression '$(varName)' in 'File Path' type script, it will be failed.

      enter image description here


    If you set 'envUpper' to be a secret variable, by default, it will not be automatically mapped as an environment variable on the agent. If you want to call its environment variable, you need to explicitly map this secret variable as an environment variable. See "Set secret variables".

    enter image description here

    • In 'Inline' type PowerShell script, you can call the secret variable directly use the expression '$(varName)'. To call its environment variable, need to explicitly map it.

      Write-Host "env:ENVUPPER = ${env:ENVUPPER}"
      Write-Host "env:ENVUPPER = $env:ENVUPPER"
      Write-Host "envUpper = $(envUpper)"
      

      enter image description here

    • In 'File Path' type PowerShell script, you should explicitly map the secret variable as environment variable, and then call the environment variable.

      Write-Host "env:ENVUPPER = ${env:ENVUPPER}"
      Write-Host "env:ENVUPPER = $env:ENVUPPER"
      

      Same as above statement, if you directly call the variable use the expression '$(varName)' in 'File Path' type script, it will be failed.

      enter image description here