Solved

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

Posted on 2014-04-09
20
5,626 Views
Last Modified: 2015-07-31
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!
0
Comment
Question by:JamieD71
  • 8
  • 8
  • 2
  • +2
20 Comments
 
LVL 49

Assisted Solution

by:Rgonzo1971
Rgonzo1971 earned 100 total points
ID: 39988355
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
 

Author Comment

by:JamieD71
ID: 39988365
Hi Rgonzo1971,

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

Thanks!
0
 
LVL 49

Expert Comment

by:Rgonzo1971
ID: 39988393
Hi,

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

On line 12 it is already specified
0
Live: Real-Time Solutions, Start Here

Receive instant 1:1 support from technology experts, using our real-time conversation and whiteboard interface. Your first 5 minutes are always free.

 

Author Comment

by:JamieD71
ID: 39988398
Sorry - thanks!  Will try it now!
0
 
LVL 27

Assisted Solution

by:MacroShadow
MacroShadow earned 50 total points
ID: 39988402
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
 
LVL 53

Expert Comment

by:Bill Prew
ID: 39988442
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
 
LVL 53

Accepted Solution

by:
Bill Prew earned 350 total points
ID: 39988546
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
 

Author Comment

by:JamieD71
ID: 39988675
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
 
LVL 53

Expert Comment

by:Bill Prew
ID: 39988700
Sorry, looks like a bug in the original code.  Should be like this:

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

~bp
0
 

Author Comment

by:JamieD71
ID: 39988854
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
 
LVL 53

Expert Comment

by:Bill Prew
ID: 39989001
Can you post the code you ran please.

~bp
0
 
LVL 65

Expert Comment

by:RobSampson
ID: 39989193
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
 

Author Comment

by:JamieD71
ID: 39989574
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
 
LVL 53

Expert Comment

by:Bill Prew
ID: 39989687
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
 
LVL 53

Expert Comment

by:Bill Prew
ID: 39989695
One more should do it, you will also need to change:

                RemoveOldFiles objSubFolder, intDays

to:

                RemoveOldFiles objSubFolder, intDays, strDateToUse, blnProcessSubFolders, blnRemoveEmptyFolders

~bp
0
 

Author Closing Comment

by:JamieD71
ID: 39991030
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
 
LVL 53

Expert Comment

by:Bill Prew
ID: 39991851
Great, glad that was useful.

~bp
0
 

Author Comment

by:JamieD71
ID: 39994205
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
 
LVL 53

Expert Comment

by:Bill Prew
ID: 39994302
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
 

Author Comment

by:JamieD71
ID: 39994312
Makes perfect sense - thank you and have  great weekend!
0

Featured Post

Gigs: Get Your Project Delivered by an Expert

Select from freelancers specializing in everything from database administration to programming, who have proven themselves as experts in their field. Hire the best, collaborate easily, pay securely and get projects done right.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Hello again, all.  For those of you that have been following along, you'll know that this is my third article on this topic (though it is not Part III).  This article is sort of remedial, and probably the topic with which I should have started the s…
Not long ago I saw a question in the VB Script forum that I thought would not take much time. You can read that question (Question ID  (http://www.experts-exchange.com/Programming/Languages/Visual_Basic/VB_Script/Q_28455246.html)28455246) Here (http…
Two types of users will appreciate AOMEI Backupper Pro: 1 - Those with PCIe drives (and haven't found cloning software that works on them). 2 - Those who want a fast clone of their boot drive (no re-boots needed) and it can clone your drive wh…
Nobody understands Phishing better than an anti-spam company. That’s why we are providing Phishing Awareness Training to our customers. According to a report by Verizon, only 3% of targeted users report malicious emails to management. With compan…

776 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question