Automatically Delete Old Files In Your Downloads Folder With PowerShell

If you don’t purge your Downloads folder occasionally, the folder can get unwieldy. While hard disk space may be a consideration, I’m more annoyed by the extended processing time it takes a mid-range PC to just list the contents of a never-emptied Downloads folder.

This post contains a script that deletes anything in a set Downloads folder older than 30 days, though you can easily configure it to point to a different folder and/or change the number of days to whatever you wish.

I copied nearly everything from this script directly from a popular StackOverflow post. I’ve added variables to make it easier to customize your Downloads folder path and how old you want to allow files to get. This script is just the first steps, though. After you get it running, follow these instructions to schedule a PowerShell script to run whenever the computer is unlocked.

 

#CONFIGURATION
#
#
$days_old = 30 #How many days ago is old enough to delete?
$path = 'C:\Users\andrew\Downloads' #Set to the path of your own Downloads file
#
#
#END CONFIGURATION

#Thanks to this code snippet from StackOverflow
#https://stackoverflow.com/questions/17829785/delete-files-older-than-15-days-using-powershell

$limit = (Get-Date).AddDays(-$days_old)
Get-ChildItem -Path $path -Recurse -Force | Where-Object { !$_.PSIsContainer -and $_.CreationTime -lt $limit } | Remove-Item -Force

# Delete any empty directories left behind after deleting the old files.
Get-ChildItem -Path $path -Recurse -Force | Where-Object { $_.PSIsContainer -and (Get-ChildItem -Path $_.FullName -Recurse -Force | Where-Object { !$_.PSIsContainer }) -eq $null } | Remove-Item -Force -Recurse