How to use a variable in one task which is defined in another task in a DevOps pipeline?
This is the yaml script I am using:
-task: PowerShell@2
displayName: 'SetVal'
inputs:
targetType: filePath
filePath: '$(System.DefaultWorkingDirectory)/setval.ps1'
pwsh: true
-task: PowerShell@2
displayName: 'UseVal'
inputs:
targetType: filePath
filePath: '$(System.DefaultWorkingDirectory)/UseVal.ps1'
arguments: -DEFAULT_WORKING_DIRECTORY $(System.DefaultWorkingDirectory) -setvalue $env:setvalue #setvalue is the variable defined from previous task
In the PowerShell script of the first task I have defined the variable to be used in the second task as:
Write-Output "##vso[task.setvariable variable=setvalue;isOutput=true]$setvalue"
What change I need to make to use the value in the next task?
2
Answers
check the devops documentation
you can use it by directly calling $(setvalue) in the next task, please check if the $setvalue variable is not $null or empty string
When you use an output variable in the same job, you don’t have to use the
isoutput
property. By default, the variable will be available to downstream steps within the same job. You can useWrite-Host "##vso[task.setvariable variable=setvalue]$setvalue"
in your setval.ps1.However, if you do add the
isoutput
property, you’ll need to reference the variable with the task name. Please note that the taskname
is the ID of the step and thedisplayName
is human-readable name for the task. They are different. In the following example, the second task consumes the variablesetvalue
in the first task "SetVal2" via $(SetVal2.setvalue).In your situation, to consume variables defined in other powershell file, we can’t use macro syntax
$(var)
directly. When using ‘filePath’ type script, normally the task would just copy the script file into the working directory of the agent. And then directly execute the script file. It will not pre-parse the macro syntax$(Var)
in the script file. However, we can pass the value of them via an environment variable in the second task. Refer to the following sample:The setval.ps1:
The UseVal.ps1:
The yaml file: