Search code examples
powershellazure-devopsazure-powershell

use variable value from one PowerShell task to another in Azure Devops


I am working on script where I want to take result from first script and run second script accordingly.

This is my first script -

$result = <command 1>
    
if ($result)
{    
    #< run command 2>   
    return $true    
}
else {    
    return  $false    
}

Here is second script

if ($return -eq $true)
{
    #<run Command 3>
}
else {
    #<run command 4>
}

I have 2 separate tasks in Azure Devops for performing these 2 scripts .

I am using Azure PowerShell task in my pipeline and output variable - return

Que - first script works good. Its returning true or false value but second script is not working. its just preforming else conditions whether return value from first script true or false. How can I make second script work according to true false result returned from first script


Solution

  • Since they are two independent tasks, you need to set a variable to save the first script result, then you could use the value in the second task.

    Here is the script to set the variable in Azure Devops:

    echo "##vso[task.setvariable variable=variablename;]value"

    You could add this script to the If statement

    Here is an example:

    Azure PowerShell Task 1

    $result = command 1
    
    if($result)
    
    {
    
     echo "##vso[task.setvariable variable=testvar;]$true"    
       return $true
        
    }
    
    else {
    
        echo "##vso[task.setvariable variable=testvar;]$false"    
        return $false 
    
    }
    

    In this script, it will create a pipeline variable based on conditions. Then in the second powershell task, you could use $variablename to get it.

    Azure PowerShell Task 2

    For example:

    if($testvar -eq $true)
    
    {
       <run Command 3>
    }
    
    else{
    
    <run command 4>
    
    }