Azure DevOps 在构建任务中设置构建号变量

Azure DevOps Set Build number variable in a Build Task

在 Azure DevOps 中,我创建了一个 Build。在那个构建中,我创建了一个 ProjectBuildNumber 管道变量,它在排队时是可设置的。然后在 Options -> Build number format 下使用该变量来设置我在 Azure 中显示的内部版本号。

但是,我正试图在我 building/deploying 的代码中设置 ProjectBuildNumber 变量。有没有一种方法可以让我的构建中有一个任务来更新该 ProjectBuildNumber 并更新 Azure DevOps 中的构建号?

查看有关此的 Microsoft 文档:Variables

根据您的操作系统,您可以添加 Powershell/Batch/Bash 任务并更改变量。

编辑:经过一些研究,变量的变化似乎会出现在后续任务中。看看这个问题Update environment variables using task.setvariable in a bash script does not work

Is there a way I can have a Task in my Build to update that ProjectBuildNumber and update the Build number in Azure DevOps?

答案是

您可以在构建定义中添加一个 Inline Power-Shell 任务来更新 ProjectBuildNumber 的值,然后更新基于它的构建号:

Write-Host "##vso[task.setvariable variable=ProjectBuildNumber;]YourUpdateValue"

Write-Host "##vso[build.updatebuildnumber]xxx.$(ProjectBuildNumber).xxx.xxx"

在构建过程中检查 Logging Command 以获取更多详细信息:

此外,如果你想在UI/web门户上更新管道变量的值,你需要REST API (Definitions - Update) 从构建任务更新构建管道定义变量的值。

有个跟帖很相似,具体可以查看答案:

注意:将 API 更改为构建定义:

PUT https://dev.azure.com/{organization}/{project}/_apis/build/definitions/{definitionId}?api-version=5.0

希望这对您有所帮助。

我们可以通过两种方式更新 Azure Devops 中的内部版本号。 一个来自选项 Section/Tab,第二个来自 PowerShell 脚本。

要从 Power shell 脚本更新版本号..我们需要添加以下脚本..

写入主机“##vso[build.updatebuildnumber]$(VersionNumber).$(VersionRevision)”

这里我们使用了 2 个变量:VersionNumber 和 VersionRevision。 我们需要在 PipeLine Configurations 中添加 2 个变量。 VersionNumber 将是所需的数字,而 VersionRevision 是每次我们创建新构建时都会更新的计数器编号。 请查看 You tube 视频的完整演示

https://youtu.be/WBmFTmzopiQ

为此创建了强大的 shell 任务

# replace existing Build.BuildNumber with
# NAME_2.1.2.54_20211220.16_345
- task: PowerShell@2
  displayName: 'Update Version Number'
  inputs:
    targetType: 'inline'
    script: | 
      $lines = Get-ChildItem ".\Project\My Project\AssemblyInfo.vb" 
      $match = $lines | Select-String -Pattern "\<Assembly\:\s+AssemblyVersion\(""(\d+\.\d+\.\d+\.\d+)""\)\>"
      $version = $match.Matches[0].Groups[1].Value
      [Version]::Parse($version) # validate
      $tag = "NAME_$($version)_$(Build.BuildNumber)_$(Build.BuildId)"
      Write-Host "##vso[build.updatebuildnumber]$tag"