Skip to content

Instantly share code, notes, and snippets.

@flcdrg
Created March 21, 2026 05:24
Show Gist options
  • Select an option

  • Save flcdrg/f204fc3f84247fe6247d654c0a673b73 to your computer and use it in GitHub Desktop.

Select an option

Save flcdrg/f204fc3f84247fe6247d654c0a673b73 to your computer and use it in GitHub Desktop.
GitHub artifact management
# Inspired by https://www.eliostruyf.com/clean-github-actions-artifacts-script/
param(
[Parameter(Position = 0)]
[string]$Repo,
[Parameter(Position = 1)]
[int]$DaysOld = 5
)
if (-not (Get-Command gh -ErrorAction SilentlyContinue)) {
Write-Error "GitHub CLI (gh) is not installed or not available in PATH."
exit 1
}
$null = gh auth status *> $null
if ($LASTEXITCODE -ne 0) {
Write-Host "Please authenticate with the GitHub CLI using 'gh auth login'."
exit 1
}
if ([string]::IsNullOrWhiteSpace($Repo)) {
Write-Host "Usage: .\delete-github-action-artifacts.ps1 <owner/repo> [days-old]"
Write-Host "Example: .\delete-github-action-artifacts.ps1 owner/repo 5"
exit 1
}
Write-Host "Cleaning up artifacts older than $DaysOld days for repository: $Repo"
$pagesResponse = gh api --paginate --slurp -H "Accept: application/vnd.github+json" "/repos/$Repo/actions/artifacts?per_page=100" | ConvertFrom-Json
$allArtifacts = @()
foreach ($pageResponse in @($pagesResponse)) {
if ($null -ne $pageResponse.artifacts) {
$allArtifacts += @($pageResponse.artifacts)
}
}
if (-not $allArtifacts -or $allArtifacts.Count -eq 0) {
Write-Host "No artifacts found."
}
else {
foreach ($artifact in $allArtifacts) {
$id = $artifact.id
$name = $artifact.name
$createdAt = $artifact.created_at
if ($null -eq $id -or [string]::IsNullOrWhiteSpace($name) -or [string]::IsNullOrWhiteSpace($createdAt)) {
$artifactJson = $artifact | ConvertTo-Json -Compress
Write-Host "Skipping invalid artifact data: $artifactJson"
continue
}
try {
$createdAtUtc = [DateTimeOffset]::Parse($createdAt, [System.Globalization.CultureInfo]::InvariantCulture).UtcDateTime
$ageDays = [int][Math]::Floor(([DateTime]::UtcNow - $createdAtUtc).TotalDays)
if ($ageDays -gt $DaysOld) {
Write-Host "Deleting artifact: $name (ID: $id, Age: $ageDays days)"
$null = gh api -X DELETE "/repos/$Repo/actions/artifacts/$id" 2>$null
if ($LASTEXITCODE -ne 0) {
Write-Host "Failed to delete artifact: $name (ID: $id)"
}
}
else {
Write-Host "Keeping artifact: $name (ID: $id, Age: $ageDays days, Created At: $createdAt)"
}
}
catch {
Write-Host "Deleting artifact: $name (ID: $id, Created At: $createdAt)"
$null = gh api -X DELETE "/repos/$Repo/actions/artifacts/$id" 2>$null
if ($LASTEXITCODE -ne 0) {
Write-Host "Failed to delete artifact: $name (ID: $id)"
}
}
}
}
Write-Host "Cleanup completed."
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment