'File: CleanFiles.vbs
'Version: 1.0
'Author: Bennett Scharf
'For: File cleanup demoDemonstration
'Purpose: Used to clean up old files, temp files, logs, reports, etc
'Creation Date: 4 Nov 2004
'Revision Date: n/a
'Related Files: cscript.exe - WSH interpreter
'Operating System: W2k & later
'Usage: See DisplayUsage subroutine, below
'Exit codes: n/a
Option explicit
Const FORCE = 1 'Flag to force deletion of read only files
Dim strPathSpec, intAge , strSubFlag
If WScript.Arguments.Count = 3 Then
strPathSpec = WScript.Arguments.Item(0)
intAge = CInt(WScript.Arguments.Item(1))
strSubFlag = ucase(WScript.Arguments.Item(2))
If strSubFlag = "/S" Then
Call CleanSubDirs(strPathSpec)
Else
Call DisplayUsage
End If
Elseif WScript.Arguments.Count = 2 Then
strPathSpec = WScript.Arguments.Item(0)
intAge = CInt(WScript.Arguments.Item(1))
Call DeleteFiles( strPathSpec, intAge)
Else
Call DisplayUsage
End If
WScript.Quit
Sub DeleteFiles(strPathSpec, intAge)
Dim fso, objFolder, objFile, colFiles, intDiff
Set fso = CreateObject("Scripting.FileSystemObject")
If (fso.FolderExists(strPathSpec)) Then
Set objFolder = fso.GetFolder(strPathSpec)
Set colFiles = objFolder.Files
For Each objFile In colFiles
On Error Resume Next
intDiff = abs(DateDiff("d", Now, objFile.DateLastModified))
If intDiff > intAge Then
WScript.Echo( "Deleting " & strPathSpec & "\" & objFile.Name & " age: " & intDiff)
fso.DeleteFile strPathSpec & "\" & objFile.Name , FORCE
End If
On Error GoTo 0
Next
Set fso = Nothing
Set objFolder = Nothing
Set colFiles = Nothing
Else 'folder does not exist
WScript.Echo("Error: invalid path specified." & Chr(7))
WScript.Quit(1)
End If
End Sub
Sub CleanSubDirs(strPathSpec)
Dim fso, objFolder, objSubFolder, colFolders, objFile, colFiles, intDiff
Set fso = CreateObject("Scripting.FileSystemObject")
If (fso.FolderExists(strPathSpec)) Then
Set objFolder = fso.GetFolder(strPathSpec)
Set colFolders = objFolder.SubFolders
For Each objSubFolder In colFolders
DeleteFiles objSubFolder, intAge
Next
Else 'folder does not exist
WScript.Echo("Error: invalid path specified." & Chr(7))
WScript.Quit(1)
End If
Set fso = Nothing
Set objFolder = Nothing
Set colFiles = Nothing
Set colFolders = Nothing
End Sub
Sub DisplayUsage
WScript.echo "CleanFiles.vbs is used to delete files that are older than a specified number of days." _
& vbCrlf & vbCrlf & "There are 2 or 3 command line arguments:"_
& vbCrlf & " 1. A string that contains the path that you are deleting files from." _
& vbCrlf & " 2. An Int that specifies the number of days." _
& vbCrlf & " 3. A string /s -delete files in next-level subdirectories. "_
& vbCrlf & vbCrlf & "Example: cscript DeleteFiles.vbs d:\JunkFiles 20" & Chr(7)
Wscript.Quit
End Sub