Deleting files in a directory older than a number of days

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


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).

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.