PowerShell classics: deleting files older than N days from a folder

Posted: (EET/GMT+2)

 

If you need to clean up old files in a folder, PowerShell makes it straightforward to delete files older than a given number of days. The traditional use case could be for example an application logging folder that has a daily roll on the log files, and thus, they would eventually fill the disk unless you clear them.

Now, let's see a PowerShell implementation. The basic approach is the following: first, list files you want to clear, then filter by the file's LastWriteTime property, and finally, remove the matching files.

For instance, along these lines:

$path = "C:\Temp"
$days = 30

Get-ChildItem -Path $path -File |
Where-Object { $_.LastWriteTime -lt (Get-Date).AddDays(-$days) } |
Remove-Item -Force

This removes all files in the folder C:\Temp that were last modified more than 30 days ago.

If you want to include subfolders, add -Recurse:

Get-ChildItem -Path $path -File -Recurse |
Where-Object { $_.LastWriteTime -lt (Get-Date).AddDays(-$days) } |
Remove-Item -Force

Tip: you can test the selection first by omitting Remove-Item:

Get-ChildItem -Path $path -File |
Where-Object { $_.LastWriteTime -lt (Get-Date).AddDays(-$days) }

This shows which files would be deleted. Good for the initial run.

Be careful when running with -Recurse or elevated permissions. It's easy to remove more than intended if the path is incorrect.

Hope this helps!