Skip to content

Instantly share code, notes, and snippets.

@nichollsc81
Created May 12, 2023 13:17
Show Gist options
  • Save nichollsc81/430d82ad403ff9edb44eb7e29e2a5ece to your computer and use it in GitHub Desktop.
Save nichollsc81/430d82ad403ff9edb44eb7e29e2a5ece to your computer and use it in GitHub Desktop.
function Invoke-CancelAdoBuildsAndJobs
{
param(
[Parameter()]
[ValidateNotNullOrEmpty()]
$AzureDevOpsPAT,
$OrganizationName,
$ProjectName
)
$ErrorActionPreference = 'Stop'
$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
if($JobsToCancel)
{
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
}
}
else
{
"Nothing queued, nothing to cancel."
}
}
Invoke-CancelAdoBuildsAndJobs -AzureDevOpsPAT '' -OrganizationName '' -ProjectName ''
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment