bulk delete nuget pkgs versions in azure devops.

recently we encountered a scenario where in we had to delete few hundreds of nuget pkgs versions in azure devops. The UI does give you option to multi-select but it does not work.

to overcome this issue we created a small console app to the deleting, here is the snippet.

// See https://aka.ms/new-console-template for more information
using System.Net.Http.Headers;



var personalaccesstoken = "ADD YOUR OWN PAT VALUE FROM AZURE DEVOPS";

using (HttpClient client = new HttpClient())
{
    client.DefaultRequestHeaders.Accept.Add(
        new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));

    client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic",
        Convert.ToBase64String(
            System.Text.ASCIIEncoding.ASCII.GetBytes(
                string.Format("{0}:{1}", "", personalaccesstoken))));

    for (int i = 74; i <= 82; i++) // version numbers that your want to delete
    {
        try
        {
            string pkgname = "NAME OF THE PKG";
            string urir = $"https://pkgs.dev.azure.com/***********/******/_apis/packaging/feeds/*********/nuget/packages/{pkgname}/versions/1.1.{i}-remove-extra-apis?api-version=5.1-preview.1";
            if (pkgname.Contains("******"))
            {
                using (HttpResponseMessage response = client.DeleteAsync(urir).Result)
                {
                    response.EnsureSuccessStatusCode();
                    string responseBody = await response.Content.ReadAsStringAsync();
                    Console.WriteLine(responseBody);
                }
            }

            Console.WriteLine(urir);
        }
        catch (Exception ex)
        {
            Console.WriteLine($"for {i}:: "+ex.Message);
        }
    }
}

Console.ReadLine();

link to generate the PAT (Personal access token)

Use personal access tokens – Azure DevOps | Microsoft Docs