6
votes

I'm trying to set the build number format in Teamcity using Powershell (kinda like in this Octopus Deploy blog post).

However, I don't know if the way Teamcity handles the service messages has changed since then or if I'm doing this wrong because it's not working.

I have the following Powershell script as the first step in my build config:

$buildCounter = "%build.counter%" 
$buildConfig = "%system.buildconfig%"
$version = "%system.majorMinorVersion%"

$branch = "%vcsroot.branch%"

if ($branch.Contains("/")) 
{
    $branch = $branch.substring($branch.lastIndexOf("/")).trim("/")
}

$buildNumber = "${version}.${buildCounter}-${branch}"

Write-Host "##teamcity[buildNumber '$buildNumber']"

(I've also tried $branch = "%teamcity.build.branch%" on line 5)

So when I try this, the if statement doesn't run because although it seems like in the example given by Octopus Deploy that $branch is set to the actual value of %vcsroot.branch% it's not and the result that it writes out to Teamcity is literally ##teamcity[buildNumber '$buildNumber']. However, this does seem to work but the build number can't have / in it so my build fails because the branch is set to refs/head/master rather than just master.

Where am I going wrong?

2
I use PowerShell such as if ("%teamcity.build.branch%".StartsWith("...")) and you've also got the correct syntax for writing out the build number. If you Write-Host $branch after the if statement, what does it output?Evolve Software Ltd
This might be useful: we use a Node based CLI tool to do this, see: github.com/nice-digital/teamcity-build-number. We build Pull Requests so we use the GitHub API to look up branch names, but the same principle applies. It uses the TeamCity service messages under the hood. It might serve as a useful reference for anyone reading this question.Ian Routledge

2 Answers

7
votes

It seems the last line of the script should be:

Write-Host "##teamcity[buildNumber '${buildNumber}']"

A note: for the script to work, if should be specified as inline script in TeamCity build step (which makes TeamCity %-references to work).

BTW, you can make TeamCity display short branch name by using +:refs/heads/* branch specification in the VCS root

2
votes

If you're using powershell the build number is available to your agents as an environmental variable, in powershell as:

$env:BUILD_NUMBER

This is number that you can configure thru the build configurations UI.