How to Delete Files Older than N Days Automatically in Windows

Windows 10 has built-in features to free up space by deleting old files in the %temp% directory and Downloads folder. Windows 10 Settings has an option (“Storage”) which automatically clears temporary files your apps are not using, files in the Downloads that haven’t been modified in the last x days, or files lying in the Recycle Bin for x days.

windows 10 storage settings cleanup options

Also, the Disk Cleanup tool clears up files in the %temp% directory that haven’t been accessed in the last 7 days.

However, Disk Cleanup and Storage settings target only the %temp% and Downloads folders. To delete files that are older than a certain number of days in a “custom” folder location such as your Documents folder, you need to use one of these three methods:

How to Auto Delete Files Older than N Days in Windows

Some of the methods below let you use either the “date created” or “date modified” property of files as a baseline to determine “older” files, as per your necessity.

Method 1. Delete Files that are Older than ‘N’ days Using File Explorer

Using Windows Search, you can easily get the list of files based on a selected date range, or files older than a certain date.

  1. Open the folder in which you want to delete older files.
  2. Click on the search box or press F3 button on the keyboard.
  3. Click on the Date modified button, and choose one of the drop-down options, say “Last week”.
    delete files older than x days in windows
  4. Windows Search will filter the results instantly. Select the files you want to delete, and press the Delete key on your keyboard.

Important: By default, Windows search looks for files in the current folder AND all subfolders. To limit searches to the current folder only, click “Current folder” button on the Search toolbar/ribbon.

Advanced Search Query: “Date” Operators

If the pre-set date range options don’t suit you, you can type in a custom search query. In the search box, type the following to filter down files from a custom date range:

datemodified:1/1/2017 .. 12/31/2017

This finds files that have been modified during the said date range. You can also use datecreated: dateaccessed: or date: (especially for camera images) operators. Note that date: operator uses the date metadata (EXIF) recorded by the camera.

RELATED: How to Search for Files Created Between Two Dates in Windows

To find files that haven’t been modified after November 1, 2017 use the less-than (<) symbol with the datemodifed: operator, as below:

datemodified:‎<11/1/‎2017

delete files older than x days in windows

Select the files from the list and delete them.

Tip: Instead of typing the date range manually, type datemodified: or datecreated: or dateaccessed: or date: operator in the search box and let File Explorer show the date picker for you. You can then pick a date or date range from the pop-up. To specify a date range, select the first date and drag the cursor to the appropriate field.

If you wish to delete older files automatically rather than doing a search query every time, you need to create a batch file or PowerShell.


Method 2: Delete Files Older Than ‘N’ Days Using Command Prompt

The ForFiles console tool (in Windows 7, Windows 8, Windows 8.1 and Windows 10) selects a file or a set of files and executes a command on that file or set of files.

Forfiles Help -- Command-line switches

/P - Indicates the path to start searching. The default folder is the current working directory (.).
/S - Instructs forfiles to recurse into subdirectories. Like "DIR /S".
/D - Select files with a last modified date. For example,-365 means over a year ago, -30 means a month ago.
/C "command" - Indicates the command to execute for each file. Command strings should be wrapped in double quotes.

The default command is "cmd /c echo @file".

The following variables can be used in the command string:
 @file - returns the name of the file.
 @fname - returns the file name without extension.
 @ext - returns only the extension of the file.
 @path - returns the full path of the file.
 @relpath - returns the relative path of the file.
 @isdir - returns "TRUE" if a file type is
 a directory, and "FALSE" for files.
 @fsize - returns the size of the file in bytes.
 @fdate - returns the last modified date of the file.
 @ftime - returns the last modified time of the file.

To view the entire list of command-line arguments supported by this tool, type FORFILES /? in Command Prompt.

To find and delete files older than certain number of days using ForFiles, open a Command Prompt window, and type one of the following commands:

ForFiles /p "D:\My Scripts" /s /d -30 /c "cmd /c del @path"

-or-

ForFiles /p "D:\My Scripts" /s /d -30 /c "cmd /c del @file"

delete files older than x days in windows forfiles.exe forfiles command

