?
Solved

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

Posted on 2014-04-09
20
Medium Priority
?
6,137 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
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 8
  • 8
  • 2
  • +2
20 Comments
 
LVL 52

Assisted Solution

by:Rgonzo1971
Rgonzo1971 earned 400 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 52

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
What does it mean to be "Always On"?

Is your cloud always on? With an Always On cloud you won't have to worry about downtime for maintenance or software application code updates, ensuring that your bottom line isn't affected.

 

Author Comment

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

Assisted Solution

by:MacroShadow
MacroShadow earned 200 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 56

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 56

Accepted Solution

by:
Bill Prew earned 1400 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 56

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 56

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 56

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 56

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 56

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 56

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

VIDEO: THE CONCERTO CLOUD FOR HEALTHCARE

Modern healthcare requires a modern cloud. View this brief video to understand how the Concerto Cloud for Healthcare can help your organization.

Question has a verified solution.

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

I met Paul Devereux (@pdevereux) today when I responded to his tweet asking “Anybody know how to automate adding files from disk to a folder in #outlook  ?”.  I replied back and told Paul that using automation, in this case scripting, to add files t…
This is pretty cool.  The purpose of this VB Script is to help you document where JAR (Java ARchive) files and specifically java class files are located so that you can address issues seen with a client or that you can speak intelligently with a dev…
In this video we outline the Physical Segments view of NetCrunch network monitor. By following this brief how-to video, you will be able to learn how NetCrunch visualizes your network, how granular is the information collected, as well as where to f…
Add bar graphs to Access queries using Unicode block characters. Graphs appear on every record in the color you want. Give life to numbers. Hopes this gives you ideas on visualizing your data in new ways ~ Create a calculated field in a query: …
Suggested Courses

770 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