Expiring Today—Celebrate National IT Professionals Day with 3 months of free Premium Membership. Use Code ITDAY17

x
?
Solved

Modify file/folder deletion script to delete folders only based on date.

Posted on 2009-07-02
10
Medium Priority
?
557 Views
Last Modified: 2012-05-07
Hi, I have a batch file that works great for deleting old files in folders then deleting the empty folder.  However, I need to modify it so that it only deletes the folder if it's older than a certain date, regardless of how old the files inside the folder are.  

Also, to accomplish a separate task,  how could this be modified to delete everything inside a folder except .zip files?
' Create a FileSystemObject
Set fso = CreateObject("Scripting.FileSystemObject")
 
' Enter your folder to start deleting files from
startFolder = "R:\WEB BACKUPS\"
 
' Enter the names of folders to exclude from checking:
arrFoldersToExclude = Array("Sync")
strFoldersToExclude = ";" & Join(arrFoldersToExclude, ";") & ";"
 
' This sets the amount of days old for files to be, before
' they are deleted.  The number must be negative.
OlderThanDate = DateAdd("d", -45, Date)  ' 90 days (adjust as necessary)
 
' This calls the function that actually deletes the files.
DeleteOldFiles startFolder, OlderThanDate
 
Function DeleteOldFiles(folderName, BeforeDate)
   Dim folder, file, fileCollection, folderCollection, subFolder
 
         ' Get the folder to delete files from
         Set folder = fso.GetFolder(folderName)
 
      If InStr(LCase(strFoldersToExclude), ";" & LCase(folder.Name) & ";") = 0 Then
         ' Return a collection of all of the files in that folder
         Set fileCollection = folder.Files
         ' Go through each file....
         For Each file In fileCollection
                   ' ... to check if the DateLastModified value is before
                   ' the minimum age of files to delete.
               If file.DateLastModified < BeforeDate Then
                  fso.DeleteFile(file.Path), True
               End If
         Next
      End If
      ' Get the next collection of SubFolders to go through
    Set folderCollection = folder.SubFolders
 
      ' Go through each SubFolder
      For Each subFolder In folderCollection
            ' Check if the current folder name is in the strFoldersToExclude string
            If InStr(LCase(strFoldersToExclude), ";" & LCase(fso.GetFolder(foldername).Name) & ";") = 0 Then
                  ' If it's not, delete the files from that folder
                  DeleteOldFiles subFolder.Path, BeforeDate
            End If
      Next
' if the folder is empty - delete it
 If folder.Files.Count = 0 And _
    folder.SubFolders.Count = 0 Then
   
   'folder.delete
   'to test script, comment out the line above ^, and
   'uncomment the line below v
    WScript.Echo "Delete folder <" & folderName & ">"
 
 End If
End Function

Open in new window

0
Comment
Question by:sharkbot221984
[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
  • 7
  • 2
10 Comments
 
LVL 5

Expert Comment

by:artoaperjan
ID: 24767784
hi
i need to script it if u want, then i'll explain

Art
0
 
LVL 12

Expert Comment

by:kevin_u
ID: 24767833
It may not be possible to do exactly what you want.

The act of deleting a file in a folder automatically updates the last modifed date of the folder.  So if anything is deleted, the folder will never be elegible for deletion... That is if I understand what you want.

If on the other hand, you mean just look at the last modifed date of a folder, without even looking at its contents, and delete it and the contents, that is possible.

To avoid deleting zip files:
Change line 31: If file.DateLastModified < BeforeDate Then
to
if file.DateLastModifed < BeforeDate and Right(LCase(file.Name),4) <> ".zip" then


0
 
LVL 8

Author Comment

by:sharkbot221984
ID: 24768192
@ kevin,

I mean just look at the last modified date of a folder, without even looking at it's contents, and delete it and the contents.
0
Industry Leaders: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 
LVL 8

Author Comment

by:sharkbot221984
ID: 24768247
Kevin,

I left a detail out I didn't remember until I went to test deleting everything but the .zip files:

The folder structure is MAINFOLDER -> SUBFOLDERS -> Files / Folders / .zip files

I want to target the Main Folder in the script, have it drill into any subfolders inside the main folder, delete everything that's not a .zip file, but leave the sub folder alone.  In other words the subfolder in the main folder is not zipped, but should contain only zip files when the script is done.  I hope that makes sense.

So when it's done it should be MAINFOLDER -> SUBFOLDERS -> .zip files

Thanks for your help.
0
 
LVL 8

Author Comment

by:sharkbot221984
ID: 24768297
Actually never mind, since it doesn't delete the .zip files the folders aren't empty so the second part of the script doesn't delete the sub folder, perfect!
0
 
LVL 12

Assisted Solution

by:kevin_u
kevin_u earned 2000 total points
ID: 24768979
The attached code is yours reworked.
It has the zip file exclusion.
It should also deal with deleting the folders as you specified.  

Test it well, as you know this deletes stuff.
' Create a FileSystemObject
Set fso = CreateObject("Scripting.FileSystemObject")
 
' Enter your folder to start deleting files from
startFolder = "R:\WEB BACKUPS\"
 
' Enter the names of folders to exclude from checking:
arrFoldersToExclude = Array("Sync")
strFoldersToExclude = ";" & Join(arrFoldersToExclude, ";") & ";"
 
' This sets the amount of days old for files to be, before
' they are deleted.  The number must be negative.
OlderThanDate = DateAdd("d", -45, Date)  ' 90 days (adjust as necessary)
ForceDelete = CDate("December 31, 2099")  ' trick: everything is older than this
 
' This calls the function that actually deletes the files.
DeleteOldFiles startFolder, OlderThanDate
 
Function DeleteOldFiles(folderName, BeforeDate)
   Dim folder, file, fileCollection, folderCollection, subFolder
 
         ' Get the folder to delete files from
         Set folder = fso.GetFolder(folderName)
 
      If InStr(LCase(strFoldersToExclude), ";" & LCase(folder.Name) & ";") = 0 Then
         ' Return a collection of all of the files in that folder
         Set fileCollection = folder.Files
         ' Go through each file....
         For Each file In fileCollection
                   ' ... to check if the DateLastModified value is before
                   ' the minimum age of files to delete.
               if file.DateLastModifed < BeforeDate and Right(LCase(file.Name),4) <> ".zip" then
                  fso.DeleteFile(file.Path), True
               End If
         Next
      End If
      ' Get the next collection of SubFolders to go through
    Set folderCollection = folder.SubFolders
 
      ' Go through each SubFolder
      For Each subFolder In folderCollection
            ' Check if the current folder name is in the strFoldersToExclude string
            If InStr(LCase(strFoldersToExclude), ";" & LCase(fso.GetFolder(foldername).Name) & ";") = 0 Then
                  ' If it's not, delete the files from that folder
                  DeleteOldFiles subFolder.Path, BeforeDate
				  ' additionally, if the folder is old, force a delete of everything.
				  '  (except zip files)
				  if subFolder.DateLastModifed < BeforeDate then
                     DeleteOldFiles subFolder.Path, ForceDelete
				  end if
            End If
      Next
' if the folder is empty - delete it
 If folder.Files.Count = 0 And _
    folder.SubFolders.Count = 0 Then
   
   'folder.delete
   'to test script, comment out the line above ^, and
   'uncomment the line below v
    WScript.Echo "Delete folder <" & folderName & ">"
 
 End If
End Function

Open in new window

0
 
LVL 8

Author Comment

by:sharkbot221984
ID: 24789956
Thanks, but I get Error: Object doesn't support this property or method: 'file.DataLastModified'
0
 
LVL 8

Author Comment

by:sharkbot221984
ID: 24824955
Okay, 'Modified' was spelled wrong so that was the error cause.  However this is still deleting all the files in the subfolders.  The files are meant to be older than the deletion date (they are archive backups)  So as written it would wipe out all the files, subfolders and folders in the directory.  I want to exclude the files from deletion and only delete the folders in the directory that have a modified date older than X days.  

So if I have Folder named "Archive 5-29-2009" and a folder named "Archive 5-30-2009"  both are likely to contain the same files that may be even older than 5-29-2009.  Folder "Archive 5-29-2009" was modified 5-29-2009 and folder "Archive 5-30-2009" was modified 5-30-2009 I want to delete 5-29 and keep 5-30 regardless of the fact that both contain files that are older than the kill date.
0
 
LVL 8

Author Comment

by:sharkbot221984
ID: 24825009
I snipped some unneeded function from this, this one doesn't need to exclude an array, so that's gone, and it also doesn't need to exclude .zip files (though that was perfect for the other application) still deleting files wrong tho
' Create a FileSystemObject
Set fso = CreateObject("Scripting.FileSystemObject")
 
' Enter your folder to start deleting files from
startFolder = "R:\WEB BACKUPS\"
 
' This sets the amount of days old for files to be, before
' they are deleted.  The number must be negative.
OlderThanDate = DateAdd("d", -45, Date)  ' 90 days (adjust as necessary)
ForceDelete = CDate("December 31, 2099")  ' trick: everything is older than this
 
' This calls the function that actually deletes the files.
DeleteOldFiles startFolder, OlderThanDate
 
Function DeleteOldFiles(folderName, BeforeDate)
   Dim folder, file, fileCollection, folderCollection, subFolder
 
         ' Get the folder to delete files from
         Set folder = fso.GetFolder(folderName)
 
         Set fileCollection = folder.Files
         ' Go through each file....
         For Each file In fileCollection
                   ' ... to check if the DateLastModified value is before
                   ' the minimum age of files to delete.
               if file.DateLastModified < BeforeDate Then
                  fso.DeleteFile(file.Path), True
               End If
         Next
      
      ' Get the next collection of SubFolders to go through
    Set folderCollection = folder.SubFolders
 
      ' Go through each SubFolder
      For Each subFolder In folderCollection
            ' Check if the current folder name is in the strFoldersToExclude string
                     DeleteOldFiles subFolder.Path, BeforeDate
                                  ' additionally, if the folder is old, force a delete of everything.
                                  '  (except zip files)
                                  if subFolder.DateLastModified < BeforeDate then
                     DeleteOldFiles subFolder.Path, ForceDelete
                                  end if
               Next
' if the folder is empty - delete it
 If folder.Files.Count = 0 And _
    folder.SubFolders.Count = 0 Then
   
   'folder.delete
   'to test script, comment out the line above ^, and
   'uncomment the line below v
    WScript.Echo "Delete folder <" & folderName & ">"
 
 End If
End Function

Open in new window

0
 
LVL 8

Accepted Solution

by:
sharkbot221984 earned 0 total points
ID: 24826041
Simple is better....

This does exactly what I wanted, tested and taken live.
Dim fso, OlderThanDate
Dim folder, folderCollection, subFolder
 
OlderThanDate = DateAdd("d", -30, Date) 
Set fso = CreateObject("Scripting.FileSystemObject")
Set folder = fso.GetFolder("R:\WEB BACKUPS\")
Set folderCollection = folder.SubFolders
For Each subFolder In folderCollection
    If subFolder.Name <> "Sync" Then
        If subFolder.DateCreated < OlderThanDate Then
            fso.DeleteFolder subFolder.Path, True
	    'WScript.Echo "Delete folder <" & subFolder & ">"
        End If
    End If
Next

Open in new window

0

Featured Post

Free Tool: Path Explorer

An intuitive utility to help find the CSS path to UI elements on a webpage. These paths are used frequently in a variety of front-end development and QA automation tasks.

One of a set of tools we're offering as a way of saying thank you for being a part of the community.

Question has a verified solution.

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

Script to copy or move mouse-selected collection of files plus targets referenced by shortcuts (.lnk) The purpose of this article is to help illuminate the real challenges and options available (where they may exist) for utilizing simple scriptin…
When it comes to writing scripts for a Client/Server computing environment it is essential to consider some way of enabling the authentication functionality within a script. This sort of consideration mainly comes into the picture when we are dealin…
This is my first video review of Microsoft Bookings, I will be doing a part two with a bit more information, but wanted to get this out to you folks.
In this video, Percona Solution Engineer Rick Golba discuss how (and why) you implement high availability in a database environment. To discuss how Percona Consulting can help with your design and architecture needs for your database and infrastr…

719 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