While I was working on migrating a number of my services to use OData rather than a custom data sculpting solution that I had built, I paused a few of my pipelines to reduce the build/deployment times.  BAD MISTAKE!

I ended up with hundreds of queued jobs waiting for me to un-pause the pipelines.  Sure I could go and click the ellipse for each of the jobs in each of the pipelines and then select "Cancel" and then confirm it by clicking "yes"....  but come on, that would be an absolute waste of time.  This is where PowerShell came in.

Below is the script that will find all jobs with the status of "notStarted" and propogate through them setting the status to "Cancelling" for each job.  

 

# Replace the values in this for the variables with your own.
$AzureDevOpsPAT = "{Personal Access Token}"
$OrganizationName = "{DevOps Organization Name}"
$ProjectName = "{DevOps Project Name}"

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

$Uri= "https://dev.azure.com/$($OrganizationName)/$($ProjectName)/_apis/build/builds?statusFilter=notStarted&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
}

Seconds later I had cleared out all the pending jobs in my projects pipelines.

brandon ~ 04/20/2021 05:05:17