Link to home
Start Free TrialLog in
Avatar of m1721c
m1721c

asked on

Delete script based on date

Hi I need VB script help.  I have backups that run and they are saved as target c:\backup\servername(I have multiple servers)

This almost does what i need it to do, this deletes the files(C:\backup\servername\allfiles*, but i need it to delete the subfolder.(C:\backup\sms\folder)  based on the date.  I want it to delete a file thats 10 days old  I need something that i can schedule using task scheduler

iDaysOld = 10
strPath = "C:\Backup"

Set objFSO = CreateObject("Scripting.FileSystemObject")  
Set objFolder = objFSO.GetFolder(strPath)  
Set colSubfolders = objFolder.Subfolders  
Set colFiles = objFolder.Files  

For Each objFile in colFiles  
   If objFile.DateLastModified < (Date() - iDaysOld) Then  
       MsgBox "Dir: " & objFolder.Name & vbCrLf & "File: " & objFile.Name
       'objFile.Delete  
   End If  
Next  


For Each objSubfolder in colSubfolders  
   Set colFiles = objSubfolder.Files  
   For Each objFile in colFiles  
       If objFile.DateLastModified < (Date() - iDaysOld) Then  
           MsgBox "Dir: " & objSubfolder.Name & vbCrLf & "File: " & objFile.Name
           objFile.Delete
       End If  
   Next  
Next  


Thanks for the help
Avatar of JesterToo
JesterToo
Flag of United States of America image

Actually, that code should delete every file that is older than 10 days in the folder "C:\Backup" or in any of its subfolders... it appears to be doing at least what you need... maybe more?

Can you clarify what needs to be deleted and what needs to remain within the C:\Backup tree?
Avatar of m1721c
m1721c

ASKER

I need it to delete the folder

so the tree is   C:\Backup\SMS\SMS_1,  C:\Backup\SET\SET_1, etc    I need it to delete the SMS_1 folder, SET_1 folder and contents based on the date created.  It is only deleting the files contained in the folders SET_1, and SMS_1
You're on the right track, you just aren't actually telling it to delete any folders.  You need to use the .Delete method on the folder object for that.

Something like this:
For Each objSubfolder in colSubfolders  
   If objSubFolder.DateLastModified < (Date() - iDaysOld) Then  
      MsgBox "Dir: " & objSubfolder.Name
      objSubFolder.Delete
   End If  
Next  

Open in new window

Avatar of m1721c

ASKER

Ok this almost gets the job done.  but it deleteing the server folder as well, I need it to only delete the actual backup(C:\backup\SMS\SMS_1)  and leave the SMS folder alone
ASKER CERTIFIED SOLUTION
Avatar of JesterToo
JesterToo
Flag of United States of America image

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