Here’s a quick Windows Powershell script to delete all files in a folder that are older than a certain number of days.
# Delete all Files in <directory> older than <x> day(s)
param($directory, $days);
function DeleteOlderFiles($directory, $days)
{
$CurrentDate = Get-Date
$DatetoDelete = $CurrentDate.AddDays(-$days)
Get-ChildItem $directory | Where-Object { $_.LastWriteTime -lt $DatetoDelete } | Remove-Item
}
DeleteOlderFiles $directory $days
This will delete files older than whatever $days is set to in the path defined by $directory.
Deleting files in sub-directories
If you want to extend this function further and make it include sub-directories, replace the following line:
Get-ChildItem $directory | Where-Object { $_.LastWriteTime -lt $DatetoDelete } | Remove-Item
with:
Get-ChildItem $directory -Recurse | Where-Object { $_.LastWriteTime -lt $DatetoDelete } | Remove-Item
Save your script as something sensible like DeleteOlderFiles.ps1 and pop it some place you can access it on the command line.
Executing the code
The code runs in Powershell but can be executed from the Command Line or a Batch Script with:
powershell -ExecutionPolicy Bypass DeleteOlderFiles.ps1 “C:\Directory\To\Purge” 30
The above command should execute with no errors. In my instance I needed to use “-ExecutionPolicy Bypass” to get the script to run on my command line – but it may not be required for your use-case. “C:\Directory\To\Purge” is the directory path – remember to use quotation marks if there’s a space in the path. And 30 is the number of days to keep (so anything older than 30 days will be deleted).