The above assumes that the folder path is D:\My Scripts and you want to delete files older than 30 days. Customize the folder path and number of days according to your needs.

You’ll see no output message if the command is successful. If no files match the specified criteria, you’ll see the message ERROR: No files found with the specified search criteria.

Additional tip: To conduct a dry run before attempting to delete files, to check which files are affected for the specified criteria, replace the command del with echo, as below:

ForFiles /p "D:\My Scripts" /s /d -30 /c "cmd /c echo @path"

-or-

ForFiles /p "D:\My Scripts" /s /d -30 /c "cmd /c echo @file"

forfiles delete older files x days echo

Optionally, you can create a batch file with the above command. Or to automatically run the command at specified intervals using Task Scheduler.

Run the command automatically Using Task Scheduler

  1. Launch Task Scheduler.
  2. In Task Scheduler, click “Task Scheduler Library”
  3. Click “Create task” link on the right pane.
  4. In the “Create Task” dialog, select the “General” tab.
  5. Mention the name of the task, say “Delete older files in My Documents”
  6. Click on the Triggers tab, and click New.
  7. Select “On a schedule” in the drop-down list under “Begin the task” dropdown list box.
  8. You may choose to run the task daily, weekly or monthly. If you choose weekly, select the day(s) of the week when you want the task to trigger.
  9. Once done, click the OK button.
  10. Click the “Actions” tab, and click the “New…” button.
  11. In the “New Action” window, fill in the following:
    Action: Start a program
    Program/script: C:\Windows\System32\ForFiles.exe
    Add arguments (optional): /p "%userprofile%\Documents" /s /d -30 /c "cmd /c del @file"

    delete files older than x days in windows task scheduler

  12. Click OK.

A new task is created which when run, deletes files in your Documents folder that haven’t been modified in the last 30 days.


Method 3: Delete files older than N days using Script

The Spiceworks forum users have VBScripts that can delete files older than N number of days on a specified folder path recursively. Here is a simple script:

On Error Resume Next

Set oFileSys = WScript.CreateObject("Scripting.FileSystemObject")
sRoot = "C:\Path To Old Files"			'Path root to look for files
today = Date
nMaxFileAge = 3					'Files older than this (in days) will be deleted

DeleteFiles(sRoot)

Function DeleteFiles(ByVal sFolder)

	Set oFolder = oFileSys.GetFolder(sFolder)
	Set aFiles = oFolder.Files
	Set aSubFolders = oFolder.SubFolders

	For Each file in aFiles
		dFileCreated = FormatDateTime(file.DateCreated, "2")
		If DateDiff("d", dFileCreated, today) > nMaxFileAge Then
			file.Delete(True)
		End If
	Next

	For Each folder in aSubFolders
		DeleteFiles(folder.Path)
	Next

End Function

Source: Delete Old Files and Empty Subfolders – Script Center – Spiceworks



IMPORTANT!The above script takes into consideration the “Date Created” property of items instead of “Date Last Modified”. If you want to delete files that haven’t been modified in the last N days, change the following line in the script:

dFileCreated = FormatDateTime(file.DateCreated, "2")

to

dFileCreated = FormatDateTime(file.DateLastModified, "2")

It clears files older than 3 days. All you need to do is modify the folder path & max file age parameters as required in the script, save it with a .vbs extension and run it. Note that the script works on the specified folder and sub-folders recursively.

Here is another script that deletes files older than N days, and automatically clears empty sub-folders recursively. See Delete files older than max age (in days) – Script Center – Spiceworks

RELATED: How to Find and Delete Empty Folders Quickly in Windows


Method 4: Delete files older than ‘n’ days Using PowerShell

The third option is to use PowerShell, which has a useful cmdlet to find and delete old files.

Start PowerShell (powershell.exe), and type the following command:

Get-ChildItem -Path [folder_path] -File -Recurse -Force | Where-Object {($_.LastWriteTime -lt (Get-Date).AddDays(-30))}| Remove-Item  -Force

Example:

