Windows Tip: How To Delete Files Older Than Certain Days in Command Line


Perhaps, the easiest way to delete files at a certain age is through a command line or a batched file or even a script. Yes, of course, you can still do so from the powerful File Explorer that comes with Windows but it certainly takes more steps than a simple command.

Command Prompt splash - Windows Tip: How To Delete Files Older Than Certain Days in Command Line

For example, if I need to search for a list of PDF files that are older than a year in my OneDrive, I can open Command Prompt and run the following command.

ForFiles /p "z:\OneDrive" /s /m *.PDF /d -365 /c "cmd /c echo @file"

in which,

  • /p to indicate the path to start the search.
  • /s to search all subfolders recursively.
  • /m to define the search mask for the specified files. In this case, use *.PDF to find all PDF files.
  • /d to select files with a last modified date. -365 simply means a year ago.
  • /c to indicate the command to execute each file found in the search. The command string needs to be wrapped up in double quotes. “cmd /c echo @file” is the default command if not specified. You can use other variables if needed, such as:
    • @path for the full path of the file.
    • @fsize for the size of the file.
    • @fdate and @ftime for the date and time of the file.

To delete the files found in the search, replace “echo” with “del” in the command.

ForFiles /p "z:\OneDrive" /s /m *.PDF /d -365 /c "cmd /c del @file"

If you need to do this frequently or on different computers, you can put it in a batch file so you can run it by double-clicking it.

You can also do the same with PowerShell if you prefer with the cmdlet Get-ChildItem and Where-Object.

Get-ChildItem "z:\OneDrive" -Recurse | Where-Object {($_.LastWriteTime -lt (Get-Date).AddDays(-365)) -and ($_.Extension -match "PDF")}

To remove the items found in above cmdlet, pipe the result to Remove-Item cmdlet.

Get-ChildItem "z:\OneDrive" -Recurse | Where-Object {($_.LastWriteTime -lt (Get-Date).AddDays(-365)) -and ($_.Extension -match "PDF")} | Remove-Item


  1. This isn’t working for me, I’ve looked at the /? options and can’t find the error. Can anyone help?

    c:\Windows>ForFiles /p “l:\New downloads\ Move to NEW Drive\PROCESSED\” /S /M *.zip /D -35 /C “cmd /C ECHO @file ”
    ERROR: Invalid argument/option – ‘@file’.
    Type “FORFILES /?” for usage.


Please enter your comment!
Please enter your name here