Delete files older than X using PowerShell

This article will discuss how to delete files older than x years, days, hours, or minutes using PowerShell. We will do that by breaking down the task into four ideas. After going through the four ideas, we will create the final PowerScript script you can use to delete older values.

Idea 1: Getting a List of All Files

This is done using the Get-ChildItem cmdlet. For example,

You can use this line to get all files and folders in a directory:

If you want to get the folders, subfolders, and files within a directory, issue the -Recurse parameter as follows.

And if you want to get files only, supply the -File parameter.

We can also filter the Get-ChildItem list using the -Filter option as follows:

You can read more about Get-ChildItem in the documentation.

Idea 2: Reading the Creation or Modification Time for Files and Folders

You can use the Get-ChildItem cmdlet to read information about a file. Among the properties retrieved by the cmdlet are LastWriteTime and CreationTime. We need these properties to identify files older than x days.

You can also right-click on a given file and see the Creation Time and Modification Time on the Properties option. You should see the results matching the output of Get-ChildItem results.

Idea 3: Computing CutOff Date

The current date can be retried with the command

Then get the cutoff date based on Years, Months, Days, etc., as shown below

If we want to remove files older than 30 days, you need to remove files whose CreationTime or ModificationTime comes before Today’Date subtract 30 days, that is, (Get-Date).AddDays(-30).

Idea 4: Removing a File Older than 7 Days

This uses what we have done in Ideas 1, 2, and 3 to identify if the file should be removed, then remove it if it is older than x days. Removing a file is done using the Remove-Item cmdlet.

This code will remove the example1.png file if it is older than 7 days.

If you want to do a dry run (viewing what will be removed without actually removing them) of Remove-Item, use the -WhatIf parameter on the cmdlet as follows

Let’s Put it All Together

After going through the four ideas above, this script will be easy to understand. This script deletes all files older than 30 days in the <folder> (you can pick a different duration using what we discussed in Idea 3).

In the code above, Get-ChildItem fetches all the files on the $folder_path and pipes the results to Where-Object, which will filter the list to get files that have not been modified in the last 30 days. The list is then passed to the Remove-Item cmdlet to remove the resulting list.

Important: If you want to automate removing old files using the PowerShell script presented here, you can add it to Windows Task Scheduler (reference).