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.

35 Responses to “Howto: automatically remove files older than ‘x’ days”

  1. Debbie Says:

    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. Julie Says:

    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. Debbie Says:

    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. Julie Says:

    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. Debbie Says:

    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. Julie Says:

    Open up your script in a text editor, and tell me which line is line 9. Then let me know which character is number 24 – put your cursor at the begining of the line, then hit your right arrow key 24 times.

    It’s hard for me to tell from your script that you pasted since this blog hosting services skews the formatting.

    You can read all about the 800a0408 error at http://www.computerperformance.co.uk/Logon/code/code_800A0408.htm

    Julie

  7. Debbie Says:

    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!

  8. Derek Says:

    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

  9. Julie Says:

    Derek –

    Scripting is definitely not my strong point, so I’d suggest using robocopy.exe – It’s easy, powerful, and free.

    http://www.microsoft.com/technet/technetmag/issues/2006/11/UtilitySpotlight/

    - Julie

  10. Andy Peaple Says:

    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.

  11. Mike C Says:

    Hey guys, I love this little script, but im trying to mod it to recurse sub dirs, anyone done this with it yet?

    mike C

    mcain@lbaop.org

  12. Mike C Says:

    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

  13. Julie Says:

    Thanks for posting your modifications Mike.

    - Julie

  14. MIKE Says:

    IT WORK GREAT MAN…THANX!!

  15. stacy Says:

    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?

  16. Aaron Says:

    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!

  17. Aaron Says:

    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.

  18. Andrew Says:

    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.

  19. kris Says:

    can you just help me out in deleting old files which are older of 1 year.
    i want that one in windows services in c#.

  20. Cahtar Says:

    can you just help me out in deleting old files which are older of 90.
    i want that one in windows services in c#.

  21. Cahtar Says:

    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#.

  22. @xel Says:

    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

  23. Shanthi Says:

    How do I delete files older than certain days with a specific extension.

  24. Chuck Says:

    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

  25. Julie Says:

    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

  26. Abe Spain Says:

    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.

  27. Abe Spain Says:

    Gee, what use are these comments if I cant paste a url?

  28. Smartpatrol Says:

    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

  29. supprimer un fichier automatiquement aprs 5 jours - Excel Downloads Forums Says:

    [...] automatiquement aprs 5 jours Bonjour En utilisant WSH* dans VBA Comme ici par exemple Howto: automatically remove files older than ‘x’ days the back room tech WSH: Windows Scripting Host __________________ Cordialement, __________________ JM Y ‘avait [...]

  30. Kamil Says:

    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?

  31. Cyber-D Says:

    Hi all,

    I think this is what you are looking for: http://cyber-d.blogspot.com/2005/10/cyber-ds-auto-delete-101.html

  32. tej Says:

    How do we delete files in subdirectory ?

  33. pjdiller Says:

    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

  34. Priyesh Gaikwad Says:

    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


Leave a Reply