I have a directory full of backupfiles but need to automate the cleanup of that directory, because i run out of space. The simplest way to do it would be a powershell script.
The Backup creates 2 Backups per Day. I want to keep 2 Backups a Day for 7 Days, backups that are older than 7 days but not older than 3 months i want to keep 1 from each day and everything older than 3 months i want to keep 1 from each week. Everything older than 2 years gets deletet.
The first function i wrote deletes everything older than 2 years:
$checkPath = "C:\demo\"
$list = (Get-ChildItem -Path $checkPath | Where-Object {$_.LastWriteTime -lt (Get-Date).AddYears(-2)}).FullName
$count = $list.Length
for ($i = 0; $i -lt $count; $i += 1)
{
Write-Verbose "[$i] $($list[$i])"
Remove-Item -Path $list[$i]
}
After that i create a function to delete every 2nd backup:
$checkPath = "C:\demo\"
$list = (Get-ChildItem -Path $checkPath | Where-Object {$_.LastWriteTime -lt (Get-Date).AddDays(-7)} | Where-Object {$_.LastWriteTime -lt (Get-Date).AddMonths(-3)}).FullName
$count = $list.Length
for ($i = 0; $i -lt $count; $i += 2)
{
Write-Verbose "[$i] $($list[$i])"
Remove-Item -Path $list[$i]
}
Well i feel a bit lost, am i on the right path here? Does anyone may have a suggestion to do this "better"?