VBScript: Delete Old Files and Folders


Scripts & Tools

Here is a simple VBScript that you can schedule to run nightly that will clean out files and folders in a selected path older than a specified number of days. Maybe you have a shared temporary working space for documents or a location where scanned or faxed documents are dropped. This VBS script will ensure that these locations don't get clogged up or overly cluttered. Read further for the code...

The following code will get rid of old files and folders. Just put in the path and how old the files or folders need to be before they are considered stale and should be removed.

 

'*  Script Name:   DeleteOldFiles.vbs
'*  Created On:    12/07/2007
'*  Author:        Michael C. Panagos
'*  Website:       http://www.grimadmin.com
'*  Purpose:       Delete files & folders older than x days
'*  History:       Michael C. Panagos 12/07/2007
'*                 Initial Draft.
'*  Legal:         Copying and distribution of this code, with or without modification,
'*                 are permitted in any medium without royalty provided the copyright
'*                 notice and this notice are preserved.  This code is offered as-is,
'*                 without any warranty.

'Account used to run script needs delete permissions to folder & files.

'Set the following variables
TempFolderPath = "X:\YourFolder\YourSubfolder" 'no trailing backslash
NumberOfDays = 60 'anything older than this many days will be removed

'Set objects & error catching
On Error Resume Next
Dim fso
Dim objFolder
Dim objFile
Dim objSubfolder
Set fso = CreateObject("Scripting.FileSystemObject")
Set objFolder = fso.GetFolder(TempFolderPath)

'DELETE all files in TempFolder Path older than x days
For Each objFile In objFolder.files
    If DateDiff("d", objFile.DateCreated,Now) > NumberOfDays Then
        objFile.Delete True
        End If
Next

'DELETE all subfolders in TempFolder Path older than x days
For Each objSubfolder In objFolder.Subfolders
    If DateDiff("d", objSubfolder.DateCreated,Now) > NumberOfDays Then
            objSubfolder.Delete True     
        End If
Next

 

Tag: vbscript file management

Share It!

Anyway this could be modded to include various different folders? I have several different folders on a server that I'd like it to clean up!
That should be pretty simple. The easiest way would be to just repeat the code in the same vbs file setting a new path for the next set of folders. The other option would be to create a variable or CSV file with all the file paths in it and do a "For Each" loop. Something like:

NumberOfDays = 60 'anything older than this many days will be removed

Dim TempFolderPath(2)
TempFolderPath(0)="C:\folder1"
TempFolderPath(1)="C:\folder2"
TempFolderPath(2)="C:\folder3"

For Each x In TempFolderPath 
  'Set objects & error catching
  On Error Resume Next
  Dim fso
  Dim objFolder
  Dim objFile
  Dim objSubfolder
  Set fso = CreateObject("Scripting.FileSystemObject")
  Set objFolder = fso.GetFolder(x)

  'DELETE all files in TempFolder Path older than x days
  For Each objFile In objFolder.files
      If DateDiff("d", objFile.DateCreated,Now) > NumberOfDays Then
          objFile.Delete True
          End If
  Next

  'DELETE all subfolders in TempFolder Path older than x days
  For Each objSubfolder In objFolder.Subfolders
      If DateDiff("d", objSubfolder.DateCreated,Now) > NumberOfDays Then
              objSubfolder.Delete True     
          End If
  Next
Next
Edited on Saturday, March 19 2011 @ 05:28 PM EDT by Admin
anyway to specify the file type like *.log files?
Sure, just change the line in the delete files section to:
If DateDiff("d", objFile.DateCreated,Now) > NumberOfDays And LCase(fso.GetExtensionName(objFile)) = "log" Then

Then delete the 'delete subfolders' folders section so it doesn't delete any subfolders.
I wrote some VBScript code on my site that I have used in the past to remove and/or archive files. It doesnt delete folders only files in directories that were passed in. That said, It does a couple of this that are very useful which may make you want incorporate the code above into it.

The script is designed to use XML to define Jobs that the Windows Scripting Host understand. Each Job script can define the directory to be search, file pattern to look for, and minimum age of the file in days as criteria for deletion. also, the Jobs can be setup to archive and log the files that were found prior to final deletion so that a proper audit trail can be maintained.

