vbscript delete files with extensions

vbscript to find all files with an extension and delete with exclude some folders


I want to scan entire drive or folder for particular extensions of files like "log" "err"

and exclude some folders like "windows" "program files"

also file having extension older than number of days
mash1978ITAsked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

mash1978ITAuthor Commented:
I found script but without folder exclusion


'Delete Files by age and file extension

'http://www.wisesoft.co.uk/scripts/vbscript_delete_files_by_age_and_file_extension.aspx
OPTION EXPLICIT
DIM strExtensionsToDelete,strFolder
DIM objFSO, MaxAge, IncludeSubFolders

' ************************************************************
' Setup
' ************************************************************

' Folder to delete files
strFolder = "C:\test\"
' Delete files from sub-folders?
includeSubfolders = TRUE
' A comma separated list of file extensions
' Files with extensions provided in the list below will be deleted
strExtensionsToDelete = "tmp,temp"
' Max File Age (in Days).  Files older than this will be deleted.
maxAge = 10

' ************************************************************

SET objFSO = CREATEOBJECT("Scripting.FileSystemObject")

DeleteFiles strFolder,strExtensionsToDelete, maxAge, includeSubFolders

wscript.echo "Finished"

SUB DeleteFiles(BYVAL strDirectory,BYVAL strExtensionsToDelete,BYVAL maxAge,includeSubFolders)
	DIM objFolder, objSubFolder, objFile
	DIM strExt

	SET objFolder = objFSO.GetFolder(strDirectory)
	FOR EACH objFile in objFolder.Files
		FOR EACH strExt in SPLIT(UCASE(strExtensionsToDelete),",")
			IF RIGHT(UCASE(objFile.Path),LEN(strExt)+1) = "." & strExt THEN
				IF objFile.DateLastModified < (NOW - MaxAge) THEN
					wscript.echo "Deleting:" & objFile.Path & " | " & objFile.DateLastModified 
					objFile.Delete
					EXIT FOR
				END IF
			END IF
		NEXT
	NEXT	
	IF includeSubFolders = TRUE THEN ' Recursive delete
		FOR EACH objSubFolder in objFolder.SubFolders
			DeleteFiles objSubFolder.Path,strExtensionsToDelete,maxAge, includeSubFolders
		NEXT
	END IF
END SUB

Open in new window

0
mash1978ITAuthor Commented:
I found script but without folder exclusion

'VB Script to delete files requires exclusion parameter
'http://www.experts-exchange.com/Programming/Languages/Visual_Basic/VB_Script/Q_23104974.html

'=======================
' Create a FileSystemObject
Set fso = CreateObject("Scripting.FileSystemObject")

' Enter your folder to start deleting files from
startFolder = "D:\test movies\"
startFolder = "C:\temp\Scripts\TestFiles"

' Enter the names of folders to exclude from checking:
arrFoldersToExclude = Array("2","3")
strFoldersToExclude = ";" & Join(arrFoldersToExclude, ";") & ";"
arrFilesToExclude = Array("ds_store","do_not_delete.txt")
strFilesToExclude = ";" & Join(arrFilesToExclude, ";") & ";"

' This sets the amount of days old for files to be, before
' they are deleted.  The number must be negative.
OlderThanDate = DateAdd("d", -30, 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)

      ' Check if the current folder name is in the strFoldersToExclude String
      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
                        If InStr(LCase(strFilesToExclude), ";" & LCase(file.Name) & ";") = 0 Then
                              fso.DeleteFile(file.Path)
                        End If
                  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
            DeleteOldFiles subFolder.Path, BeforeDate
      Next
End Function
'=======================

Open in new window

0
mash1978ITAuthor Commented:
I found script but without folder exclusion
'********************************************************************************
' Cleanup old files depending on the age of x days, folder and file extension
' http://www.wisesoft.co.uk/scripts/vbscript_cleanup_old_files_depending_on_the_age_of_x_days_folder_and_file_extension.aspx
' File System Scripts
' http://www.wisesoft.co.uk/scripts/file_system/vbscript.aspx
'********************************************************************************

