I ran into a bump when trying to pass variables around between PowerShell files in two tasks in the same job. I found the PowerShell task acts differently when using inline vs file path type.
Inline vs File Path
Set variables in scripts - Azure Pipelines | Microsoft Learn shows how to pass variables around between inline tasks in the same job.
Write-Host "##vso[task.setvariable variable=myVar;]foo"
Subsequent inline tasks in the same job can use it:
Write-Host "myVar is $(myVar)"
File Path Type
Referencing variables in File Path Type PowerShell Tasks changes slightly. If you try to access the variable
$(myVar) like the inline example you get an error:
myVar : The term 'myVar' is not recognized as the name of a cmdlet, function, script file, or operable program.
There are two ways to accomplish this with the File Path Type.
Use the environment ($env):
Use an output variable and pass it as a parameter into the next script task. This also works for tasks not in the same job.
The syntax to set the variable in the Set it step’s script file changes to:
Write-Host "##vso[task.setvariable variable=myVar;isoutput=true]foo"
In the task, set the Reference name in the task to a name of your choosing. I used setOutput.
The consuming task, uses an argument in the consuming PowerShell file and uses the Reference Name from the previous task. If you called the argument in the PowerShell file
$myVarArg then you pass it in
The PowerShell file needs to accept that parameter:
Write-Host "myVar: $myVarArg"
See Classic release and artifacts variables - Azure Pipelines | Microsoft Learn for more information.
The advantage of the second option is that it also works between jobs. If you are using the variables in the same job, consider using the environment variable.