在 Azure Devops 中使用从一个 PowerShell 任务到另一个任务的变量值

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

我正在编写脚本,我想从第一个脚本和 运行 第二个脚本中获取相应的结果。

这是我的第一个脚本 -

$result = <command 1>

if($result)

{

< run command 2>


return $true

}

else 
{

return 
$false

}

这是第二个脚本

if($return -eq $true)

{

<run Command 3>

}

else{

<run command 4>
 
}

我在 Azure Devops 中有 2 个单独的任务来执行这 2 个脚本。

我在管道和输出变量中使用 Azure PowerShell 任务 - return

Que - 第一个脚本运行良好。它的 returning true 或 false 值但第二个脚本不起作用。它只是执行 else 条件,第一个脚本中的 return 值是真还是假。 我如何根据第一个脚本 returned 的真假结果使第二个脚本工作

如果这些是真正独立的脚本,您需要将 return 值保存到变量以保留第一个脚本的值,供第二个脚本处理。我很惊讶你没有收到错误:

PS> .\Test\Get-RetVal.ps1 -RetVal $True  #Equiv of Script 1
True

#Equiv of Script 2
PS> If ($RetVal) {
  "Previous Return Value = $RetVal`n" +
  "Execute Command 3"
}
Else {
  "Previous Return Value = $RetVal`n" +
  "Execute Command 4"

}

#Script 2 Output w/o saved Variable

The variable '$RetVal' cannot be retrieved because it has not been set.
At line:1 char:5
+ If ($RetVal) {
+     ~~~~~~~
    + CategoryInfo          : InvalidOperation: (RetVal:String) [], RuntimeExc 
   eption
    + FullyQualifiedErrorId : VariableIsUndefined
 
#Saving the Value
PS> $RetVal = .\Test\Get-RetVal.ps1 -RetVal $True

#Rerun Script 2 when saved value = True

#Script 2 Output:
Previous Return Value = True
Execute Command 3

#Rerun Script 1 to set $RetVal to False
PS> $RetVal = .\Test\Get-RetVal.ps1 -RetVal $False

#Rerun Script 2 when saved value = False

#Script 2 Output:
Previous Return Value = False
Execute Command 4

PS> 

如果上述情况并非如此,您需要 post 更多实际脚本

HTH

因为是两个独立的task,所以你需要设置一个变量来保存第一个脚本的结果,然后你才能在第二个task中使用这个值。

这是在 Azure Devops 中设置变量的脚本:

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

您可以将此脚本添加到 If statement

这是一个例子:

Azure PowerShell 任务 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 

}

在此脚本中,它将根据条件创建管道变量。然后在第二个powershell任务中,你可以使用$variablename来获取它。

Azure PowerShell 任务 2

例如:

if($testvar = $true)

{
   <run Command 3>
}

else{

<run command 4>

}