Use PowerShell to Add Some Logic to Your Build Numbers in TeamCity
TeamCity has a bunch of parameters that you can use to change-up your build number if you want to.
Want to add the build count?
How about adding the branch name as well?
How about truncating the branch name at 20 characters to support Semantic Versioning and excluding the branch name completely if it’s master?
Well, that requires a little more work.
Build Number Config
We’ll use a custom script to build out the pre-release info for our builds but we need to set up a base number first. Following SemVer, this should be of the format MAJOR.MINOR.PATCH. We’ll use the TeamCity build counter for our patch number so that increases with every build. The rest will be manually set.
We can set this up under the General Settings tab of our build config. Parameters in TeamCity are referenced by wrapping them in % marks.
We now need a script to add the rest of the info.
The PowerShell Build Runner
TeamCity includes PowerShell as part of its collection of build runners. We can use this to build out our build number to match the rules above.
First, we go to our build config and add a new step.
Next, we select PowerShell as the step type.
We can now fill in some details about what our build step is going to do.
Now we’ve got that in place, we can create the PowerShell script for updating the build number.
The Script
Here’s what our final script will look like:
There’s not a huge amount to it, but let’s go through it bit by bit.
We start off by creating a local variable to store the default build number (the one we specified above) from TeamCity, along with the name of the current branch.
If our branch is the master branch, we don’t want to include any suffix, so we can just return 0 to exit and keep the version number as the default.
The pre-release suffix for a version number has a maximum of 20 characters, so we check for the length of the branch name and truncate it if necessary.
Then, finally, we export our new version number back to TeamCity using Write-Host.
Now, when we run our build, we’ll get a suffix matching our branch names.