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

Posted

技术标签:

【中文标题】在 Azure Devops 中使用从一个 PowerShell 任务到另一个任务的变量值【英文标题】:use variable value from one PowerShell task to another in Azure Devops 【发布时间】:2020-12-01 15:48:45 【问题描述】:

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

这是我的第一个脚本 -

$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 任务 - 返回

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

【问题讨论】:

嗨@megha。您能否检查答案是否可以解决此问题?如果您有任何问题,请随时告诉我。只是提醒this。 【参考方案1】:

由于它们是两个独立的任务,你需要设置一个变量来保存第一个脚本结果,然后你可以使用第二个任务中的值。

这是在 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>


【讨论】:

嗨@Kevin,这对我有用。非常感谢:-) T【参考方案2】:

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

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> 

如果不是上述情况,您需要发布更多实际脚本

HTH

【讨论】:

以上是关于在 Azure Devops 中使用从一个 PowerShell 任务到另一个任务的变量值的主要内容,如果未能解决你的问题,请参考以下文章

Azure Devops 使用 Powershell 从特定组织中删除特定用户

从 azure devops 管道更新变量组

如何从 Azure DevOps Pipeline 读取 Azure 文件共享文件

无法使用服务主体从发布管道访问 Azure Devops Git 存储库

如何从 Azure DevOps DACPAC 部署中获取漂移报告?

如何从 Azure Devops 服务器迁移到 Azure Devops 服务中的现有组织