Cleanup outdated artifacts in Artifactory

The below script can be used to cleanup outdated artifacts in Artifactory. It uses REST API to scan and delete items by age. Make sure you use Powershell 5.

#
# CleanupArtifacts.ps1
# Cleans up Artifactory repository from old artifacts.
# Requires Powershell 5 because of the bug with Invoke-RestMethod in PS 3,4!
#
param([Parameter(Mandatory=$true)]$artifactoryUrl, [Parameter(Mandatory=$true)]$authorization, [Parameter(Mandatory=$true)]$repo, [Parameter(Mandatory=$true)]$path, [Parameter(Mandatory=$true)]$lifetime)
$ErrorActionPreference = "Stop"
trap
{
Write-Host $_
exit 1
}
$headers = @{Authorization = "Basic $authorization" }
$criteria = @{
"repo" = @{"`$eq" = $repo}
"path" = @{"`$match" = $path}
"created" = @{"`$lt" = (get-date).AddDays(-$lifetime).ToString("yyyy-MM-dd")}
}
$query = 'items.find(' + ($criteria | ConvertTo-Json) + ')';
Write-Host Requesting a list of outdated artifacts in $repo/$path
$expiredItems = Invoke-RestMethod -Uri "$artifactoryUrl/api/search/aql" -Headers $headers -Method Post -Body $query
Write-Host Found $expiredItems.results.Count outdated artifacts
Write-Host Deleting outdated artifacts
foreach ($artifact in $expiredItems.results) {
$artifactPath = $($artifact.repo + "/" + $artifact.path + "/" + $artifact.name)
Write-Host Removing $artifactPath
Invoke-RestMethod -Uri "$artifactoryUrl/$artifactPath" -Headers $headers -Method Delete
}
Write-Host Deleted $expiredItems.results.Count outdated artifacts

Comments

Popular posts from this blog

TFS Proxy not working: The source control proxy is not responding

Demystifying fast up-to-date check in Visual Studio C# projects