TeamCity.ServiceMessages from Powershell

In this post I describe the small example on how to use TeamCity.ServiceMessages library from powershell

Preparations

First you need to have TeamCity.ServiceMessages library assemblies downloaded. The easiest way to do it is to fetch the package from NuGet


NuGet.exe install TeamCity.ServiceMessages -ExceludeVersion

So in the TeamCity.ServiceMessage\lib\net35 you'll find JetBrains.TeamCity.ServiceMessages.dll. Further I assume assemblies are downloaded and available from powershell

The Script

First you need to know the methods you like to call. The most easiest way is to play with the library from Visual Studio project

It's required to have a using statement in the powershell script in order to use the library properly. I found the following solution to it:


#### from http://blogs.msdn.com/b/powershell/archive/2009/03/12/reserving-keywords.aspx
function TeamCityUsing($obj, [scriptblock] $sb)
{
try {
& $sb
} finally {
if ($obj -is [IDisposable]) {
$obj.Dispose()
}
}
}

This script implements using statement in powershell making the library usage simple.

The Code

Let's implement the code to report unit test into TeamCity with help of Service Messages implemented with help of TeamCity.ServiceMessage library:


#### loading reporting assembly
#### improve the path if needed
Add-Type -Path .\JetBrains.TeamCity.ServiceMessages.dll

#### create instance of the logging factory
$teamcityMessages = "JetBrains.TeamCity.ServiceMessages.Write.Special.TeamCityServiceMessages"
$teamcityWriterFactory = New-Object -TypeName $teamcityMessages


#### start reporting of service messages
TeamCityUsing ($writer = $teamcityWriterFactory.CreateWriter()) {
TeamCityUsing ($suite = $writer.OpenTestSuite("test-from-powershell")) {
TeamCityUsing ($test = $suite.OpenTest("some.powershell.test")) {
$test.WriteStdOutput("some test output")
}
}
}

Library Usage Examples

More library usage examples could be found here or here

I believe this would play well with TeamCity Powershell build runner.

Sources are available at GitHub. I setup a build configuration at TeamCity.JetBrains.com.

comments powered by Disqus