Team City and Powershell

Say we need Team City to perform certain actions but we don't want to add another script to source control. In my case, I needed Team City to create a file if it didn't exist, and delete some others if they did. I couldn't use MSBuild for this because I needed this to be done before building any project. Though there are workarounds for that, they implied adding MSBuild scripts to source control.

To avoid further cluttering the repo, Powershell is a good choice here. Using Team City's jargon, we can add a Build Step with a Powershell Build Runner, and write the script directly in its configuration page. Said script will be stored by Team City, leaving our repo intact.

First of all, we need to have Powershell installed in our build server machine. It's usually bundled with Visual Studio and SQL Server installs, so most likely you already have it. Nevertheless, you can check if it so by opening a terminal and typing powershell. If it is installed, we'll enter the Powershell command prompt, which we can leave with the exit command.

A more subtle issue is that, by default, Windows (XP and 7 at least) forbid running Powershell scripts. To get around this, we must open a terminal and enter some commands. If Team City is configured to run under the SYSTEM account (which it does by default), said terminal must be opened under said account. In a previous post, we learned that can be done using PsTools. Once your terminal is open:

  1. powershell
  2. Set-ExecutionPolicy RemoteSigned
  3. exit

With the RemoteSigned setting, local scripts, like Team City's, can be ran directly, but those proceeding from other machines or the Internet will need a trusted certificate to run.

Let's move on to configuring Team City. For a Powershell Build Runner, Team City can run a script from an existing .ps1 file, or run code directly. The latter case is the one we want. In that scenario, we can run code with the -Command (send directly to Powershell stdin) or -File option (create temporary file). In my first attempt, I tried to use -Command, but it has issues with multiline statements

Once I solved that problem, this was the final setup:

About the script: asides from Powershell's syntax, which is simple and can be quickly learnt here, we must note the following: %IconSet% is a reference to Team City Build Parameter of the Configuration Parameter type. Basically, those can be defined for each project, and referenced throughout its configuration. When Team City parses the Powershell script and finds %IconSet%, it replaces it with whatever value I set in the Build Parameters section. This allows parameterizing the script without touching source control. I could also have used an environment variable, but this was more direct.

Comments

Popular posts from this blog

VB.NET: Raise base class events from a derived class

Apache Kafka - I - High level architecture and concepts

Upgrading Lodash from 3.x to 4.x