Cleaning Publish Folders for TFS/Visual Studio Online

The data growth a year down the line on our build server is pretty insane. There are nearly a terabyte of files in the Publish folder, even though we run cleanup scripts after each build in the pipeline.

The problem is that the retention in Visual Studio Online does not match what is in the Publish folder as these are never cleared. You need to create a pipeline step or run a script.

I created a script that can be run on a schedule. Here, you need to create a personal access token and replace it below. You also need to enter the tenant name and the project name, plus the build definition numbers you need to retrieve.

To get the build numbers, click the build in VSTO in the browser and check the URL parameter "definitionId".

$personalAccessToken = "[PERSONAL ACCESS TOKEN]"
$uri = "https://[TENANT][PROJECT]/_apis/build/builds?api-version=2.0&definitions=[DEFINITION IDs, COMMA SEPARATED]&statusFilter=completed&resultFilter=succeeded
$data = Invoke-RestMethod `
-Uri $uri `
-Headers @{Authorization = 'Basic ' + [Convert]::ToBase64String([Text.Encoding]::ASCII.GetBytes(":$($personalAccessToken)")) }

if ($data -eq $null -or $data.value -eq $null) {
    throw [System.Exception] "Builds not retrieved"

foreach($folder in gci -Path $root -Directory) {
    Write-Host "Cleaning folder"$folder"..." -ForegroundColor Cyan
    foreach ($build in gci -Path $folder.FullName -Directory) {
        Write-Host ("`t" + $build.Name + ": ") -NoNewline
        $test = ($data.value | Where-Object { $ -eq $folder.Name -and $_.buildNumber -eq $build.Name })
        if ($test -eq $null) {
            Write-Host "Deleted" -ForegroundColor Red
            $out = Remove-Item -Path $build.FullName -Recurse -Force
        } else {
            Write-Host "Retained" -ForegroundColor Green