Howto: automatically remove files older than ‘x’ days

Tape backups have failed me too many times, so I now do my Windows backup to an external hard drive. One of the office staff is in charge of swapping out our backup drives and taking it offsite. I needed a solution that would remove old backups without user intervention so they wouldn’t have to worry about having enough space available for the backup to complete.

My hard drives can hold four backups, so here’s a very simple .vbs script that deletes files from I:\Backup Files that are more than three days old:

Dim Fso

Dim Directory

Dim Modified

Dim Files

Set Fso = CreateObject(“Scripting.FileSystemObject”)

Set Directory = Fso.GetFolder(“I:\Backup Files”)

Set Files = Directory.Files

For Each Modified in Files

If DateDiff(“D”, Modified.DateLastModified, Now) > 3 Then Modified.Delete

Next

Save this as filename.vbs

To execute this file, run:

cscript.exe filename.vbs

Thanks to Don for the original script I modified for my particular needs.

[updated 12-07-2007]

I just added another script that automatically removes files older than ‘x’ days which uses the forfiles command that is native to Windows.

[updated 01-01-2008]

Here’s another simple script from KWSupport.

[updated 01-02-2008]

This script from the Scripting Guy deletes files ‘X’ number of hours old. Looks like it could be modified easily to meet your needs.

42 thoughts on “Howto: automatically remove files older than ‘x’ days”

  1. I get the following error when I run the script:

    filename.vbs(6, 24) Microsoft VBScript compilation error: Invalid character

    Can you help with this? Thank you!

  2. Did you paste the script into a text editor like Notepad? If you paste into a word processor like MS Word, the program will write all sorts of funny characters that cannot be complied.

    Let me know if you want me to email you a copy.

    Julie

  3. Thank you, Julie, for responding so quickly!!

    I copied the script into notepad and saved it in “c” as filename.vbs:
    ~~~~~~~~~~~~~~~~~
    Dim Fso

    Dim Directory

    Dim Modified

    Dim Files

    Set Fso = CreateObject(”Scripting.FileSystemObject”)

    Set Directory = Fso.GetFolder(”E:\Backups”)

    Set Files = Directory.Files

    For Each Modified in Files

    If DateDiff(”D”, Modified.DateLastModified, Now) > 3 Then Modified.Delete

    Next
    ~~~~~~~~~~~~~~~~~

    I’m sure it’s user error–I don’t know much about scripting. I really appreciate your help.

    I’m trying to run this on a server running Windows Server 2003 Standard SP2

  4. Hi Debbie,

    I suspect the problem is the following line:

    Set Directory = Fso.GetFolder(”E:\Backups”)

    Does this folder (E:\Backups) already exist? If not, you’ll need to create it beforehand.

    When you receive the error, do you get a code, such as 800A0408? Maybe a line number/character position indicator?

    Julie

  5. Thanks so much again Julie. E:\Backups does exist and has about 7 days worth of backups in it.

    I just noticed that if I double-click the filename.vbs file I get a Windows Script Host error window:

    Script: c:\filename.vbs
    Line: 9
    Char: 24
    Error: Invalid character
    Code: 800A0408
    Source: Microsoft VBScript compilation error

    I apologize for not providing this info in my previous post. When I ran the script using cscript.exe this info was not provided.

  6. That is very helpful. After reading about the error (thank you for the link) and looking at the code I pasted, the quotation mark is not the correct ASCI character. I will correct it and try again. thank you for your help!

  7. Is there a way to modify the script which will search all folder (and its subfolders) in c:\filestorage and move them to a folder called “Archive”?

    Thanks,
    D

  8. When copying and pasting code from the Internet, often the double quotation mark changes to some weird code.

    Usually if you just delete the ” mark and re-type it in notepad with your own ” character, and save the file – it will then work.

  9. In case anyone is reading this. I figured it out. Our path is a UNC, but if you name the root of the path you want to parse through, you will be able to delete 4 day old stuff from subs as well.

    Dim Fso
    Dim Directory
    Dim Modified
    Dim Files

    Set Fso = CreateObject(“Scripting.FileSystemObject”)

    ListFolderContents(“\\rungus\Backup\Gateway\MSSQLBackups”)

    Sub ListFolderContents(path)
    Set fs = CreateObject(“Scripting.FileSystemObject”)
    Set folder = fs.GetFolder(path)
    For each item in folder.SubFolders
    DeleteFiles(item.Path)
    Next
    Set folder = Nothing
    set fs = Nothing
    End Sub

    Sub DeleteFiles(Dir)
    Set Directory = Fso.GetFolder(Dir)
    Set Files = Directory.Files
    For Each Modified In Files
    If DateDiff(“D”, Modified.DateLastModified, Now) > 3 Then Modified.Delete
    Next
    End Sub

  10. thankx mike c. the script is work! (subfolder)
    but the script only can run for 1st level subfolder.
    how about 2nd, 3rd level and so on of subfoder files ?
    can any one please help me to solve?

  11. This script works great. But I am also curious if the script can delete files in subfolders within subfolders…and possibly delete the empty folders as well. If this is not possible, I will still be very happy as-is. Thanks again!

  12. Hello again…
    I am getting closer. I added in a script to delete empty folders:

    If Directory.size <= 0 Then
    Directory.delete
    End if

    Now I just need to alter the script to include only empty folders after x days.

  13. Thanks for this script. It’s exactly what I was looking for.
    I haven’t tried this myself, but if you want to recurse through all subfolders, maybe you could just call ListFolderContents(path & “\” & Directory) inside the DeleteFiles subroutine.

  14. can you just help me out in deleting old files in a folder and the path is retrive from the “app.config” file and the files which are older of 90 days.
    i want that one in windows services in c#.

  15. What you have to do is copy and paste on notepad after that erase all the ” and wtirite them again.

    Change the Folder accordig to your needs and save as *.vbs

  16. I have what seems like a simple task. But being VERY new to scripting it has been VERY challenging. I want to take the previous days log file from a webserver and move the file to another server. The key is the previous days file not the current file. HELP PLEASE…… Also do not want to use any 3rd party software, has to be done in DOS batch file or vb script.

    Thanks

  17. Chuck –

    Is the previous day’s log file the only one it that directory? If so, its easy. But if you need to select a particular file to move based on the previous day’s date, that will be more challenging.

    Let me know, and you may want to look around at Rob’s Scripting Site – http://www.robvanderwoude.com/

    – Julie

  18. If you are interested in listing folders within folders with folders or recursion then microsoft made a handy page,

    I’ll probably come back later and post a modified script.

  19. Found this script and combined it with the recursive directory listing to delete files in sub directories but the the folders.(what i needed it to do) just wanted to return the favor :)

    Const FOR_READING = 1
    strFolder = “d:\test\”
    Set objFSO = CreateObject(“Scripting.FileSystemObject”)
    Set objFolder = objFSO.GetFolder(strFolder)
    Set colFiles = objFolder.Files
    For Each objFile In colFiles
    If DateDiff(“D”, objFile.DateLastModified, Now) > 90 Then objFile.Delete
    Next

    ShowSubFolders(objFolder)

    Sub ShowSubFolders(objFolder)
    Set colFolders = objFolder.SubFolders
    For Each objSubFolder In colFolders
    Set colFiles = objSubFolder.Files
    For Each objFile In colFiles
    If DateDiff(“D”, objFile.DateLastModified, Now) > 90 Then objFile.Delete
    Next
    ShowSubFolders(objSubFolder)
    Next
    End Sub

  20. I have FTP directory in which are users folders and every user have folder PDFOut.
    Example:
    F:\FTP\User1\ – never delete
    F:\FTP\User1\PDFOut\ – never delete
    F:\FTP\User1\Folder14DaysOld\ – do not delete
    F:\FTP\User1\Folder16DaysOld\ – delete
    F:\FTP\User1\Files14DaysOld.* – do not delete
    F:\FTP\User1\Files16DaysOld.* – delete

    I want delete all files and folders within user folders older than 15 days, except PDFOut folders even if it was not used 15 days. And also I do not want delete User* folders .

    I think about create some “system” files in important folders and use Aaron code:
    If Directory.size <= 0 Then
    Directory.delete
    End if

    But may be can be added some “exclusions code” to Smartpatrol (May 7, 2008 at 5:26 pm) script?

  21. A revised version of the recursive script.

    option explicit

    Dim strStartFolder
    Dim iExpiredAge
    dim objFSO, objStartFolder

    strStartFolder=”c:\testdelete\”
    iExpiredAge=90

    Set objFSO = CreateObject(“Scripting.FileSystemObject”)
    Set objStartFolder = objFSO.GetFolder(strStartFolder)

    call DeleteFromFolder(objStartFolder,iExpiredAge)

    Sub DeleteFromFolder(objFolder,iAge)

    dim colFolders, colFiles
    dim objSubFolder, objFile

    Set colFolders = objFolder.SubFolders
    For Each objSubFolder In colFolders
    Call DeleteFromFolder(objSubFolder,iAge)
    Next

    Set colFiles = objFolder.Files
    For Each objFile In colFiles
    If DateDiff(“D”, objFile.DateLastModified, Now) > iAge Then objFile.Delete
    Next

    End Sub

  22. Hi friends,
    In reply to very first script. there is
    its just to replace ” everywhere. After u copy this text. u can just manually replace ” in notepad. bec its just ascii characters gets changed. It will work

    Dim Fso

    Dim Directory

    Dim Modified

    Dim Files

    Set Fso = CreateObject(“Scripting.FileSystemObject”)

    Set Directory = Fso.GetFolder(“I:\Backup Files”)

    Set Files = Directory.Files

    For Each Modified in Files

    If DateDiff(“D”, Modified.DateLastModified, Now) > 3 Then Modified.Delete

    Next

    Thanx
    Priyesh

  23. Here is an alternate script that may possibly reduce the lines of code, and also, possibly, provide more control.

    # Script DeleteOld.txt
    var str folder, diff, list, file
    lf -r -n “*” $folder (($ftype==”f”) AND ($fmtime $list
    while ($list “”)
    do
    lex “1” $list > $file
    # system del (“\””+$file+”\””)
    echo -e “DEBUG: Deleted file ” $file
    done

    Script is in biterscripting ( http://www.biterscripting.com ). Copy and paste the script code into file “C:/Scripts/DeleteOld.txt”. Call it as follows.

    script “C:/Scripts/DeleteOld.txt” folder(“C:/Testing”) diff(“30000000″)

    The above script call will delete files older (modified earlier) than 30 days, 00 hrs, 00 mins, 00 sec from folder “C:/Testing” and all its subfolders (and sub-sub folders).

    script “C:/Scripts/DeleteOld.txt” folder(“C:/Testing”) diff(“240000″)

    will delete files older (modified earlier) than 24 hrs.

    script “C:/Scripts/DeleteOld.txt” folder(“C:/Testing”) diff(“3000″)

    will delete files older (modified earlier) than 30 mins and 00 seconds.

    script “C:/Scripts/DeleteOld.txt” folder(“C:/Testing”) diff(“0″)

    will delete files older (modified earlier) than 0 seconds – that is it will delete all the files. This is same as not specifying the diff() argument at all.

    etc.

    Test the script first in a test folder until you understand how it works. I have commented out (#) the system del command that actually deletes the files. Once you understand the script, you can uncomment that command.

  24. Hi Friends,

    I am using below query to delete files,

    Dim Fso

    Dim Directory

    Dim Modified

    Dim Files

    Set Fso = CreateObject(“Scripting.FileSystemObject”)

    Set Directory = Fso.GetFolder(“D:\”)

    Set Files = Directory.Files

    For Each Modified in Files

    If DateDiff(“D”, Modified.DateLastModified, Now) > 1 Then Modified.Delete

    Next

    i received below error when i executed above query please can anyone help me.

    D:\delold.vbs(9, 24) Microsoft VBScript compilation error: Invalid character

  25. Search “RoboBasket” in google you will find a software which can automatically process your files based on user predefined rules. You can process your files based on name, size, date, mp3 tag, extension and more other attributes. and choose actions from move, copy, rename, delete and more. You can create rules with just drag&drop, no programming or script skills needed.

  26. Hello,

    i have a weird issue with this script.
    it doesn’t delete the files…
    i adjusted it a little bit, and when i do a wscript.echo i see it checks all the files, and when i do some other wscript echo’s i also see that the datediff for example gives a value 63 and my number of days is 60, so when i do a 63 > 60… it says it isn’t..
    veryy strange.
    Does anyone see the problem?

    Option Explicit
    ‘On Error Resume next

    ‘Variables
    Dim objStartFolder, objParameters, Datafiles, DataFolder
    Dim objAPI, fso, modified, verschil
    Dim NumberOfDays, oBag
    Dim StateDataType, strReturn

    ‘Set objAPI = CreateObject(“MOM.ScriptAPI”)

    Set objParameters = WScript.Arguments
    objStartFolder = objParameters(0) ‘The 0 indicates FolderName is the first argument
    NumberOfDays = objParameters(1) ‘The 1 indicates the amount of days

    Set fso = CreateObject(“Scripting.FileSystemObject”)

    Set DataFolder = fso.GetFolder(objStartFolder)
    Set DataFiles = DataFolder.Files
    For Each Modified in DataFiles
    verschil = DateDiff(“D”, Modified.DateLastModified, Now)
    If verschil > NumberOfDays Then
    wscript.echo “verwijderd : ” & Modified
    ‘Modified.Delete
    ‘else
    ‘wscript.echo verschil & “niet ouder dan 2 maanden : ” & Modified
    end if
    ‘wscript.echo verschil & ” : ” & NumberOfDays

    Next

Leave a Reply

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

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>