Visual Studio Team Services – Triggering A Build From A Build (Using PowerShell)

As of April 2016, Visual Studio Team Services (VSTS) does not support triggering a build from another build. This presents a problem if you want your setup to do something like start two builds from a single pull request onto a branch (because VSTS does not support starting multiple builds from one pull request trigger). Since I want to fire off a build whenever a pull request is made on the develop branch, I had to find my own solution.

Surprisingly, the solution I found is pretty simple: utilize the REST API provided by VSTS within a PowerShell script and run that as a build step within the build that is initially kicked off.

To do this, add a PowerShell step to your build definition and pass the script in through your source control, or write it inline.


Be aware that there’s a fairly small character limit on inline scripts. The script below simply posts a build definition id (IOSBUILD_DEFINITIONID) to the API, which kicks off the build. It utilizes an OAuth token from within the build, so we don’t have to worry about credentials. The API response will be written to the build log (Refer to this page for a detailed explanation of the API).

$url = "$($env:SYSTEM_TEAMFOUNDATIONCOLLECTIONURI)$env:SYSTEM_TEAMPROJECTID/_apis/build/builds?api-version=2.0"
$body = "{ 'definition' : { 'id' : $env:IOSBUILD_DEFINITIONID }, 'sourceBranch' : '$env:BUILD_SOURCEBRANCH' }"
$type = "application/json"

$headers = @{
    Authorization = "Bearer $env:SYSTEM_ACCESSTOKEN"
Write-Host "URL: $url"
$definition = Invoke-RestMethod -Uri $url -Body $body -ContentType $type -Method Post -Headers $headers
Write-Host "Definition = $($definition | ConvertTo-Json -Depth 1000)”

Optionally (you could put the id in line with the script instead), set the build definition id of the target build in the source build’s variables. To find the target build id, check the target build’s variables for “system.definitionId”.


Then head over to the Options tab and check “Allow Scripts to Access OAuthToken”.


And that’s all you have to do. Simple, right?

Update: If you’d like to know how your build can check and report back the status of the build it triggered, check out this follow-up post by Nathan Wilkinson.