Script to Delete Files Over 2 Days Old?

Posted on 2012-09-18
Last Modified: 2012-09-19
We have a SQL server with a maintenance plan that is set to remove backup data older than two days.

For whatever reason, the maintenance plan is not removing any of the previous backups and the disk space is filling to capacity with backup data.

Our DBA is busy working on priority issues and will not be able to address this maintenance plan issue any time soon.

As a temporary measure, I would like to create a script that would check the contents of a directory, look at the dates, and then delete everything older than two days.

Scripting is not a strong point of mine – I could really use some guidance on creating a BAT or VBS script that will check the dates of files within a directory and then delete everything older than two days.

Any help would be greatly appreciated.

Question by:acmi
    LVL 14

    Expert Comment

    Create a simple batch file with the following (change the folder and file extension as appropriate) and schedule it using task scheduler.

    Forfiles /P "C:\Folder\" /M "*.ext" /D -2 /C "cmd /c del @file"

    Type "Forfiles /?" at the command prompt for the full syntax.

    LVL 14

    Expert Comment

    If you want to test to see if you are selecting the correct files, just omit everything after -2 and it should list the files that are 2 days or older inside "C:\Folder" with the extension od .ext.

    Forfiles /P "C:\Folder\" /M "*.ext" /D -2
    LVL 43

    Expert Comment

    by:Steve Knight
    Only here briefly at the moment, but I have on example on a page of mine here:

    You can take that script as it is, paste it into notepad, Save As, choose "all files" so it doesn't add .TXT on the end, call it delolder.vbs say (or see the attached file on that page) then amend the line:

    DeleteFiles "c:\temp",DateAdd("m", -1, Date)


    DeleteFiles "c:\yourdir",DateAdd("d", -2, Date)

    That will run against "c:\yourdir" for anything over 2 days old.

    Please check against a copy of the files or a test dir (e.g. your temp drive) to make sure you are happy before running it live.

    You can run that by double clicking the VBS, or by scheduling it, or from commandline with:

    cscript //nologo delolder.vbs


    LVL 9

    Expert Comment

    LVL 51

    Expert Comment

    by:Bill Prew
    If you can use a small utility program for this heres a great simple way to solve this.  Take a look at DELAGE32 here:

    DelAge32 is a command line tool that deletes or moves files by age (number of days).
    The age is calculated as date difference (each date determined at local time). By default the "last modified" file stamp is taken to calculate the age (see options /created, /modified and the note about file stamps).
    Syntax: 	DelAge32 filespec days [options]
    Examples: 	DelAge32 "C:\some\where\*.*" 100 /recurse
    DelAge32 there\*.tmp 1 /created /includeRO
    Delage32 *.zip 35
    filespec 	File name search pattern (wildcards) with full or relative path.
    Quote marks recommended; required if path includes space or other special characters.
    days 	Number of days: minimum age of files to delete or move
    options 	Options begin with a slash, case ignored.
    All command arguments must be separated by blank space!
    /preview 	The files will not be deleted or moved, but only listed with age.
    /created 	The "created" time stamp is taken to calculate the age. Default is the "last modified" stamp. See note about file stamps (below)
    /modified 	The "last modified" time stamp is taken to calculate the age. This is the default. However, when used in conjunction with the /created option, the most recent one of these two stamps is taken.
    /accessed 	The "last access" time stamp is taken to calculate the age.
    /includeRO 	Include files with Read-Only attribute
    /includeH 	Include files with Hidden attribute
    /includeS 	Include files with System attribute
    /includeRHS 	= /includeRO /includeH /includeS
    /recurse 	Recurse through the entire subdirectory structure (see /rd option to remove empty directories)
    /subonly 	Recurse, but exclude the initial directory
    /rd 	Remove empty subdirectories regardless of age (initial directory will not be removed).
    Note: /preview will not make any /rd predictions.
    /move target 	Move files instead of deleting; specify target directory. This works across drives.
    Note: If a target file exists, it will be overwritten without warning!
    /quiet 	No output (makes no sense with the /preview option). By default all deleted or moved files are listed with age (number of days).
    The output can be redirected to a file (OEM format).
    In case of any syntax errors the program will take no action.
    Maximum length of fully expanded paths: 260 bytes.
    Errorlevels: 	0: successful, even if no files have qualified
    1: invalid path, 255: syntax error
    Failed operations: 	If there are any files that could not be deleted or moved, the output line will be marked with *** failed ***.
    Note about file stamps:
    Usually you would not expect that a file has been "modified" before it was "created".
    However, when a file is copied, for example, the new copy is "created" at the current date (obviously), whereas the "last modified" stamp is taken from the original file, because it is supposed to refer to the contents - not the physical file.
    Deleting folders:
    Delage32 deletes files, and optionally removes empty folders. Delage32 was not designed to delete directory structures depending on the age of the folder, regardless of the age of the files inside.
    Copyright, Disclaimer
    This program is distributed as "freeware," copyright reserved by the author. There are no warranties of any kind, nor any liability by the author. Users accept full responsibility for the use they make of the software and for any damage caused thereby.
    Email: horst.schaeffer at

    Open in new window

    LVL 14

    Expert Comment

    No offense fellow experts, but talk about a sledgehammer to crack a nut.

    What's wrong with using Forfiles.exe in a batch file?

    LVL 12

    Accepted Solution

    Here is a script that will do what you are wanting:
    LVL 1

    Expert Comment

    sfk select -before 2d -dir directoryname -file .extension +delete

    Author Comment

    First – thanks to everyone that has posted.  I was not expecting such a quick response.

    It will be close to 2 more hours before I can pull away to look at this business – will update the posting as soon as I can test successfully.

    Again, thank you all for your input.

    LVL 43

    Expert Comment

    by:Steve Knight
    Forfiles is 2008/Windows 7 (and Vista?) natively, don't think it was on 2003 but was available from the resource kits and has had various oddities over the years which is why I tend to script it though afaik later versions are good.

    You could also use robocopy too I suppose while we talk of built in tools in later OS versions - moves to a temporary dir

    md "d:\tempdir"
    ROBOCOPY "d:\backupdir" "D:\tempdir" /move /minage:2
    rd "D:\tempdir"  /s/q
    LVL 14

    Expert Comment

    Forfiles.exe is available in Server 2003 as standard, at least in the servers I manage. I have been using it to manage some unruly application logs on few servers for the past year or so.
    LVL 43

    Expert Comment

    by:Steve Knight
    Agreed, there... Forfiles on 2003 and 2003 R2 onwards, just not Windows XP / 2000 without adding on.

    Author Closing Comment

    Thank you to everyone that responded.  I went with the script by Symantec offered by Seaton007.  I’m sure there are other suggestions posted that may be just as good – but with little time to test all of the proposed solutions, the script from Symantec quickly fits the need.  - Thank you.

    Featured Post

    IT, Stop Being Called Into Every Meeting

    Highfive is so simple that setting up every meeting room takes just minutes and every employee will be able to start or join a call from any room with ease. Never be called into a meeting just to get it started again. This is how video conferencing should work!

    Join & Write a Comment

    Whether you’re a college noob or a soon-to-be pro, these tips are sure to help you in your journey to becoming a programming ninja and stand out from the crowd.
    If you’re thinking to yourself “That description sounds a lot like two people doing the work that one could accomplish,” you’re not alone.
    An introduction to basic programming syntax in Java by creating a simple program. Viewers can follow the tutorial as they create their first class in Java. Definitions and explanations about each element are given to help prepare viewers for future …
    In this seventh video of the Xpdf series, we discuss and demonstrate the PDFfonts utility, which lists all the fonts used in a PDF file. It does this via a command line interface, making it suitable for use in programs, scripts, batch files — any pl…

    745 members asked questions and received personalized solutions in the past 7 days.

    Join the community of 500,000 technology professionals and ask your questions.

    Join & Ask a Question

    Need Help in Real-Time?

    Connect with top rated Experts

    17 Experts available now in Live!

    Get 1:1 Help Now