'********************************************************************************
' name:     Cleanup.vbs
' function: Cleanup old files depending on the age of X days, folder and file ext
' options:  /dir:*  /days:* /? (*=requiered)
' author:   Pinkel
' version:  1.1
' date:     01-04-2011
' correction date: 03-11-2011
' correction author: superurbi
'********************************************************************************
OPTION EXPLICIT
DIM wshArgs, wshShell
DIM FilePath, Retention, FileFilter, FilterExt
DIM fso, writelog, Folder, xFileDelete, xErrorDelete
SET wshArgs = wscript.arguments
SET wshShell = wscript.CREATEOBJECT("wscript.shell")
SET fso = CREATEOBJECT("Scripting.FileSystemObject")
IF ChkArgs = TRUE THEN
	FilePath = wshArgs.named.item("dir")
	Retention = wshArgs.named.item("days")
	FilterExt = wshArgs.named.item("ext")
	SET writelog = fso.OpenTextFile( FilePath & "\" & GetLogName(), 8, TRUE)
	writelog.writeline "Operation cleanup started in " & FilePath & " on " & DATE & ", at " & TIME & "."
	writelog.writeline "Cleaning files from " & FilePath & " older then " & Retention & " days."
	DelFiles FilePath, Retention, FileFilter
	writelog.writeline "Operation cleunup finished in " & FilePath & " on " & DATE & ", at " & TIME & "."
ELSE
	ShowUsage 1
	wshShell.LogEvent 2, "Operation cleanup failed (Cleanup.VBS). Requiered options are missing."
	wscript.echo "Operation cleanup FAILED!"
	wscript.echo "Requiered options are missing."
END IF
SET wshArgs = NOTHING
SET wshShell = NOTHING
SET fso = NOTHING
FilePath = ""
Retention = ""
FUNCTION ChkArgs
	DIM PathArg, DaysArg, ExtArg, HelpArg
	PathArg = wshArgs.Named.exists("dir")
	DaysArg = wshArgs.named.exists("days")
	ExtArg = wshArgs.named.exists("ext")
	HelpArg = wshArgs.named.exists("?")
	IF HelpArg = TRUE THEN
		ShowUsage 0
		wscript.quit
	END IF
	IF PathArg = TRUE AND DaysArg = TRUE THEN 
		ChkArgs = TRUE
	ELSE
		ChkArgs = FALSE
	END IF
	IF ExtArg = TRUE THEN
		FileFilter = TRUE
	ELSE
		FileFilter = FALSE
	END IF
END FUNCTION
FUNCTION GetLogName
	GetLogName = YEAR(NOW()) & MONTH(NOW()) & DAY(NOW()) & "-optuim.log"
END FUNCTION
SUB ShowUsage(Mode)
	wscript.echo "CLEANUP.VBS ussage:" & _
	vbcrlf & _
	vbcrlf & _
	" Cleanup.vbs /dir:[path] /days:[older than x days] /ext:[file extension]" & _
	vbcrlf & _
	"path = Folder location of the files." & _
	vbcrlf & _
	"older then x days = Required life time of files, older files will be deleted." & _
	vbcrlf & _
	"file extension = option: Cleaning files with an exention (only the extension, no dot)" & _
	vbcrlf & _
	"All files older than x days, will be deleted." 
	IF Mode = 0 THEN
		wscript.quit
	ELSE
	END IF
END SUB
SUB DelFiles(Dir, days, DelFilter)
	DIM DelDate, FSO, Folder, SubFolder, SubDir, Files, File, FileDate, Ext, FileDelete, ErrorDelete
	SET FSO = CREATEOBJECT("scripting.filesystemobject")
	ON ERROR RESUME NEXT
	SET Folder = FSO.GetFolder(Dir)
	IF Err.Number = 76 THEN
		wscript.echo "Operation cleanup FAILED! - Folder not found."
		wshShell.LogEvent 2, "Operation cleanup FAILED! (Cleanup.VBS) - Folder not found."
		wscript.quit
	END IF
	ErrorDelete = 0
	FileDelete = 0
	DelDate = NOW - days
	ON ERROR GOTO 0
	SET Files = Folder.Files
	SET SubFolder = Folder.SubFolders
	FOR EACH File in Files
		FileDate = File.DateLastModified
		Ext = FSO.GetExtensionName(File)
		ON ERROR RESUME NEXT
		IF DelFilter = TRUE THEN
			IF FileDate <= DelDate AND Ext = FilterExt THEN
				File.Delete
				FileDelete = FileDelete + 1
			END IF
			ELSE
			IF FileDate <= DelDate THEN
				File.Delete
				FileDelete = FileDelete + 1
			END IF
		END IF
		IF Err.Number = 70 THEN
			wscript.echo "File " & Dir & "\" & File.Name & _
			" not deleted: Failed - ACCESS DENIED!"
			wshShell.LogEvent 2, "File " & Dir & "\" & _
			File.Name & " not deleted: Failed - ACCESS DENIED! (Cleanup.VBS)"
			writelog.writeline "File " & Dir & "\" & File.Name
			writelog.writeline " not deleted: Failed - ACCESS DENIED!" & TIME
			ErrorDelete = ErrorDelete + 1
		END IF
		ON ERROR GOTO 0
	NEXT
	
	FOR EACH SubDir in SubFolder
		DelFiles SubDir.Path, days, DelFilter
	NEXT
	
	writelog.writeline FileDelete & " files deleted from folder " & Dir & "."
	writelog.writeline ErrorDelete & " errors found."
	
	SET Files = NOTHING
	SET Folder = NOTHING
	SET FSO = NOTHING
	FileDelete = ""
	ErrorDelete = ""
END SUB

Open in new window

0
10 Tips to Protect Your Business from Ransomware

Did you know that ransomware is the most widespread, destructive malware in the world today? It accounts for 39% of all security breaches, with ransomware gangsters projected to make $11.5B in profits from online extortion by 2019.

arnoldCommented:
Pick one.
Then there are different ways to check the found folders on whether they match the pattern of excluded if the pattern is matched,might.e. Excluded folder issue a next, meaning skip processing.

In the last script, you would add a check before calling the delete function.
Foreach subfolder in folders
If  Pattern match test next
   Delete subfolder
Next
0
mash1978ITAuthor Commented:
not able to understand as I am not programmer.
0
arnoldCommented:
In the script from http://www.experts-exchange.com/OS/Microsoft_Operating_Systems/Q_28265820.html#a39569404, you need to add the folder names you want to exclude in the line

' Enter the names of folders to exclude from checking:
arrFoldersToExclude = Array("2","3","windows","users")
etc.

Test first before unleashing it.
0
Bill PrewCommented:
I could work something up, but your original question is not specific enough, you mention scanning, skipping, deleting, etc.  I would need to know in more detail exactly what you want a script to do?  Are you deleting folders?  And subfolders? Or files? Under what conditions? Do you want to just list files or folders found that match, or process them somehow, etc?

There are a lot of details missing from the original question given that you seem to want to do multiple things in the script, please be more precise.

~bp
0
mash1978ITAuthor Commented:
Deleting Files having particular extensions like "PDF" , "JPG" , "TIF" , "XML"  having creation or modified date older than "x" days , but want to exclude particular system  folders like
"Windows" , " Program Files" etc.
0
mash1978ITAuthor Commented:
still searching for solution
0
Bill PrewCommented:
Sorry, been wrapped up on other things, will try and work something up tomorrow.

~bp
0
mash1978ITAuthor Commented:
any update
0
RobSampsonCommented:
Hi, you can try this as a modification of one of the scripts you posted.

Please test it on a test set of files first

Set your required modified date here, by changing the -30:
OlderThanDate = DateAdd("d", -30, Date)  ' (adjust as necessary)

Set your folders to exclude here, by adding more of the same lines as necessary:
dctFoldersToExclude.Add "Windows", 0
dctFoldersToExclude.Add "Program Files", 0

And set your file types to include here, by adding more of the same lines as necessary:
dctFilesToInclude.Add "PDF", 0
dctFilesToInclude.Add "JPG", 0
dctFilesToInclude.Add "TIF", 0
dctFilesToInclude.Add "XML", 0


Regards,

Rob.

' Create a FileSystemObject
Set fso = CreateObject("Scripting.FileSystemObject")

' Enter your folder to start deleting files from
startFolder = "C:\temp\Scripts\TestFiles"

' Enter the names of folders to exclude from checking:
Set dctFoldersToExclude = CreateObject("Scripting.Dictionary")
dctFoldersToExclude.CompareMode = vbTextCompare
dctFoldersToExclude.Add "Windows", 0
dctFoldersToExclude.Add "Program Files", 0

' Enter the names of file extensions to include:
Set dctFilesToInclude = CreateObject("Scripting.Dictionary")
dctFilesToInclude.CompareMode = vbTextCompare
dctFilesToInclude.Add "PDF", 0
dctFilesToInclude.Add "JPG", 0
dctFilesToInclude.Add "TIF", 0
dctFilesToInclude.Add "XML", 0

' This sets the amount of days old for files to be, before
' they are deleted.  The number must be negative.
OlderThanDate = DateAdd("d", -30, Date)  ' (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)

      ' Check if the current folder name is in the strFoldersToExclude String
      If dctFoldersToExclude.Exists(folder.Name) = False 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
                        If dctFilesToInclude.Exists(fso.GetExtensionName(file.Path)) = True Then
                              fso.DeleteFile(file.Path)
                        End If
                  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
            DeleteOldFiles subFolder.Path, BeforeDate
      Next
End Function

Open in new window

0
Bill PrewCommented:
I had started this last night, so I'll post the finished version now.  I think it meets the original ask.  I added some logic so that it skips over any folders that it can't access, and I also checked both dates as asked.

Right now it only displays the files that would be deleted, the actual delete is commented out.  This will allow some testing and then if it looks good you can uncomment the delete.

Adjust the constants and dictionary entries near the top as needed.

' Define the folder to scan, and the age of files to delete
Const strBaseDir = "C:\Temp"
Const intAge = 30

' Create a dictionary to hold the list of extensions to delete
Set dicExt = CreateObject("Scripting.Dictionary")
dicExt.CompareMode = vbTextCompare

' Add the extensions to the dictionary
dicExt.Add "pdf", 0
dicExt.Add "jpg", 0
dicExt.Add "tif", 0
dicExt.Add "xml", 0

' Create a dictionary to hold the list of folders to skip
Set dicSkip = CreateObject("Scripting.Dictionary")
dicSkip.CompareMode = vbTextCompare

' Add the folders to the dictionary
dicSkip.Add "Windows", 0
dicSkip.Add "Program Files", 0

' Set up filesystem object for usage
Set objFSO = CreateObject("Scripting.FileSystemObject")

' Look for files
FindFiles objFSO.GetFolder(strBaseDir)

' Subroutine (recursive) to search for files to delete
Sub FindFiles(objFolder)
   On Error Resume Next

   ' Skip any folders we don't want to process
   If Not dicSkip.Exists(objFolder.Name) Then

       ' Look at all files in this folder
       For Each objFile In objFolder.Files
           ' Make sure it's one of the extensions we want to delete
           If dicExt.Exists(objFSO.GetExtensionName(objFile.Path)) Then
              ' See if it's old enough to delete
              If DateDiff("d", objFile.DateLastModified, Now) > intAge Or DateDiff("d", objFile.DateCreated, Now) > intAge Then
                 'objFile.Delete
                 WScript.StdOut.WriteLine "Deleted:" & objFile.Path
              End If
           End If
       Next

       ' See if we were able to access this folder, if not don't recurse into it
       If Err.Number = 0 Then
           ' Recursively drill down into subfolder
           For Each objSubFolder In objFolder.SubFolders
               FindFiles objSubFolder
           Next
       End If

   End If
End Sub

Open in new window

~bp
0
RobSampsonCommented:
Bill, good idea to check for permissions issues, there will be some if searching an entire drive.
0
mash1978ITAuthor Commented:
Thanks Bill and Rob , I used Rob script for deletion and modified script as follows for to exclude folder and their sub-folders  ( tried to include delete read only files but not able to)

Kindly correct if any thing wrong in script
----------------------------------------------------------------------------------

Const DeleteReadOnly = True

' Create a FileSystemObject
Set fso = CreateObject("Scripting.FileSystemObject")

' Enter your folder to start deleting files from
startFolder = "C:\TEST_DELETE\"

' Enter the names of folders to exclude from checking:
Set dctFoldersToExclude = CreateObject("Scripting.Dictionary")
dctFoldersToExclude.CompareMode = vbTextCompare
dctFoldersToExclude.Add "folder_exclude", 0
dctFoldersToExclude.Add "Tets_not_delete", 0

' Enter the names of file extensions to include:
Set dctFilesToInclude = CreateObject("Scripting.Dictionary")
dctFilesToInclude.CompareMode = vbTextCompare
dctFilesToInclude.Add "PDF", 0
dctFilesToInclude.Add "JPG", 0
dctFilesToInclude.Add "TIF", 0
dctFilesToInclude.Add "XML", 0

' This sets the amount of days old for files to be, before
' they are deleted.  The number must be negative.
OlderThanDate = DateAdd("d", -4, Date)  ' (adjust as necessary)

   On Error Resume Next

' 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)

   On Error Resume Next

      ' Check if the current folder name is in the strFoldersToExclude String
      If dctFoldersToExclude.Exists(folder.Name) = False 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
                        If dctFilesToInclude.Exists(fso.GetExtensionName(file.Path)) = True Then
                              fso.DeleteFile(file.Path)

                        End If
                  End If
            Next
      End If

   On Error Resume Next

      ' Get the next collection of SubFolders to go through
If dctFoldersToExclude.Exists(folder.Name) = False Then

      Set folderCollection = folder.SubFolders

      ' Go through each subFolder
      For Each subFolder In folderCollection

  If dctFilesToInclude.Exists(fso.GetExtensionName(file.Path)) = True Then
            DeleteOldFiles subFolder.Path, BeforeDate

 End If

   On Error Resume Next

      Next
 End If

End Function
--------------------------------------------------------------------------------------
0
RobSampsonCommented:
Hi, this is a slightly cleaner version of your code, with the DeleteReadyOnly flag included.

Regards,

Rob.

Const DeleteReadOnly = True

' Create a FileSystemObject
Set fso = CreateObject("Scripting.FileSystemObject")

' Enter your folder to start deleting files from
startFolder = "C:\TEST_DELETE\"

' Enter the names of folders to exclude from checking:
Set dctFoldersToExclude = CreateObject("Scripting.Dictionary")
dctFoldersToExclude.CompareMode = vbTextCompare
dctFoldersToExclude.Add "folder_exclude", 0
dctFoldersToExclude.Add "Tets_not_delete", 0

' Enter the names of file extensions to include:
Set dctFilesToInclude = CreateObject("Scripting.Dictionary")
dctFilesToInclude.CompareMode = vbTextCompare
dctFilesToInclude.Add "PDF", 0
dctFilesToInclude.Add "JPG", 0
dctFilesToInclude.Add "TIF", 0
dctFilesToInclude.Add "XML", 0

' This sets the amount of days old for files to be, before
' they are deleted.  The number must be negative.
OlderThanDate = DateAdd("d", -4, Date)  ' (adjust as necessary)

On Error Resume Next

' 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)
	
	On Error Resume Next
	
	' Check if the current folder name is in the strFoldersToExclude String
	If dctFoldersToExclude.Exists(folder.Name) = False 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
				If dctFilesToInclude.Exists(fso.GetExtensionName(file.Path)) = True Then
					fso.DeleteFile file.Path, DeleteReadOnly
				End If
			End If
		Next
		Set folderCollection = folder.SubFolders

		' Go through each subFolder
		For Each subFolder In folderCollection
			If dctFoldersToExclude.Exists(subFolder.Name) = False Then
				DeleteOldFiles subFolder.Path, BeforeDate
			End If
		Next
	End If
End Function

Open in new window

0

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
mash1978ITAuthor Commented:
Thanks Rob script worked perfectly.

Thanks
0
mash1978ITAuthor Commented:
Thanks
0
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
Windows OS

From novice to tech pro — start learning today.