Solved

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

Posted on 2009-07-02
10
551 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
  • 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
 
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
Threat Intelligence Starter Resources

Integrating threat intelligence can be challenging, and not all companies are ready. These resources can help you build awareness and prepare for defense.

 
LVL 12

Assisted Solution

by:kevin_u
kevin_u earned 500 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

Better Security Awareness With Threat Intelligence

See how one of the leading financial services organizations uses Recorded Future as part of a holistic threat intelligence program to promote security awareness and proactively and efficiently identify threats.

Join & Write a Comment

This is an addendum to the following article: Acitve Directory based Outlook Signature (http://www.experts-exchange.com/Programming/Languages/Visual_Basic/VB_Script/Q_24950055.html) The script is fine, and works in normal client-server domains…
Welcome back!  My apologies for taking so long to write part two of this series; it's been a long time coming!  As I promised in Part 1, this article will focus on how to locate those elusive AD properties that you are searching for.  Why is this us…
Access reports are powerful and flexible. Learn how to create a query and then a grouped report using the wizard. Modify the report design after the wizard is done to make it look better. There will be another video to explain how to put the final p…
In this tutorial you'll learn about bandwidth monitoring with flows and packet sniffing with our network monitoring solution PRTG Network Monitor (https://www.paessler.com/prtg). If you're interested in additional methods for monitoring bandwidt…

760 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

18 Experts available now in Live!

Get 1:1 Help Now