且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何在Azure Devops管道中使用PowerShell根据条件触发代理作业

更新时间:2023-11-04 11:14:46

如果您希望使用 GUI 配置管道,则必须运行脚本以将 MyVariable 添加为通过调用此定义的变量将不会转移到下一个代理作业. agent job1agent job2彼此独立.

If you prefer to configure your pipeline with GUI, you must run script to add the MyVariable as Variables instead of a temporary variable by calling this api. Because after the agent job1 finished, the variable you just defined with $MyVariable = "Proceed" will not transfer to the next agent job. The agent job1 and agent job2 are independent with each other.

在座席工作1中:

配置2个Powershell任务.

Configure 2 powershell tasks.

(1)第一个用于定义带有值的变量并将其设置为输出变量:

(1) The first one is used to define a variable with value and set it as output variable:

echo "Hello-World"
echo "##vso[task.setvariable variable=MyVariable;isOutput=true]Proceed"
echo $MyVariable

不要忘记在此任务中指定其reference名称 MyVariableOutput .

Do not forget specify its reference name MyVariableOutput in this task.

(2)第二个作业用于将此output variable添加到Variables中,然后agent job2可以访问它:

(2) The second job is used to add this output variable into Variables, then the agent job2 could access it:

$connectionToken="{token}"
$urlget = "https://vsrm.dev.azure.com/{org}/{project}/_apis/release/releases/$(Release.ReleaseId)?api-version=5.1"
$base64AuthInfo = [System.Convert]::ToBase64String([System.Text.Encoding]::ASCII.GetBytes(":$($connectionToken)"))
$getdef = Invoke-RestMethod -Headers @{Authorization=("Basic {0}" -f $base64AuthInfo)} -Method GET -ContentType application/json -Uri $urlget 
##Write-Host Pipeline = $($getdef | ConvertTo-Json -Depth 100)
$MyVariable=@"
    {
      "value": "$(MyVariableOutput.MyVariable)"
    }
"@
$getdef.variables | add-member -Name "MyVariable" -value (Convertfrom-Json $MyVariable) -MemberType NoteProperty -Force -PassThru

$getdef = $getdef | ConvertTo-Json -Depth 100
$getdef | clip
$urlput = "https://vsrm.dev.azure.com/{org}/{project}/_apis/release/releases/$(Release.ReleaseId)?api-version=5.1"
$putdef = Invoke-RestMethod -Uri $urlput -Method PUT -Body $getdef -ContentType "application/json" -Headers @{Authorization=("Basic {0}" -f $base64AuthInfo)}

上面的脚本将创建一个变量MyVariable,其值是Proceed.

The above script will create a variable MyVariable which its value is Proceed.

agent job2中,配置条件,如下所示:

In agent job2, configure the condition as the shown below:

eq(variables['MyVariable'],'Proceed')

您可以看到代理job2可以成功运行,因为它已检测到MyVariable的值为Proceed.

You can see the agent job2 can be run successfully since it has detect the value of MyVariable is Proceed.