This sample script (WHICH IS PROVIDED AS IS) may help purging files older than n days in a folder
Just copy the following code to a VBS file (DeleteOldFiles.vbs).
Sample call:
cscript DeleteOldFiles.vbs C:\Windows\Temp 90
The code is:
option explicit
Call DoTheJob()WScript.Echo "--- end of script execution ---"
Sub DoTheJob dim limitDate dim formattedLimitDate dim folder dim strComputer dim objWMIService dim colFileList dim objFile dim nbFiles dim totalFiles dim nbErrors dim result dim nbDays
if WScript.Arguments.Count <> 2 then WScript.Echo "usage : DeleteOldFiles.vbs <folder> <nb of days ago>" WScript.Echo "sample: DeleteOldFiles.vbs C:\Windows\temp 90" Exit Sub end if
folder = WScript.Arguments(0) nbDays = WScript.Arguments(1)
'calculate and format limit date limitDate = DateAdd("d", -1 * nbDays , Date)
formattedLimitDate = DatePart("yyyy", limitDate)
if DatePart("m", limitDate) < 10 then formattedLimitDate = formattedLimitDate & "0" end if formattedLimitDate = formattedLimitDate & DatePart("m", limitDate)
if DatePart("d", limitDate) < 10 then formattedLimitDate = formattedLimitDate & "0" end if formattedLimitDate = formattedLimitDate & DatePart("d", limitDate)
'show what will be done WScript.Echo "Will remove files from " & folder & " with a date older than " & formattedLimitDate & " (" & nbDays & " days ago)"
'Get the files and delete the old ones strComputer = "."
Set objWMIService = GetObject("winmgmts:" _ & "{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2")
Set colFileList = objWMIService.ExecQuery _ ("ASSOCIATORS OF {Win32_Directory.Name='" & folder & "'} Where " _ & "ResultClass = CIM_DataFile")
nbFiles = 0 totalFiles = 0 nbErrors = 0
For Each objFile In colFileList totalFiles = totalFiles + 1 if objFile.CreationDate < formattedLimitDate then result = objFile.Delete() WScript.Echo objFile.Name & " - " & objFile.CreationDate & ". Delete Result: " & result if result = 0 then nbFiles = nbFiles + 1 else nbErrors = nbErrors + 1 end if end if Next
'Show the result Wscript.Echo "Total files in folder: " & totalFiles WScript.Echo "Deleted files: " & nbFiles WScript.echo "Errors: " & nbErrorsEnd Sub
PingBack from http://itsupportjournal.com/2009/04/29/further-automate-disk-clean-up-by-scripting/