Remove TFS builds from queue with powershell

This morning we had a problem with our Team Foundation Build Server, solution tend to be is to unregister the build controller and register it again. But today there was builds in queue so I could’t do that. To fix it I wrote a powershell script that removed all builds from the queue.

$collectionUri = New-Object Uri("http://uriToCollection")
$controllerName = "Controller name"
 
#Load assemblies
[Void][Reflection.Assembly]::Load("Microsoft.TeamFoundation.Client, Version=11.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a")
[Void][Reflection.Assembly]::Load("Microsoft.TeamFoundation.Build.Client, Version=11.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a")
 
# Connect to the team collection
$tpc = New-Object Microsoft.TeamFoundation.Client.TfsTeamProjectCollection($collectionUri)
#tpc.EnsureAuthenticated()
 
# Get the build service
$bs = $tpc.GetService([Microsoft.TeamFoundation.Build.Client.IBuildServer])
$qbSpec = $bs.CreateBuildQueueSpec("*", "*")
 
# Query the build service
$qbResults = $bs.QueryQueuedBuilds($qbSpec)
Foreach ($qb in $qbResults.QueuedBuilds)
{
	if($qb.BuildController)
	{							
		if(!$qb.BuildController.Name.CompareTo($controllerName))
		{
			$qb.Cancel()
			Write-Host "Cancel build"+$qb.Id
		}
	}
}