Friday, 16 August 2013

Deleting files using vbs without hard coding variables

Deleting files using vbs without hard coding variables

How can I modify following script in order to avoid hard coding location,
date-stamp and extension into it and specify those details as input
variables in command prompt like for example "cscript del.vbs d:\temp
16/08/2013 jpg".
OPTION EXPLICIT
DIM strExtensionsToDelete,strFolder
DIM objFSO, MaxAge, IncludeSubFolders
' ************************************************************
' Setup
' ************************************************************
' Folder to delete files
strFolder = "d:\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 = "jpg"
' Max File Age (in Days). Files older than this will be deleted.
maxAge = 1
' ************************************************************
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

No comments:

Post a Comment