Home > Net >  Pass variable value from one Powershell script in Powershell task to another script in the next Powe
Pass variable value from one Powershell script in Powershell task to another script in the next Powe

Time:11-23

I am working on Azure DevOps Release pipeline. The first task in the release pipeline is a Powershell task. This task has a Powershell Script Inline. The below is the content of the task:

steps:
- powershell: |
$repo = '$(Release.TriggeringArtifact.Alias)'

switch ( $repo )
{
   _repo-health { $result = 'Health'    }

}

$result
$Repo_Name = $result

Write-Output "$Repo_Name"

displayName: 'PowerShell Script'

So, from the above task via Powershell script I am trying to fetch the Repository name using predefined variables and assign it to a variable.

The second task in the pipeline is a Powershell task with a Powershell script with the below content -

# Write your PowerShell commands here.

Write-Output "$Repo_Name"

So, when I am trying to print "$Repo_Name" in the same task it is printing, but if I am trying to print or fetch the variable value in the another task or stage in the same pipeline I am not able to print it. So need help here.

CodePudding user response:

You use special formatted output from your first powershell script. That will tell the build agent that you want to set a variable to a given value:

Write-Host "##vso[task.setvariable variable=Repo_Name;]$Repo_Name"

From then on, the variable "Repo_Name" will have the value of the powershell variable "$Repo_Name".

In following scripts/tasks you can then reference the variable:

Write-Host "I got the value of $(Repo_Name) for the Repo_Name variable."

More details here, especially review the isoutput=true modifier which you might need to add depending on the "scope" that your variable should have.

For example, if you need to read the variable in the next stage, you have to set it like this:

Write-Host "##vso[task.setvariable variable=Repo_Name;isoutput=true]$Repo_Name"
  • Related