The Jobs can be set to run using the windows scheduler every day, week, month ect.

you can find the runnable VBscript app ziped up with some example files @ http://www.code-bytes.com/Automate_WSH_VBScript_To_Delete_Or_Archive_Files.html
Thanks for sharing!
Hi

THanks for the script. I am running this on an XP Pro SP3 box.

Getting a file not found error on this line when it finds a file older than the specified date. It does not throw the error until it finds a folder that is older than and tries to delete it.

objSubfolder.Delete True

Also, non of the files in the folders and subfolders are being deleted, even tho that portion of the code appears before the place where it throws the error!?!?

Any ideas?
my guess is there is an issue early on in the script possibly cause by the version of WSH or vbscript shell version. As I recall there are some on error resume statments in the WSH files or in the includes. Comment them our to find out what the error is that is causing the problem.

Can anyone please share the vbscript code to delete files older than x days with given format and then updating the details for report name , created date,last modified date, deleted date in a log file.
Hi,

Can some help me to modify the below script?
I just want to add one more directory in source. As of now I have E: drive to delete the folders and files older than 2 days. This script will also delete empty folers, but i want only delete the empty folder older than two days

My requirements

Source folders

E: drive
c:\windows\temp

Delete empty folder older than two days



on error resume next

Const MaxAge = 2 'days ' Enter number of days to keep files
Const Recursive = True ' Only does path provided in Parameter1 if FALSE, includes sub directories if TRUE

' Below are defaults for the variables used

Active = True ' Set this to False to test - Active will delete files
Checked = 0
FoldersChecked = 0
Deleted = 0
FoldersDeleted = 0

' This will capture the command line parameters - uses safe setting if parameter1 is omitted.

set ArgObj = wScript.Arguments
var1 = ArgObj(0)
if len(var1) = 0 then
Active = TRUE
sSource = "E:"
else
sSource = var1
end if


' Start of main script - calls CheckFolder (for files) and CheckFolders (for directories)

Set oFSO = CreateObject("Scripting.FileSystemObject")
if active then verb = "Deleting """ Else verb = "Old file: """
CheckFolder oFSO.GetFolder(sSource)
CheckFolders oFSO.GetFolder(sSource)

WScript.echo
if Active then verb = " file(s) deleted" Else verb = " file(s) would be deleted"
WScript.Echo Checked & " file(s) checked, " & Deleted & verb
if Active then verb = " folder(s) deleted" Else verb = " folder(s) would be deleted"
wscript.echo FoldersChecked & " folder(s) checked, " & FoldersDeleted & verb


' This sub checks files in each folder, recursively if selected

Sub CheckFolder (oFldr)
For Each oFile In oFldr.Files
Checked = Checked + 1
If DateDiff("D", oFile.DateLastModified, Now()) > MaxAge Then
Deleted = Deleted + 1
WScript.Echo verb & oFile.Path & """"
If Active Then oFile.Delete
End If
Next
if not Recursive then Exit Sub
For Each oSubfolder In oFldr.Subfolders
CheckFolder(oSubfolder)
Next
End Sub


'This sub checks directories (to delete), recursively if selected

Sub CheckFolders (oFolder)
for each oFldr in oFolder.SubFolders
if oFldr.SubFolders.count <> 0 and recursive then CheckFolders(oFldr)
FoldersChecked = FoldersChecked + 1
If oFldr.SubFolders.count = 0 and oFldr.Files.count = 0 then
FoldersDeleted = FoldersDeleted + 1
If Active Then
wscript.echo ("Folder """ & oFldr & """ is empty and will be deleted.")
oFldr.Delete
else
wscript.echo ("Folder """ & oFldr & """ is empty and should be deleted.")
end if
end if
Next
End Sub
Maybe there is an important websites just where I often look for http://www.besttermpapers.com/thesis-writing.html? We want to begin the process choosing all of these offerings still there is a great many one could use and additionally Now i'm confounded. Is it possible you provide you with a the best quality offerings i absolutely may well consider?