“Delete Files Older Than” Batch Script

batch-filewindows-server-2008-r2

So in the work of doing backups, I need a batch script that would allow me to delete files in a specified directory, that are older than lets say, 3 days. This script will be set as a scheduled task to run at a specified time every day.

Best Answer

If powershell is acceptable (should be, as its enabled by default on Server 2008+) try this:

$numberOfDays = 3
$Now = Get-Date
$TargetFolder = “C:\myoldfiles”
$LastWrite = $Now.AddDays(-$numberOfDays)
$Files = get-childitem $TargetFolder -include *.bak, *.x86 -recurse | Where {$_.LastWriteTime -le “$LastWrite”} 

foreach ($File in $Files)
{
    write-host “Deleting File $File” -foregroundcolor “Red”;
    Remove-Item $File | out-null
} 

Souce here.