S Mir
S Mir

Reputation: 33

How can I cancel & delete a waiting build in the queue using PowerShell

Due to long running builds various next in line builds take longer time to execute.

Is there a way I can cancel and delete waiting build in queue and give way for latest triggered build using PowerShell or REST API's?

Upvotes: 2

Views: 1785

Answers (1)

Amit Baranes
Amit Baranes

Reputation: 8132

The following code snippet goes over all TFS builds,Gets the Builds which in Progress and not started, and then, cancel them.

$tfsUrl = "http://{server}:{port}/{organization}/{collection}/{project}" # TFS Base URL
$BuildDefsUrl = "$tfsUrl/_apis/build/definitions?api-version=2.0" # TFS build definitions URL
$BuildsUrl = "$tfsUrl/_apis/build/builds"  #TFS Builds URL

$Builds = (Invoke-RestMethod -Uri ($BuildDefsUrl) -Method GET -UseDefaultCredentials).value | Select id,name # get all builds 
#for filtering use : |  Where-Object {$_.name -like "*Your Pattern*"}

foreach($Build in $Builds)
{
    $command = "$($BuildsUrl)?api-version=3.2-preview.3&resultFilter=inprogress&definitions=$($Build.id)&queryOrder=finishTimeDescending"
 
    $Ids = (((Invoke-RestMethod -Method Get -Uri $command -UseDefaultCredentials).value) | where status -like "*notStarted*").id # get waiting builds id's

    foreach($id in $Ids)
    {
            $uri =  "$($BuildsUrl)/$($id)?api-version=2.0" # TFS URI
            $body = '{"status":4}' # body 
            $result = Invoke-RestMethod -Method Patch -Uri $uri -UseDefaultCredentials -ContentType 'application/json' -Body $body -Verbose #cancel  build
    }
} 

The above example is pretty old. The code snippet below working for Azure Devops-

$PATToken = "PAT_GOES_HERE"
$AuthHeader= @{Authorization = 'Basic ' + [Convert]::ToBase64String([Text.Encoding]::ASCII.GetBytes(":$($PATToken)")) }

$azureDevops = "https://dev.azure.com/{organization}/{project}"
$BuildsUrl = "$azureDevops/_apis/build/builds" 

$filterBuilds = "$($BuildsUrl)?statusFilter=notStarted&api-version=6.0"
    
(Invoke-RestMethod -Method Get -Uri $filterBuilds -Headers $AuthHeader).value | % {
  $uri =  "$($BuildsUrl)/$($_.id)?api-version=6.0" # Azure Devops URI
  $body = '{"status":4}' # body 
  $result = Invoke-RestMethod -Method Patch -Uri $uri -Headers $AuthHeader -ContentType 'application/json' -Body $body -Verbose #cancel  build
  Write-Output "$($_.definition.name) cancaled"
}

Upvotes: 4

Related Questions