0
votes

I'm new to VBScripting and have completely no knowledge on how to code but however i understand the basics of VBScripting.

I tried using the search function to find similar cases to mine but it doesn't have what i need.

I would really appreciate any help as my project is due soon.

Scenario:

I need to delete jpeg files that are more than 3months old that is in a directory with lots and lots of subfolders within each other. Furthermore there are 4 folders in the directory that i must not delete or modify.

How i manually did it was to navigate to the mapped drive, to the folder, use the "Search 'Folder'" from the window and type in this "datemodified:‎2006-‎01-‎01 .. ‎2013-‎08-‎31".

It will then show all the folders and subfolders and excel sheets within that folder, i'll then filter the shown list by ticking jpeg only from Type.

Code: '**** Start of Code **********

 Option Explicit 
 On Error Resume Next 
 Dim oFSO, oFolder, sDirectoryPath 
 Dim oFileCollection, oFile, sDir 
 Dim iDaysOld 

' Specify Directory Path From Where You want to clear the old files

 sDirectoryPath = "C:\MyFolder" 

' Specify Number of Days Old File to Delete

 iDaysOld = 15

 Set oFSO = CreateObject("Scripting.FileSystemObject") 
 Set oFolder = oFSO.GetFolder(sDirectoryPath) 
 Set oFileCollection = oFolder.Files 

For each oFile in oFileCollection

'This section will filter the log file as I have used for for test case 'Specify the Extension of file that you want to delete 'and the number with Number of character in the file extension

If LCase(Right(Cstr(oFile.Name), 4)) = "jpeg" Then

    If oFile.DateLastModified < (Date() - iDaysOld) Then 
    oFile.Delete(True) 
    End If 

End If   
Next 

Set oFSO = Nothing 
enter code here`Set oFolder = Nothing 
enter code here`Set oFileCollection = Nothing 
enter code here`Set oFile = Nothing 

'******* End of Code **********

I need to set an path that must be excluded + go through sub folders.

I'd like to thank you in advance for helping me out.

Thanks,

2

2 Answers

0
votes

Never ever use On Error Resume Next unless it absolutely cannot be avoided.

This problem needs a recursive function. Here's how I would do it:

Option Explicit

'set these constants to your requirements
Const DIR = "C:\MyFolder"
Const AGE = 15

Dim oFSO
Dim aExclude

'add to this array to exclude paths
aExclude = Array("c:\folder\exclude1", "c:\folder\another\exclude2")

Set oFSO = CreateObject("Scripting.FilesystemObject")
Call deleteFiles(oFSO.GetFolder(DIR))

Set oFSO = Nothing
WScript.Quit

'=================================
Function isExclude(sPath)
  Dim s

  For Each s in aExclude
    If LCase(s) = LCase(sPath) Then
      isExclude = True
      Exit Function
    End If
  Next

  isExclude = False
End Function

'==================================
Sub deleteFiles(fFolder)
  Dim fFile, fSubFolder

  If Not isExclude(fFolder.Path) Then
    For Each fFile in fFolder.Files
      If (LCase(Right(Cstr(fFile.Name),4)) = "jpeg") And (fFile.DateLastModified < (Date() - AGE)) Then
        'WScript.echo fFile.Path 'I put this in for testing, uncomment to do the same
        Call fFile.Delete(true)
      End If
    Next
  End If
  For Each fSubFolder in fFolder.SubFolders
    Call deleteFiles(fSubFolder)
  Next
End Sub

I'm not really able to fully test it out because I don't have an example data set, but really all you need to do is set DIR and change the aExclude array. Make sure you know what its going to delete before you run it though...

Also, it will only delete jpeg extensions, not jpg but I imagine you already know that

0
votes

Working solution (Jobbo almost got it to work in generic form):

UPDATE: includes log file writing with number of folders skipped and files deleted.

Option Explicit

'set these constants to your requirements
Const DIR = "C:\Test"
Const LOGFILE = "C:\Log.txt" ' Location of Log file
Const MAX_AGE = 3 ' Unit: Months
Const FILEEXT = "jpeg"

Dim oFSO
Dim oLogFile
Dim aExclude
Dim lngDeletes, lngSkips

'add to this array to exclude paths
aExclude = Array("c:\Test\test 1", "c:\Test\test 2\test")

Set oFSO = CreateObject("Scripting.FilesystemObject")
Set oLogFile = oFSO.createtextfile(LOGFILE)
lngDeletes = 0
lngSkips = 0
LOGG "Script Start time: " & Now
LOGG "Root Folder: " & DIR
LOGG String(50, "-")

deleteFiles oFSO.GetFolder(DIR)

LOGG String(50, "-")
LOGG lngDeletes & " files are deleted"
LOGG lngSkips & " folders skipped"
LOGG "Script End time: " & Now
oLogFile.Close
Set oLogFile = Nothing
Set oFSO = Nothing
MsgBox "Logfile: """ & LOGFILE & """", vbInformation, wscript.scriptName & " Completed at " & Now
wscript.Quit

'=================================
Sub LOGG(sText)
    oLogFile.writeline sText
End Sub
'=================================
Function isExclude(sPath)
    Dim s, bAns
    bAns = False
    For Each s In aExclude
        If InStr(1, sPath, s, vbTextCompare) = 1 Then
            bAns = True
            Exit For
        End If
    Next
    isExclude = bAns
End Function
'=================================
Function isOldFile(fFile)
    ' Old file if "MAX_AGE" months before today is greater than the file modification time
    isOldFile = (DateAdd("m", -MAX_AGE, Date) > fFile.DateLastModified)
End Function
'==================================
Function isFileJPEG(fFile)
    Dim sFileName
    sFileName = fFile.Name
    ' Mid(sFileName, InStrRev(sFileName, ".")) gives you the extension with the "."
    isFileJPEG = (LCase(Mid(sFileName, InStrRev(sFileName, ".") + 1)) = FILEEXT)
End Function
'==================================
Sub deleteFiles(fFolder)
    Dim fFile, fSubFolder
    If Not isExclude(fFolder.Path) Then
        'WScript.echo "==>> """ & fFolder.Path & """" ' Comment for no output
        For Each fFile In fFolder.Files
            If isFileJPEG(fFile) And isOldFile(fFile) Then
                lngDeletes = lngDeletes + 1
                LOGG lngDeletes & vbTab & fFile.Path
                'WScript.echo vbTab & "DELETE: """ & fFile.Path & """" ' Comment for no output
                fFile.Delete True ' Uncomment to really delete the file
            End If
        Next
        ' Only Process sub folders if current folder is not excluded
        For Each fSubFolder In fFolder.SubFolders
            deleteFiles fSubFolder
        Next
    Else
        lngSkips = lngSkips + 1
        'WScript.echo "<<-- """ & fFolder.Path & """" ' Comment for no output
    End If
End Sub

Output