Skip to content

Instantly share code, notes, and snippets.

@zhilich
Created November 6, 2017 03:32
Show Gist options
  • Save zhilich/fc5a03b6a74a4b6fce69a6cb18bf7744 to your computer and use it in GitHub Desktop.
Save zhilich/fc5a03b6a74a4b6fce69a6cb18bf7744 to your computer and use it in GitHub Desktop.
Cleans up Artifactory repository from old artifacts.
#
# 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
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment