Howto: automatically remove files older than ‘x’ days

by admin on June 12, 2007

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.

{ 40 comments… read them below or add one }

Debbie September 21, 2007 at 10:24 am

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!

Reply

Julie September 21, 2007 at 11:29 am

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

Reply

Debbie September 21, 2007 at 1:44 pm

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

Reply

Julie September 21, 2007 at 3:38 pm

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

Reply

Debbie September 21, 2007 at 4:33 pm

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.

Reply

Julie September 23, 2007 at 8:38 am

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

Reply

Debbie September 24, 2007 at 12:11 pm

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!

Reply

Derek September 27, 2007 at 8:38 pm

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

Reply

Julie September 28, 2007 at 3:17 pm

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

Reply

Andy Peaple October 18, 2007 at 8:00 am

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.

Reply

Mike C October 23, 2007 at 4:56 pm

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

Reply

Mike C October 23, 2007 at 6:06 pm

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

Reply

Julie October 24, 2007 at 12:56 pm

Thanks for posting your modifications Mike.

- Julie

Reply

MIKE October 24, 2007 at 4:45 pm

IT WORK GREAT MAN…THANX!!

Reply

stacy October 31, 2007 at 2:44 am

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?

Reply

Aaron November 6, 2007 at 8:21 pm

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!

Reply

Aaron November 6, 2007 at 8:36 pm

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.

Reply

Andrew November 21, 2007 at 2:52 pm

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.

Reply

kris December 4, 2007 at 9:53 am

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

Reply

Cahtar February 20, 2008 at 2:29 am

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

Reply

Cahtar February 20, 2008 at 3:43 am

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

Reply

@xel March 11, 2008 at 9:38 am

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

Reply

Shanthi March 17, 2008 at 1:23 pm

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

Reply

Chuck April 4, 2008 at 10:24 am

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

Reply

Julie April 4, 2008 at 2:43 pm

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

Reply

Abe Spain May 1, 2008 at 5:46 am

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.

Reply

Abe Spain May 1, 2008 at 5:48 am

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

Reply

Smartpatrol May 7, 2008 at 5:26 pm

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

Reply

Kamil August 4, 2008 at 7:53 am

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?

Reply

Cyber-D February 14, 2009 at 6:43 am

Hi all,

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

Reply

tej August 27, 2009 at 2:46 pm

How do we delete files in subdirectory ?

Reply

pjdiller October 20, 2009 at 3:21 pm

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

Reply

Priyesh Gaikwad November 18, 2009 at 3:45 am

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

Reply

RandiR January 19, 2010 at 12:29 pm

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.

Reply

RandiR January 19, 2010 at 12:31 pm

Excellent discussion is going on here. Glad to see some healthy discussion on batch files and scripts.

Reply

amar February 1, 2010 at 9:17 am

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

Reply

bd March 3, 2010 at 6:00 pm

Thanks for the original Script i am new to scripting, but this is a huge help!

Reply

Dan April 1, 2010 at 9:09 pm

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.

Reply

tom October 1, 2010 at 9:08 am

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

Reply

Claudia Camargo October 19, 2010 at 10:31 am

I really liked this script. Simple, quick and it worked.
Thanks a lot!

Reply

Leave a Comment

{ 2 trackbacks }

Previous post:

Next post: