VBScript to find files in a folder (and all subfolders) older than XX days and delete them

Hello EE experts,

I am looking for a simple VBscript which I will run on a scheduled basis.  

The purpose of this is to search a folder, for example, D:\Application and all it's subfolders for *.log files.  Any that are older than XX days should then be deleted.  I specify XX since I'm not sure how many days yet...

Also, could it be possible that I can specify an entire drive (and thereby all folders)?  I never know when/if the devs might change folder structure used by the application!  Perhaps this can be done by simply dropping the folder name and specifying D:\ for example?

Help greatly appreciated!
JamieD71Asked:
Who is Participating?
 
Bill PrewConnect With a Mentor Commented:
I had also changed that slightly after that original question, adding some error checking so that if the user running the script did not have access to a folder the script continues on.  I also moved a couple of the flags to the subroutine parms so that they could be changed per folder.

' Set processing mode flags
Const UseCreatedDate = "C"
Const UseModifiedDate = "M"
Const UseAccessedDate = "A"

' Create file system object
Set objFSO = WScript.CreateObject("Scripting.FileSystemObject")

' Remove old files and as needed
' Parms are: Base folder, days to keep files, file date to use for age check, process subfolders flag, remove empty folders flag
RemoveOldFiles objFSO.GetFolder("d:\", 30, UseCreatedDate, True, False)
RemoveOldFiles objFSO.GetFolder("e:\temp", 90, UseModifiedDate, True, False)
RemoveOldFiles objFSO.GetFolder("f:\", 30, UseCreatedDate, True, False)

Sub RemoveOldFiles(objFolder, intDays, strDateToUse, blnProcessSubFolders, blnRemoveEmptyFolders)
    On Error Resume Next

    ' Remove any files older than specified days from this folder
    For Each objFile In objFolder.Files
        
        ' Get the desired date for the age check        
        Select Case UCase(strDateToUse)
           Case "C"
              datFile = objFile.DateCreated
           Case "M"
              datFile = objFile.DateLastModified
           Case "A"
              datFile = objFile.DateLastAccessed
           Case Else
              datFile = objFile.DateLastModified
        End Select

        If DateDiff("d", datFile, Now) > intDays Then
            If objFile.name = "*.log" Then
                Wscript.Echo "Deleted file: " & objFile.Path
                objFile.Delete
            End If
        End If
    Next

    ' See if we were able to access this folder, if not don't recurse into it
    If Err.Number = 0 Then
        If blnProcessSubFolders Then
            ' Remove all older files in any subfolders of this one
            For Each objSubFolder In objFolder.Subfolders
                RemoveOldFiles objSubFolder, intDays
            Next
        End If

        If blnRemoveEmptyFolders Then
            ' If folder is now empty, remove it
            If objFolder.Files.Count = 0 And objFolder.Subfolders.Count = 0 Then
                Wscript.Echo "Deleted folder: " & objFolder.Path
                objFolder.Delete
            End If
        End If
    End If
End Sub

Open in new window

~bp
0
 
Rgonzo1971Connect With a Mentor Commented:
Hi,

pls try

Const strPath = "M:\"
Dim objFSO
Set objFSO = CreateObject("Scripting.FileSystemObject")
Call Search(strPath, 14)
WScript.Echo "Done."

Sub Search(str, NrDays)
    Dim objFolder, objSubFolder, objFile
    Set objFolder = objFSO.GetFolder(str)
    For Each objFile In objFolder.Files
        If objFile.DateCreated < (Now() - days) Then
            If objFile.Name Like "*.log" Then
                objFile.Delete (True)
            End If
        End If
    Next
    For Each objSubFolder In objFolder.SubFolders
        Search objSubFolder.Path, NrDays
    Next
End Sub

Open in new window

Regards
0
 
JamieD71Author Commented:
Hi Rgonzo1971,

Where in the script to I specify the age (in days) and the .log file extension?

Thanks!
0
Keep up with what's happening at Experts Exchange!

Sign up to receive Decoded, a new monthly digest with product updates, feature release info, continuing education opportunities, and more.

 
Rgonzo1971Commented:
Hi,

On line 4 Instead of 14 give numbers of days you want

On line 12 it is already specified
0
 
JamieD71Author Commented:
Sorry - thanks!  Will try it now!
0
 
MacroShadowConnect With a Mentor Commented:
Here is a script written by EE's billprew

On line 2 you determine if to process all sub-folders too.
On line 3 you determine if to remove empty folders.
On line 4 you determine which date you're dealing with.
On lines 10-12 you define: 1) the parent folder 2) the min. age of files to delete.

' Set processing mode flags
Const ProcessSubFolders = True
Const RemoveEmptyFolders = False
Const DateToUse = "C"    ' C=created, M=modified, A=accessed

' Create file system object
Set objFSO = WScript.CreateObject("Scripting.FileSystemObject")

' Remove old files as needed
RemoveOldFiles objFSO.GetFolder("d:\", 30)
RemoveOldFiles objFSO.GetFolder("e:\", 30)
RemoveOldFiles objFSO.GetFolder("f:\", 30)

Sub RemoveOldFiles(objFolder, intDays)
    ' Remove any files older than specified days from this folder
    For Each objFile In objFolder.Files
        
        ' Get the desired date for the age check        
        Select Case UCase(DateToUse)
           Case "C"
              datFile = objFile.DateCreated
           Case "M"
              datFile = objFile.DateLastModified
           Case "A"
              datFile = objFile.DateLastAccessed
           Case Else
              datFile = objFile.DateLastModified
        End Select

        If DateDiff("d", datFile, Now) > intDays Then
            If objFile.name = "*.log" Then
                Wscript.Echo "Deleted file: " & objFile.Path
                objFile.Delete
            End If
        End If
    Next

    If ProcessSubFolders Then
        ' Remove all older files in any subfolders of this one
        For Each objSubFolder In objFolder.Subfolders
            RemoveOldFiles objSubFolder, intDays
        Next
    End If

    If RemoveEmptyFolders Then
        ' If folder is now empty, remove it
        If objFolder.Files.Count = 0 And objFolder.Subfolders.Count = 0 Then
            Wscript.Echo "Deleted folder: " & objFolder.Path
            objFolder.Delete
        End If
    End If
End Sub

Open in new window

0
 
Bill PrewCommented:
Here is a script written by EE's billprew
Great to see that little script reused, and with a mention, thanks and glad it is useful.

Originally submitted for this question: http://www.experts-exchange.com/Programming/Languages/Visual_Basic/VB_Script/Q_27188057.html

~bp
0
 
JamieD71Author Commented:
billprew, thank you very much for this.  I am trying your amended script, but receive an error (screenshot attached).

I modified only one line in your text, but rem'd out the lines I didn't need, again shown in the screenshot.
Capture.JPG
0
 
Bill PrewCommented:
Sorry, looks like a bug in the original code.  Should be like this:

RemoveOldFiles objFSO.GetFolder("d:\"), 30, UseCreatedDate, True, False

~bp
0
 
JamieD71Author Commented:
Hi bp,

Thanks for the update.  I can now run the script with no errors, but no files are being deleted....

I've got local admin right to the server I am running it on...  And the files aren't marked as read only either.

If I go into a command prompt and then execute the vb script, I get the next prompt appearing instantly...

Any ideas?
0
 
Bill PrewCommented:
Can you post the code you ran please.

~bp
0
 
RobSampsonCommented:
Hi, you could comment out the On Error Resume Next line and run it again to see if you get any errors.  This might tell us something the script is not catching, and it could be amended to log the info.

Rob.
0
 
JamieD71Author Commented:
Hi bp

Here is the code:

' Set processing mode flags
Const UseCreatedDate = "C"
Const UseModifiedDate = "M"
Const UseAccessedDate = "A"

' Create file system object
Set objFSO = WScript.CreateObject("Scripting.FileSystemObject")

' Remove old files and as needed
' Parms are: Base folder, days to keep files, file date to use for age check, process subfolders flag, remove empty folders flag
' RemoveOldFiles objFSO.GetFolder("d:\"), 30, UseCreatedDate, True, False
' RemoveOldFiles objFSO.GetFolder("e:\temp"), 90, UseModifiedDate, True, False
RemoveOldFiles objFSO.GetFolder("d:\"), 30, UseModifiedDate, True, False

Sub RemoveOldFiles(objFolder, intDays, strDateToUse, blnProcessSubFolders, blnRemoveEmptyFolders)
    On Error Resume Next

    ' Remove any files older than specified days from this folder
    For Each objFile In objFolder.Files
        
        ' Get the desired date for the age check        
        Select Case UCase(strDateToUse)
           Case "C"
              datFile = objFile.DateCreated
           Case "M"
              datFile = objFile.DateLastModified
           Case "A"
              datFile = objFile.DateLastAccessed
           Case Else
              datFile = objFile.DateLastModified
        End Select

        If DateDiff("d", datFile, Now) > intDays Then
            If objFile.name = "*.log" Then
                Wscript.Echo "Deleted file: " & objFile.Path
                objFile.Delete
            End If
        End If
    Next

    ' See if we were able to access this folder, if not don't recurse into it
    If Err.Number = 0 Then
        If blnProcessSubFolders Then
            ' Remove all older files in any subfolders of this one
            For Each objSubFolder In objFolder.Subfolders
                RemoveOldFiles objSubFolder, intDays
            Next
        End If

        If blnRemoveEmptyFolders Then
            ' If folder is now empty, remove it
            If objFolder.Files.Count = 0 And objFolder.Subfolders.Count = 0 Then
                Wscript.Echo "Deleted folder: " & objFolder.Path
                objFolder.Delete
            End If
        End If
    End If
End Sub

Open in new window

I will try and comment out the on error statement tomorrow...

Thanks!
0
 
Bill PrewCommented:
Ah, I see a problem.  Try changing this line:

            If objFile.name = "*.log" Then

to:

            If LCase(Right(objFile.name, 4)) = ".log" Then

~bp
0
 
Bill PrewCommented:
One more should do it, you will also need to change:

                RemoveOldFiles objSubFolder, intDays

to:

                RemoveOldFiles objSubFolder, intDays, strDateToUse, blnProcessSubFolders, blnRemoveEmptyFolders

~bp
0
 
JamieD71Author Commented:
Rgonzo1971 - thank you very much - nice, simple easy script!
billprew - again, thank you very much - your script is brilliantly flexible and incorporating your last updates worked a treat!
0
 
Bill PrewCommented:
Great, glad that was useful.

~bp
0
 
JamieD71Author Commented:
Hi bp,

Very sorry to reopen a thread, but I've had a thought.

What are the possibilities to run the script to check against a file name, rather than the extension.

For example, if I searched for

FileName.0001
FileName.0002

The name remains the same, but the extension is sort of random...
0
 
Bill PrewCommented:
You can adjust the line we had above from this:

 If LCase(Right(objFile.Name, 4)) = ".log" Then

to this::

 If LCase(Left(objFile.Name, 9)) = "filename." Then

Just make sure the length in the LEFT() is correct, and if you want an exact match include the period so that things line "filenamexxx" don't also match.

Make sense?

~bp
0
 
JamieD71Author Commented:
Makes perfect sense - thank you and have  great weekend!
0
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.