Sign Up!
Login
Welcome to The Grim Admin
Wednesday, April 26 2017 @ 07:47 AM EDT

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

Trackback

Trackback URL for this entry: http://www.grimadmin.com/trackback.php/vbs-delete-old-files-and-folders

Here's what others have to say about 'VBScript: Delete Old Files and Folders':

Programming Links | Vincent's Webspace
[...] Language Reference Contents for Guy’s Scripting Ezine 36 – FSO Copy (Part 2) Cook BookVBScript: Delete Old Files and FoldersVBScript to Delete Files in a Directory Older Than X Days Unix Epoch Time in seconds converter in [...] [read more]
Tracked on Thursday, March 24 2016 @ 04:09 AM EDT

How To Delete Nested Folders By Vbscript | Khmer Bank
[...] and VB6 and in doesn’t work can you help me??? this is my email freakofrk2@msn.comVBScript: Delete Old Files and Folders – The Grim Admin – I wrote some VBScript code on my site that I have used in the past to remove and/or [...] [read more]
Tracked on Sunday, July 17 2016 @ 07:21 AM EDT

How To Delete Nested Folders By Vbscript | Information
[...] A Homemade Wind Turbine 1 min ago How To Delete Birthdays On Google Calendar 1 min agoVBScript: Delete Old Files and Folders – The Grim Admin – I wrote some VBScript code on my site that I have used in the past to remove and/or archive [...] [read more]
Tracked on Tuesday, September 06 2016 @ 01:33 AM EDT

How To Delete Nested Folders By Vbscript | Information
[...] Vista 5 mins ago How To Determine Quartiles With Mean And Standard Deviation 6 mins agoVBScript: Delete Old Files and Folders – The Grim Admin – I wrote some VBScript code on my site that I have used in the past to remove and/or [...] [read more]
Tracked on Tuesday, September 06 2016 @ 06:45 PM EDT

How To Delete Recursive Folders In Windows Xp | Information
[...] Empty Windows XP" by going to "Disk Properties" and performing the check …VBScript: Delete Old Files and Folders – The Grim Admin – I wrote some VBScript code on my site that I have used in the past to remove and/or [...] [read more]
Tracked on Friday, September 09 2016 @ 12:54 PM EDT

How To Delete Vbs Files | Information
[...] = True Set oFSO = CreateObject("Scripting.FileSystemObject") Set …VBScript: Delete Old Files and Folders – The Grim Admin – I wrote some VBScript code on my site that I have used in the past to remove and/or archive [...] [read more]
Tracked on Sunday, September 25 2016 @ 08:34 PM EDT

How To Delete Recursive Folders In Windows Xp | am
[...] Empty Windows XP" by going to "Disk Properties" and performing the check …VBScript: Delete Old Files and Folders – The Grim Admin – I wrote some VBScript code on my site that I have used in the past to remove and/or [...] [read more]
Tracked on Tuesday, September 27 2016 @ 08:21 PM EDT

13 comments

The following comments are owned by whomever posted them. This site is not responsible for what they say.
Authored by: jasonfrancis170 on Wednesday, March 16 2011 @ 06:18 AM EDT VBScript: Delete Old Files and Folders
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!
Authored by: Admin on Saturday, March 19 2011 @ 02:14 PM EDT VBScript: Delete Old Files and Folders
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 @ 02:28 PM EDT by Admin
Authored by: Anonymous User on Monday, May 16 2011 @ 02:54 PM EDT VBScript: Delete Old Files and Folders
anyway to specify the file type like *.log files?
Authored by: Admin on Tuesday, May 17 2011 @ 10:17 AM EDT VBScript: Delete Old Files and Folders
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.
Authored by: Anonymous User on Tuesday, April 19 2011 @ 11:55 PM EDT VBScript: Delete Old Files and Folders
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
Authored by: Admin on Sunday, August 14 2011 @ 12:32 AM EDT VBScript: Delete Old Files and Folders
Thanks for sharing!
Authored by: Anonymous User on Wednesday, January 04 2012 @ 01:02 PM EST VBScript: Delete Old Files and Folders
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?
Authored by: John on Saturday, August 18 2012 @ 01:48 PM EDT VBScript: Delete Old Files and Folders
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.

Authored by: Suraj on Wednesday, June 06 2012 @ 01:13 PM EDT VBScript: Delete Old Files and Folders
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.
Authored by: Anonymous User on Tuesday, January 29 2013 @ 10:41 AM EST VBScript: Delete Old Files and Folders
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
Authored by: Anonymous User on Tuesday, April 01 2014 @ 09:57 PM EDT VBScript: Delete Old Files and Folders
Hello,
Just found this: http://gallery.technet.microsoft.com/scriptcenter/Delete-files-folders-and-2eb27869

I believe this guy did a good job.

Enjoy :)
Authored by: Anonymous User on Sunday, March 06 2016 @ 05:43 AM EST VBScript: Delete Old Files and Folders
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?
Authored by: Anonymous User on Sunday, March 27 2016 @ 12:21 PM EDT VBScript: Delete Old Files and Folders
You can find the description to a code analysis on http://www.besstdissertation.com/

Advertisement