Delete Files Older Than Date Using Batch Files


This problem has nagged at me for years.  Here is a batch command to delete files on a Windows 2003 machine.

Forfiles -pC:\backup -s -m*.* -d-5 -c "cmd /c del /q @path"

This will delete all files in my backup directory older than 5 days. To test it first, use this:

Forfiles -pC:\backup -s -m*.* -d-5 -c "cmd /C Echo 0x22@Path\@File0x22"

This will print out each file that you will be deleting.

Now playing: Lamb Of GodTerror And Hubris In The House Of Frank Pollard

,

47 responses to “Delete Files Older Than Date Using Batch Files”

  1. Thanks for that. Forfiles FTW!

    Just what I needed to clean up a load of cookies folders without wiping them out entirely. A nice little command.

  2. Very useful; forfiles.

    However, shouldn’t the first line read:

    forfiles -pC:\backup -s -m*.* -d-5 -c “cmd /c del /q @PATH\@FILE”

    …or all files would be deleted in the @PATH not the list of files over 5 days old such as @PATH/@FILE would result in?

    Try this:
    forfiles -pC:\backup -s -m*.* -d-5 -c “cmd /c echo del /q @PATH”

    …echos a list of delete commands with the same (duplicate) path string (with no filename) for each file found in the directory over 5 days old) that was older than 5 days.

    You Get This (duplicate directory only names, not desired):
    del -q c:\backup\db2\
    del -q c:\backup\db2\
    del -q c:\backup\mssql\
    del -q c:\backup\mssql\
    del -q c:\backup\mssql\
    del -q c:\backup\oracle\
    del -q c:\backup\oracle\

    NOTE: these (above) del commands would delete all files in these directories, not just the one over 5 days old

    VS. this:
    forfiles -pC:\backup -s -m*.* -d-5 -c “cmd /c echo del /q @PATH/@FILE”

    You get This (desired):
    del -q c:\backup\db2\file_01.zip
    del -q c:\backup\db2\file_02.zip
    del -q c:\backup\mssql\file_51.zip
    del -q c:\backup\mssql\file_52.zip
    del -q c:\backup\mssql\file_53.zip
    del -q c:\backup\oracle\file_71.zip
    del -q c:\backup\oracle\file_72.zip

    NOTE: these (above, desired) del commands would the specifc files that are over 5 days old

    Or am I missing something?

    Also, the version of forfiles that I got requires @PATH, @FILE, etc. to be ALL uppercase (maybe my version?).

    BTW.. thank you for turning me on to forfiles. 🙂 does the job and is more strait forward than find|xargs.

    –marc

  3. Not sure what version of forfiles you have – but my Windows 2000 version worked as I wrote it. Maybe yours was Windows 2003?

  4. maybe… below is the help screen fro the forfiles that I am using. It clearly shows @FILE and @PATH as 2 distinct variables. The all-uppercase requirement is not so clear but verified during testing. I just brought it up because the delete example forfiles syntax did not match your test case example forfiles syntax (i.e. @PATH only vs. @PATH/@FILE) and I did not want anyone to delete more than they bargained for.

    File Stats:
    -rwxrwxrwx 1 user group 12048 Sep 3 00:28 forfiles.exe

    Help Screen:
    FORFILES v 1.1 – emmanubo@microsoft.com – 4/98

    Syntax : FORFILES [-pPath] [-mSearch Mask] [-ccommand] [-d] [-s]

    -pPath Path where to start searching
    -mSearch Mask Search files according to
    -cCommand Command to execute on each file(s)
    -d Select files with date >= or = or <= (current date – DD days)
    -s Recurse directories
    -v Verbose mode

    The following variables can be used in Command :
    @FILE, @FNAME_WITHOUT_EXT, @EXT, @PATH, @RELPATH, @ISDIR, @FSIZE, @FDATE,
    @FTIME

    To include special hexa characters in the command line : use 0xHH

    Default :
    Examples :
    FORFILES -pc:\ -s -m*.BAT -c”CMD /C Echo @FILE is a batch file”
    FORFILES -pc:\ -s -m*.* -c”CMD /C if @ISDIR==TRUE echo @FILE is a directory”
    FORFILES -pc:\ -s -m*.* -d-100 -c”CMD /C Echo @FILE : date >= 100 days”
    FORFILES -pc:\ -s -m*.* -d-01011993 -c”CMD /C Echo @FILE is quite old!”
    FORFILES -pc:\ -s -m*.* -c”CMD /c echo extension of @FILE is 0x22@EXT0x22″

    Thanks again.
    –marc

  5. Hey Scott,

    thanks for the information. I was also searching for this. Got a couple of backup things that need special care. So this commandline tool came in handy.

    regards from holland

    Henk

  6. Hey, I did this command but it doesn’t actually delete the file. It just outputs the command to delete the file. I am a little confused on how to actually delete the file?

    forfiles /p c:\test -s -m *.* -d -07 -c “cmd /c echo del /q @path@file”

    Then it just displays

    del /q “c:\test\filename.doc”

    But it doesn’t delete the filename

  7. Works great and just what I needed, but as with marc above,my forfiles (on Win2003 Server) did not work correctly with your syntax. Had to add spaces in some places and change the delete syntax to *.??? to get mine to work correctly.

    One thing to consider..with this batch, if no ‘new’ backup is done within five days from the date on your computer, all your backups get deleted. Not a problem most of the time, but say your accounting software is backed up manually…and the right people are out sick for a week…just food for thought. Some might want to allow for a longer time span (say 15 days) to make certain that the last backup is never deleted. If it happens anyway, check out r-undelete. You can google it. Thanks again from Texas.

  8. Thanks for this.
    One thing I noticed is that it does not exclude the subfolders even with a command of:
    forfiles -pC:\folder\ -m*.* -d-5 -c”cmd /c echo del /q @PATH/@FILE”

    In other words, if you have a subfolder of
    “C:\folder\my_folder” then the “my_folder” WILL be deleted as well….so what is the point of “-s” parameter?
    Thanks!

  9. Thank you, this batch file is brilliant. I’ve been playing with DOS scripting for years and never came across the ForFiles cmd. WEIRD! Thanks, this is a great article!

    -Ted

  10. I have the same results as BigPimpin. It successfully echoes back the DEL commands for each file, but does not actually delete the file. Any ideas about this ? I am logged in as domain admin and testing interactively. I have not scripted and scheduled this yet.

    forfiles /p D:\Backups\ /S /M *.bak /D -1 /C “cmd
    /c echo del /q @PATH”

  11. Per http://winhlp.com/node/180, I downloaded a differnet version of forfiles that uses Unix switches with a dash (-), instead of Windows switches with a slash (/).

    I’m still getting the same results where it display the delete command, but does not actually delete any files. hhmmm…

  12. Great work Scott. A little tweaking and I was able to fit it right into a batch file I am using for file rotation.

  13. I have the same result, del command shows just fine, but it does not delete the files. What’s going on?

  14. The correct syntax under win 2003 should be:

    Forfiles /p C:\backup /s /m *.* /d- 5 /c “cmd /c del /q @path”

  15. Here is what I get when trying the command above, do you have any idea what it is saying and how i could correct this

    C:\Documents and Settings\Administrator>Forfiles /p C:\test3 /s /m *.* /D -5 /c
    “cmd /c del /q @path”
    ERROR: Invalid syntax. ‘/c’ option is not allowed more than ‘1’ time(s).
    Type “FORFILES /?” for usage.

  16. To answer pingram’s last post…and if anyone else is looking. I found the answer to that error and tweaked the command until it worked for me.

    First….

    If you copy this line, you will need to put it into Notepad first delete and re-type the quotation marks. This is what caused that “Invalid syntax” error that pingram had.

    Second…I am using Windows Server 2003 and needed to delete any files older than today’s date from a certain folder. Here’s what finally worked for me:

    forfiles /P C:\temp\DELtest /S /M *.* /D -2 /C “cmd /C del /q @FILE”

    Good luck!

  17. WINDOWS XP USERS:

    FORFILES -pc:\backup -s -m*.* -d-100 -c”CMD /c del @FILE”

    This does work – IMPORTANT NOTE –

    Make sure there are no spaces in your file names.

    If you have something like “ABC Statistic.XLS” you may either get “Could not find ABC” or you will get the list stating the file is being deleted, but, it never does.

    Try using underscores or dashes instead of spaces. Then it should work.

  18. Very excellent. I fiddled around with this myself. I had trouble because my path included space and like most Microsoft command line programs, forfiles doesn’t handle spaces for crap. Had to resort to the 8.3 scheme. So on Server 2003, my command looked like this:

    forfiles -pD:\Micros~1\MSSQL.1\MSSQL\Backup\ -s -m*.bak -d-3 -c “cmd /c del /q @PATH”

    Where D:\Micros~1\ = D:\Microsoft SQL Server\. Were I to put that in quotes, it would work with about half of the commands in cmd/powershell, but not the other half. forfiles appears to be part of the other half.

  19. That works!

    I had to resort to underscores because we had other files with the same prefix that had to be in the folder longer than 100 days.

  20. FTP download same name files of specific date
    I have to write a batch script which download file from ftp server(unix environment) which contain several same name

    file with different modified date. Batch file should take two parameters file name and last modified date.that

    script go to server and match file name according to its lastmodified date and download it to windows environment .
    Problen is that when i use mget command it does not filter with date.besause there is several same nane file..
    ex– abc_pqr 12/29/2010
    abc_pqr 12/24/2010
    abc_pqr 12/25/2010
    I want a perticular file from ftp server of abc_pqr 12/24/2010 date. Please help

  21. You can still try using any of the above commands, but, you might need more than one in your batch file.

    Using this as an example:
    FORFILES -pc:\backup -s -m*.* -d-100 -c”CMD /c del @FILE”

    In the part where there is ” -m*.* “, you can try ” -m*ex-abc*.* ”
    see if that works.

    I haven’t tried putting more than one command in a line, otherwise it would be something like:

    FORFILES -pc:\backup -s -m*ex-abc*.* -m*abc_pqr*.* -d-100 -c”CMD /c del @FILE”

    If this doesn’t work you might have to create a seperate line for each file.

    A lot of times with VB it’s trial and error based on different operating systems, etc.

  22. Didn’t know about forfiles either…
    It’s a very welcome addition to my admin toolkit.

    Regarding this command line, spawning a new cmd.exe on each file delete sounds like overkill.
    I’d rather type:

    for /f %a in (‘forfiles /p C:\backup /s /d -5’) do del %a

  23. After several attempts, I noticed that the command switches may need to be in upper case. (The command failed out right for me until I made this change.)

  24. I’m having issues trying to delete files with no extension. The ForFiles batch file seems to skip if I just do *.*. I tried specifing a file typ and got rid of the /M switch and then I get prompted if I’m sure I want to delete wit a Yes/No. having to input Yes/No invalidates the batch process. How can I modify this to delete files with no extension?

  25. Previous comment says no spaces, in these cases using quotes fixing that issue.

    FORFILES /P “C:\TEST\TEST\TEST” /M *.dat /D -5 /C “cmd /c del /q @PATH”

    For those of you from other languages might like this batch function method. Basically you do a call to the label %1 is first argument. You don’t leave the batch file… Fun Trick.

    CALL:DELETE “C:\test”

    GOTO:EOF

    :DELETE

    DEL /q %1

    GOTO:EOF

  26. I had the same problem but I get it resolved once I removed the “echo” word from the command line. It should work nicely.

  27. Forfiles -pC:\backup -s -m*.* -d-5 -c “cmd /c del /q @path”

    Worked great for me. Saved my life! Thanks a ton.

  28. This worked for me Win 2003 Server:

    REM displays all the files older than 180 days from the X:\exene folder
    FORFILES /P X:\exene /M *.xml /S /D -180 /C “cmd /c echo @file”

    REM deletes all the files older than 180 days from the X:\exene folder
    FORFILES /P X:\exene /M *.xml /S /D -180 /C “cmd /c del @file”

  29. I use FileDestroyer
    http://sourceforge.net/projects/filedestroyer/

    Here is a short tutorial:

    http://arturito.net/2010/07/13/file-destroyer-clean-upfree-up-disk-space-and-deleting-files-or-folders-after-a-certain-period-of-time/

    Usage:

    FileDestroyer.exe -scan “D:\SQLBackup” -ext bak -log “D:\Logs\” –days 2

    This command scans folder “D:\SQLBackup” looks for extension .bak and removes backups/files older than 2 days and it logs everything in D:\Logs\

    It also supports UNC Paths (\\server1\shared\backups\)

    (Disclaimer: I’m the author of this utility)

  30. Thanks Scott. This is exactly what I needed to delete old bak files off of my blackboard database server. I tweaked this just a little and it works great on Win2k8 as well.
    Forfiles /p B:\bb_bb60 /s /m *.* /d -5 /c “cmd /c del /q @path”

  31. This was an EXCELLENT script, and the discussion afterward about versions and switches helped me adapt it to my environment. Thank you for your work.

Leave a Reply

Your email address will not be published. Required fields are marked *