Link to home
Start Free TrialLog in
Avatar of yccdadmins
yccdadmins

asked on

VBscript to delete files older than X day from folder and subfolders

Hello all,

I have been trying to set up a VB script to delete all files older than 2 days in a specific folder and all subfolders without deleting the folders.  I found a great script presented by an Expert on this site - RobSampson.  When I have tried to run the script I get an error message:

"Object doesn't support this property or message" 800A01B6.

The line being flagged is line 13, character 1 which equates to the first "For Each oSubFolder in oFolder"  Probably a spelling error somewhere on my part but I can't see it.  The only thing I noted is that I don't see oSubFolder defined anywhere previously in the script.

Here is the script:

iDaysOld = 1
Set oFSO = CreateObject("Scripting.FileSystemObject")
sDirectoryPath = "C:\Temp"
set oFolder = oFSO.GetFolder(sDirectoryPath)
set oFileCollection = oFolder.Files
'If database log file backups are older than 1 days, delete them.
For each oFile in oFileCollection
      If oFile.DateLastModified < (Date() - iDaysOld) Then
            oFile.Delete(True)
      End If
Next

For Each oSubFolder In oFolder 'SCRIPT BOMBS HERE
      RecurseFolders oSubFolder
Next

'Clean up
Set oFSO = Nothing
Set oFolder = Nothing
Set oFileCollection = Nothing
Set oFile = Nothing

Sub RecurseFolders(oFolder)
      set oFileCollection = oFolder.Files
      'If database log file backups are older than 1 days, delete them.
      For each oFile in oFileCollection
            If oFile.DateLastModified < (Date() - iDaysOld) Then
                  oFile.Delete(True)
            End If
      Next      
      For Each oSubFolder In oFolder
            RecurseFolders oSubFolder
      Next
End Sub

RobSampson....you out there?
Avatar of yccdadmins
yccdadmins

ASKER

Forgot to mention - environment is Windows 2008 R2 server.
ASKER CERTIFIED SOLUTION
Avatar of Kimputer
Kimputer

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Looks like that may have been it - excellent!  I'm getting a permissions error now and that is probably due to specific system files - I'm testing on old user profiles.
In that case, try to incorporate:

'at the top
On Error Resume Next

'right after delete
if  Err.Number <> 0  then  
  'code some text  file logging to list the files giving you errors
end
Err.Clear