Link to home
Start Free TrialLog in
Avatar of mash1978
mash1978Flag for India

asked on

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
Avatar of mash1978
mash1978
Flag of India image

ASKER

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

I found script but without folder exclusion

'VB Script to delete files requires exclusion parameter
'https://www.experts-exchange.com/questions/23104974/VB-Script-to-delete-files-requires-exclusion-parameter.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

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

Avatar of arnold
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
not able to understand as I am not programmer.
In the script from https://www.experts-exchange.com/questions/28265820/vbscript-delete-files-with-extensions.html?anchorAnswerId=39569404#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.
Avatar of Bill Prew
Bill Prew

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
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.
still searching for solution
Sorry, been wrapped up on other things, will try and work something up tomorrow.

~bp
any update
SOLUTION
Avatar of RobSampson
RobSampson
Flag of Australia image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Bill, good idea to check for permissions issues, there will be some if searching an entire drive.
SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
ASKER CERTIFIED SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Thanks Rob script worked perfectly.

Thanks
Thanks