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=, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a")
[Void][Reflection.Assembly]::Load("Microsoft.TeamFoundation.Build.Client, Version=, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a")
# Connect to the team collection
$tpc = New-Object Microsoft.TeamFoundation.Client.TfsTeamProjectCollection($collectionUri)
# 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)
			Write-Host "Cancel build"+$qb.Id