Skip to content

Instantly share code, notes, and snippets.

@Fronix
Last active October 11, 2022 10:33
Show Gist options
  • Save Fronix/d64e43a45973d67842e52bf588bd194c to your computer and use it in GitHub Desktop.
Save Fronix/d64e43a45973d67842e52bf588bd194c to your computer and use it in GitHub Desktop.
Cleanup release folders
# Clean up old releases on the server
# This script will check a specified folder for all release versions (i.e. R1, R2, R3, etc.) and delete all except the last X releases.
# Can be used together with Azure DevOps releases, each rlease is named RX which this script takes care of
# Modify $regex = '^.*?\(R(?<release>\d+)\).*' if you want to look for your own foldertype
# Usage
# release-cleanup.ps1 -releasesPath /path/to/release -releasesToKeep 3
# Options
# --releasePath
# Path to where folders are stored
#
# --releasesTokeep
# Number of folders to keep, rest will be deleted
#
# --dryRun
# Use if you want to run without deleting any folders
param ([string] $releasesPath, [int] $releasesToKeep, [bool] $dryRun)
function Green
{
process { Write-Host $_ -ForegroundColor Green }
}
function Red
{
process { Write-Host $_ -ForegroundColor Red }
}
if ([string]::IsNullOrWhiteSpace($releasesPath)) {
Write-Output "(-releasesPath) Missing path to the releases folder" | Red;
Write-Output "Exiting...";
exit 1;
}
if ([string]::IsNullOrWhiteSpace($releasesToKeep) -Or $releasesToKeep -lt 3) {
Write-Output "(-releasesToSkip) Missing number of releases to skip or it's less than 3 which is the minimum" | Red;
Write-Output "Exiting...";
exit 1;
}
$regex = '^.*?\(R(?<release>\d+)\).*'
$allFolders = get-childitem -path $releasesPath -Recurse |
Where-Object { $_.Name -match $regex } |
Sort-Object { [int] ($_.Name -replace $regex, '${release}') }
# Get all releases except the last X releases
$foldersToDelete = $allFolders | Select-Object -SkipLast $releasesToKeep;
if($foldersToDelete.Count -eq 0) {
Write-Output "No releases to delete";
exit 0;
}
if($dryRun -eq $true) {
Write-Output "Dry run, no folders will be deleted" | Red
Write-Output "Number of folders $($foldersToDelete.Count)";
Write-Output "Folders to delete: `r`n $($foldersToDelete | ForEach-Object { "$($_.Name)`r`n" })";
} else {
Write-Output "Deleting $($foldersToDelete.Count) folders";
Write-Output "Folders to delete: `r`n $($foldersToDelete | ForEach-Object { "$($_.Name)`r`n" })";
$foldersToDelete | Remove-Item -Recurse -Force
}
Write-Output "Done" | Green;
exit 0;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment