Created
June 26, 2023 02:34
-
-
Save bartvdbraak/3d8b9d707ecc8b90b8fdb0912c8a8502 to your computer and use it in GitHub Desktop.
This PowerShell script deletes a specified Azure DevOps pipeline and its builds.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
param ( | |
[Parameter(Mandatory=$true)] | |
[string]$PersonalToken, | |
[Parameter(Mandatory=$true)] | |
[string]$Organization, | |
[Parameter(Mandatory=$true)] | |
[string]$Project | |
) | |
function Invoke-AzureDevOpsAPI { | |
param ( | |
[Parameter(Mandatory=$true)] | |
[string]$Uri, | |
[Parameter(Mandatory=$false)] | |
[string]$Method = "Get", | |
[Parameter(Mandatory=$false)] | |
[string]$ContentType = "application/json", | |
[Parameter(Mandatory=$false)] | |
[string]$Body = $null | |
) | |
$token = [System.Convert]::ToBase64String([System.Text.Encoding]::ASCII.GetBytes(":$($PersonalToken)")) | |
$header = @{authorization = "Basic $token"} | |
Invoke-RestMethod -Uri $Uri -Method $Method -ContentType $ContentType -Headers $header -Body $Body | |
} | |
$pipelineName = Read-Host "Please enter the pipeline to delete" | |
# Get all build definitions | |
$url = "https://dev.azure.com/$Organization/$Project/_apis/build/definitions?api-version=6.0-preview.7" | |
$buildDefinitions = Invoke-AzureDevOpsAPI -Uri $url | |
$buildDefinitions.value | Sort-Object id | ForEach-Object { | |
Write-Host $_.id $_.name $_.queueStatus | |
if ($_.name -ne $pipelineName) { | |
return | |
} | |
# Get all builds for a definition | |
$url = "https://dev.azure.com/$Organization/$Project/_apis/build/builds?definitions=$($_.id)&api-version=6.0-preview.5" | |
$builds = Invoke-AzureDevOpsAPI -Uri $url | |
$builds.value | Where-Object { $_.retainedByRelease -eq "True" } | Sort-Object id | ForEach-Object { | |
# Report on retain status | |
Write-Host "BuildId:" $_.id "retainedByRelease:" $_.retainedByRelease | |
# API call to update the build | |
$url = "https://dev.azure.com/$Organization/$Project/_apis/build/builds/$($_.id)?api-version=6.0-preview.5" | |
Invoke-AzureDevOpsAPI -Uri $url -Method Patch -Body (ConvertTo-Json @{"retainedByRelease"="false"}) -ContentType "application/json" | |
} | |
$url = "https://dev.azure.com/$Organization/$Project/_apis/build/definitions/$($_.id)?api-version=6.0-preview.1" | |
Write-Host $url | |
Invoke-AzureDevOpsAPI -Uri $url -Method Delete -ContentType "application/json" | |
Write-Host "Pipeline: $pipelineName ($($_.id)) deleted" | |
} | |
Write-Host "Done" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment