Automatically delete old downloads with PowerShell

As you browse the internet, over time as you download PDF files, applications, and documents, your downloads folder can begin to fill up with a lot of old files that can take up a lot of space on your hard drive.

As part of one of my jobs, I was downloading a lot of software continuously as software versions change, my downloads folder was continuously full of old files that I no longer needed.

To remedy this issue and keep my downloads folder clean, I set out to create a script to automatically delete any old files in my downloads folder that were older than 14 days. It's a pity that such a feature is not built into Google Chrome and other modern browsers, but fear not, this is something that a little PowerShell can fix.

Deleting Files Automatically With PowerShell

  1. The first thing we need in our script is a date to compare the age of our files, lets initialise a variable with a date and subtract 14 days.
    $comparison = (get-date).adddays(-14)
  2. Next, using Get-ChildItem we can get all the items in our downloads folder, here I am retrieving the username environment variable from the system so that this script can work for any user who logs onto the computer.

    The recurse parameter of Get-ChildItem includes files that are in subfolders in the downloads directory. We will then pass the list of items to a foreach loop to process each file.
    Get-ChildItem "C:\Users\$([Environment]::UserName)\Downloads" -Recurse | foreach($_){}
  3. Now that we have our list of files in the downloads directory, we will iterate over each of them to check if they are older that 14 days, we will compare the files date to our comparison date we created in step one.

    If the file is older than 14 days old, we will use the Remove-Item function to delete the file.
    if([datetime]($_.LastWriteTime) -lt $comparison){
        Remove-Item ($_.FullName)

Deleting Particular File Types in PowerShell

In my script there were particular file types that I wanted to delete regardless of age as I'm constantly downloading the same files, for this I added an else condition to my script to check for particular file types and then delete them.

  1. I added a else condition to my script, if the file is not older then 14 days then I check the file extension and if it matches one of the extensions I specify I delete the file.

    else {
        #For particular file types, remove them regardless of age
        if(($_.Extension) -contains ".pdf" -or ($_.Extension) -contains ".jpg" -or ($_.Extension) contains ".dat"){
            Remove-Item ($_.FullName)

You can see my full completed script below which is configured to delete files that are older than 14 days, or files that have an extension of .jpg, .pdf, or .dat

Was this helpful?

Yes No