I have a bunch of drives on which I backup our servers (I rotate them) and I was running out of space on them because of the old backup files. So I decided to delete every file that was created more than a 1 month(31 days) ago, as it’s specified in the backup procedure.
Here is the powershell one liner:
Dir ‘d:\testxxx’ | Where-Object { $_ -is [System.IO.FileInfo] } | Where-Object {$_.CreationTime -lt (Get-Date).AddDays(-31)} | Remove-Item –Force
and you can add the –Recurse switch to find all files in the subfolders of the path like this:
Dir ‘d:\testxxx’ -Recurse | Where-Object { $_ -is [System.IO.FileInfo] } | Where-Object {$_.CreationTime -lt (Get-Date).AddDays(-31)} | Remove-Item –Force
You’ll want to replace d:\testxxx with the name of your folder or drive. You set how old would be the remaining files by changing the number or method in the (Get-Date).AddDays(-31) section .
For example if you want that the files that you keep would be of at most two months old you would need to change the powershell command like this:
Dir ‘d:\testxxx’ | Where-Object { $_ -is [System.IO.FileInfo] } | Where-Object {$_.CreationTime -lt (Get-Date).AddMonths(-2)} | Remove-Item –Force
Of course you have o bunch of methods available:
AddDays
AddHours
AddMilliseconds
AddMinutes
AddMonths
AddSeconds
AddTicks
AddYears
And if you need to keep the older files you simply change the Where-Object {$_.CreationTime -lt (Get-Date).AddMonths(-2)
like this:
Where-Object {$_.CreationTime -gt (Get-Date).AddMonths(-2)
But be very carefull with this command and test it first on a test folder and only after you’re certain of the result use it because it will delete a lot of files in no time.
For testing you’ll need to set the creation time of some files at your convenience so that’s how you’ll do it.
For a single file:
$a=Get-ChildItem d:\testxxx\file1.txt
$a.CreationTime=(Get-Date).AddMonths(-3)
For multiple files with name pattern filexxx.txt
foreach($x in Get-ChildItem d:\testxxx\file*.txt)
{
$x.CreationTime=(Get-Date).AddMonths(-3)
}