VBScript to delete all files and folders in a directory

On a Windows 2003 Server I created a folder called "C:\Test" which I have another batch file that dumps temporary data too. I want to run a VBScript with my nightly scheduled tasks to go through and clear out folder AND files that are older then 7 days. I understand that some files/folders will be in use and cannot be deleted - which is fine but if thats the case, I want to make sure it will continue on to the next file/folder and not just terminate the script right then and there.

I found a script that does 90% of what I need, it loops though and recursively deletes files past x date, now how do I create another sub routine that executes after the recursive files one to take care of the directories past x date.

Everytime I run this script it deletes all folders and files in the specified directory no matter what I put.  I wanted to edit this for 7 days, so i changed the intDays*-1 (which is how I found the script) too intDays*-7 and it still deletes everything.  

Am I doing something wrong? What do I need to do to get this to run correctly?

Thanks you in advance for all your help!
strFolder = "D:\test"
intDays = 0
Set objFSO	= CreateObject("Scripting.FileSystemObject")
Set objFolders	= objFSO.GetFolder(strFolder)
objToday		= Now()
objPastDate	= DateAdd("d", intDays*-7, objToday)
Recurse objFolders
Sub recurse(ByRef objFolders)
    Set objSubFolders = objFolders.SubFolders
    Set objFiles = objFolders.Files
    For Each File In objFiles
        If File.DateLastModified < objPastDate Then
            On Error Resume Next
        End If
    For Each Folder In objSubFolders
        If Folder.DateLastModified < objPastDate Then
            On Error Resume Next
            objFSO.DeleteFolder Folder.Path, True
            recurse Folder
        End If
    Set objSubFolders = Nothing
    Set objFiles = Nothing
End Sub

Open in new window

Who is Participating?
FemSteenkampConnect With a Mentor Commented:
in line 2 change this to
IntDays = 7

change the 7 in line 7 back to a 1
try this

change line 7

to this

objPastDate      = DateAdd("d", intDays-7, objToday)

for 7 days old files
slavetononeAuthor Commented:
Is that a 1 (one) or l (L)?
RobSampsonConnect With a Mentor Commented:
Hi, change
intDays = 0

intDays = 7

and change
objPastDate      = DateAdd("d", intDays*-7, objToday)

objPastDate      = DateAdd("d", -intDays, objToday)

The asterisk should not be there....


Guy Hengel [angelIII / a3]Billing EngineerCommented:
This question has been classified as abandoned and is being closed as part of the Cleanup Program. See my comment at the end of the question for more details.
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.