TFS CI 构建 - 构建成功后更新自定义定义变量

TFS CI Build - Update custom define variable after build is succeed

我们已经设置了我的 TFS CI 构建,我们正在管理一个变量以维护版本控制, 我们想在每次成功构建后进行更新,知道怎么做吗?

我写过PowerShell脚本

param([Int32]$currentPatchVersion)
Write-Host "Current patch version "$currentPatchVersion
$NewVersion=$currentPatchVersion + 1
Write-Host "New patch version "$NewVersion
Write-Host ("##vso[task.setvariable variable=PackageVersion.Patch;]$NewVersion")

但它只是即时应用。

我想在设置中永久应用它。

"##vso[task.setvariable variable=PackageVersion.Patch;]$NewVersion" 只是在构建过程中设置变量值,它不会在构建定义级别设置值。如果要永久更新构建定义中的变量值,可以调用 Rest API 设置定义中变量的值。有关详细信息,请参阅以下部分:

创建一个"testvariable"作为示例:

使用以下代码创建 Power Shell 脚本并将其上传到源代码管理中:

[String]$buildID = "$env:BUILD_BUILDID"
[String]$project = "$env:SYSTEM_TEAMPROJECT"
[String]$projecturi = "$env:SYSTEM_TEAMFOUNDATIONCOLLECTIONURI"

$username="alternativeusername"
$password="alternativepassword"

$basicAuth= ("{0}:{1}"-f $username,$password)
$basicAuth=[System.Text.Encoding]::UTF8.GetBytes($basicAuth)
$basicAuth=[System.Convert]::ToBase64String($basicAuth)
$headers= @{Authorization=("Basic {0}"-f $basicAuth)}

$buildurl= $projecturi + $project + "/_apis/build/builds/" + $buildID + "?api-version=2.0"

$getbuild = Invoke-RestMethod -Uri $buildurl -headers $headers -Method Get |select definition

$definitionid = $getbuild.definition.id

$defurl = $projecturi + $project + "/_apis/build/definitions/" + $definitionid + "?api-version=2.0"

$definition = Invoke-RestMethod -Uri $defurl -headers $headers -Method Get

$definition.variables.testvariable.value = "1.0.0.1"

$json = @($definition) | ConvertTo-Json  -Depth 999

$updatedef = Invoke-RestMethod  -Uri $defurl -headers $headers -Method Put -Body $json -ContentType "application/json; charset=utf-8"

此脚本将获取当前构建定义并将 "testvariable" 的值更新为 "1.0.0.1"。您需要启用备用凭据。

然后您可以在构建定义中向 运行 此脚本添加一个 "PowerShell Script" 任务。