Link to home
Start Free TrialLog in
Avatar of slavetonone
slavetonone

asked on

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
            File.Delete
        End If
    Next
    
    For Each Folder In objSubFolders
        If Folder.DateLastModified < objPastDate Then
            On Error Resume Next
            objFSO.DeleteFolder Folder.Path, True
        Else
            recurse Folder
        End If
    Next
 
    Set objSubFolders = Nothing
    Set objFiles = Nothing
    
End Sub

Open in new window

ASKER CERTIFIED SOLUTION
Avatar of FemSteenkamp
FemSteenkamp
Flag of South Africa image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
try this

change line 7

to this

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

for 7 days old files
Avatar of slavetonone
slavetonone

ASKER

Is that a 1 (one) or l (L)?
SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
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.