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,479 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 48

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 48

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
 

Author Comment

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

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 51

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 51

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 51

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
What Security Threats Are You Missing?

Enhance your security with threat intelligence from the web. Get trending threat insights on hackers, exploits, and suspicious IP addresses delivered to your inbox with our free Cyber Daily.

 
LVL 51

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 51

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 51

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 51

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 51

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

Enabling OSINT in Activity Based Intelligence

Activity based intelligence (ABI) requires access to all available sources of data. Recorded Future allows analysts to observe structured data on the open, deep, and dark web.

Join & Write a Comment

Welcome, welcome!  If you are new to the series and haven't been following along, please take a brief moment to review the first three installments: Part 1 (http://www.experts-exchange.com/Programming/Languages/Visual_Basic/VB_Script/A_266-VBScri…
Deploying a Microsoft Access application in a Citrix environment is not difficult but takes a few steps. However, Citrix system people are often of little help, as they typically know next to nothing about Access. The script provided here will take …
It is a freely distributed piece of software for such tasks as photo retouching, image composition and image authoring. It works on many operating systems, in many languages.
This video discusses moving either the default database or any database to a new volume.

757 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

Need Help in Real-Time?

Connect with top rated Experts

21 Experts available now in Live!

Get 1:1 Help Now