Monthly Archives: November 2004

RecycleOldFiles

This VB script for Windows deletes files older than X days in a specified folder.
It is useful for recycling old log files, like IIS log files for example.
I used the example found here as a base and then modified it a bit.
Usage: Download, rename from .txt to .vbs , Set the constants sDirectoryPath to define which path to look for files in and iDaysOld to defined the max age for the files.

'=================================================================================================== 
'RecycleOldFiles.vbs
'
'Created by: See http://www.sqlservercentral.com/columnists/hji/usingvbscripttoautomatetasks.asp
'Modifed by: Goran Tornqvist. 
' 
'Description: 
'This script deletes files older than X days in a specified folder.
'It is useful for recycling old log files, like IIS log files for example.
'I used the example found here: http://www.sqlservercentral.com/columnists/hji/usingvbscripttoautomatetasks.asp
'as a base and then modified it a bit.  
'===================================================================================================

Option Explicit

Dim oFSO
Dim oFolder
Dim oFileCollection
Dim oFile
Dim strFiles
Dim objShell

Const EVENT_SUCCESS	= 0
Const EVENT_ERROR	= 1
Const EVENT_WARNING	= 2
Const EVENT_INFORMATION	= 4

Const iDaysOld = 30
Const sDirectoryPath = "C:\WINDOWS\System32\LogFiles\W3SVC100"

Set oFSO = CreateObject("Scripting.FileSystemObject")
set oFolder = oFSO.GetFolder(sDirectoryPath)
set oFileCollection = oFolder.Files

'Walk through each file in this folder collection.
'If it is older than iDaysOld days, then delete it.

strFiles = ""
For each oFile in oFileCollection
	If oFile.DateLastModified < (Date() - iDaysOld) Then
		strFiles = strFiles & oFile.Name & vbCrLf
		oFile.Delete(True)
	End If
Next

If strFiles <> "" Then
	Set objShell = CreateObject("WScript.Shell")
	objShell.LogEvent EVENT_INFORMATION, "Recycle Old Files" & vbCrLf & "The following files in directory " & sDirectoryPath & " are older than " & iDaysOld & " days and has been recycled: " & vbCrLf & strFiles
	Set objShell = Nothing
End If

'Clean up
Set oFSO = Nothing
Set oFolder = Nothing
Set oFileCollection = Nothing
Set oFile = Nothing