Summary: Goal of the script is to remove all the leases that are set on all of the builds that are created with a specific pipeline.
Date: Around 2022
Refactor: 6 April 2025: Checked links and formatting.
Goal of the script is to remove all the leases that are set on all of the builds that are created with a specific pipeline:
If the leases kept you from deleting the build pipeline, you can delete the pipeline afterwards.
Note that you need to change the first four variables.
# Define organization base url, PAT and API version variables $orgUrl = "https://dev.azure.com/ORGNAME" $project = "projectname" $builddefinition = "buildpipelinename" $pat = "XXXX" $apiversion = "api-version=6.1-preview" # Create header with PAT $token = [System.Convert]::ToBase64String([System.Text.Encoding]::ASCII.GetBytes(":$($pat)")) $header = @{authorization = "Basic $token"} #Get build definition ID for $buildefinition $buildurl = "$orgurl/$project/_apis/build/definitions?$apiversion" Write-Output "Build url = $buildurl" $builddefinitionid = ((Invoke-RestMethod -Uri $buildurl -Method GET -ContentType "application/json" -Headers $header).Value | select-object id,name | where-object {$_.name -eq $builddefinition}).id Write-Output "Build definition $builddefinition has the id $builddefinitionid" # Function to delete all retention leases for a build definition function DeleteLease($defid) { #Get all leases for the build definition $leaseurl = "$orgurl/$project/_apis/build/retention/leases?$apiversion&definitionId=$defId" Write-Output "Lease url = $leaseurl" $leases = (Invoke-RestMethod -Method GET -Uri $leaseurl -ContentType "application/json" -Headers $header ) Write-Output "The Build definition $builddefinition has $($leases.count) leases" #Loop through all leases and delete them. foreach ($lease in $leases.value) { $leaseId = $lease.leaseId $leaseurl = "$orgurl/$project/_apis/build/retention/leases?ids=$($leaseId)&$apiversion" Write-Output $leaseurl Invoke-RestMethod -Method DELETE -Uri $leaseurl -ContentType "application/json" -Headers $header } } DeleteLease $builddefinitionid