Get-ChildItem -Path "D:\Reports" -File -Recurse -Force | Where-Object {($_.LastWriteTime -lt (Get-Date).AddDays(-30))}| Remove-Item  -Force

To use paths containing environment variable like %userprofile%\documents, use the syntax below:

Get-ChildItem -Path "$env:userprofile\documents" -File -Recurse -Force | Where-Object {($_.LastWriteTime -lt (Get-Date).AddDays(-30))}| Remove-Item -Force

(Note: The folder name in the example is your user profile’s Documents folder. Change the folder name and path accordingly as per your needs.)

Since we used the -File parameter, it works only for files. So, sub-folders which haven’t been written in the last n days are prevented from being deleted.

The above command has three parts:

  1. The Get-ChildItem cmdlet gets the list of files in your Documents folder.
  2. Then the output is piped to Where-Object cmdlet so that filtration is done, selecting only files that haven’t been modified in the last x number of days (in this example, 30 days).
  3. Finally, we’re piping the output to the Remove-Item cmdlet, which in turn deletes those older files returned by the previous two cmdlets.

Tip 1: List matching files, don’t delete them?

To list the matching files and folders without deleting them, drop the | Remove-Item switch.

Get-ChildItem -Path [folder_path] -File -Recurse -Force | Where-Object {($_.LastWriteTime -lt (Get-Date).AddDays(-30))}

Tip 2: Suppress errors when deleting items

To suppress error messages (when accessing or deleting items) from displaying in the console, add the -ErrorAction SilentlyContinue parameter.

Get-ChildItem -Path [folder_path] -File -Recurse -Force | Where-Object {($_.LastWriteTime -lt (Get-Date).AddDays(-30))} | Remove-Item -ErrorAction SilentlyContinue -Force

Delete old files as well as folders

Note that the above commands delete only the old files but not the sub-folders that haven’t been written in the last x days. To remove old folders, drop the -File argument in the from the previously explained commands.

Example:

Get-ChildItem -Path "$env:userprofile\documents" -Recurse -Force | Where-Object {($_.LastWriteTime -lt (Get-Date).AddDays(-30))}| Remove-Item -Force

(Refer: Get-ChildItem cmdlet documentation at Microsoft site)

Important: The -Recurse parameter directs PowerShell to get files recursively (in sub-directories). To prevent searching for files in subfolders, remove the -Recurse option so that only the current folder is processed.


One small request: If you liked this post, please share this?

One "tiny" share from you would seriously help a lot with the growth of this blog. Some great suggestions:
  • Pin it!
  • Share it to your favorite blog + Facebook, Reddit
  • Tweet it!
So thank you so much for your support. It won't take more than 10 seconds of your time. The share buttons are right below. :)

Ramesh Srinivasan is passionate about Microsoft technologies and he has been a consecutive ten-time recipient of the Microsoft Most Valuable Professional award in the Windows Shell/Desktop Experience category, from 2003 to 2012. He loves to troubleshoot and write about Windows. Ramesh founded Winhelponline.com in 2005.

6 thoughts on “How to Delete Files Older than N Days Automatically in Windows”

  1. Hello Ramesh,

    The powershell script works wonderfully. I do have a question though. How can I alter the script to not delete any folders, just the files within ? I need to keep my folder structure, no matter what the date, and only remove files older than X days.

    Thank you for considering my question

    Jeff Wilson

    Reply
  2. Hi, we made this script but forfiles don’t work, any ideas?

    NET USE \\coresrv2019\\Software /u:coresrv2019\username *pasword*
    ForFiles /p “\\coresrv2019\Software\BackupBBDDERP” /s /d -04 /c “cmd /c del @path”
    robocopy “E:\Backups\erp” “\\coresrv2019\Software\BackupBBDDERP” /e /maxage:3
    NET USE \\coresrv\Software /D

    We use @path and @file but same result.

    Reply
  3. Just wondering, is a script for deleting the last saved file? My son is into creating youtube videos of games, when whe comes say 2nd or third in fortnite, id like him to push a button on the stream deck to delete that file and retain space… at the moment after a couple of days there is 80GB of useless data on the SSD.

    Reply

Leave a Reply