1 min read

Stop multiple pipeline runs in Azure DevOps


Sometimes you need to stop hundreds of pipeline runs in Azure DevOps. There is no good way to do this using the az devops CLI, so you have to resort to the REST API.

stop_multiple_pipeline_runs.ps1
 
 
$AzureDevOpsPAT = "***" # Replace the values in this for the variables with your own.
$OrganizationName = "" # Replace the values in this for the variables with your organisation name.
$ProjectName = "" # Replace the values in this for the variables with your project name.
$AzureDevOpsAuthenicationHeader = @{Authorization = 'Basic ' + [Convert]::ToBase64String([Text.Encoding]::ASCII.GetBytes(":$($AzureDevOpsPAT)")) }
$Uri = "https://dev.azure.com/$($OrganizationName)/$($ProjectName)/_apis/build/builds?statusFilter=Started&api-version=5.1"
$PendingJobs = Invoke-RestMethod -Uri $Uri -Headers $AzureDevOpsAuthenicationHeader -Method get -ContentType "application/json"
$JobsToCancel = $PendingJobs.value
ForEach ($build in $JobsToCancel) {
    $build.status = "Cancelling"
    $body = $build | ConvertTo-Json -Depth 10
    $urlToCancel = "https://dev.azure.com/$($OrganizationName)/$($ProjectName)/_apis/build/builds/$($build.id)?api-version=5.1"
    Invoke-RestMethod -Uri $urlToCancel -Method Patch -ContentType application/json -Body $body -Header $AzureDevOpsAuthenicationHeader
}