[THIN] Re: Deleting files X days old

  • From: "Christopher Checca" <chris@xxxxxxxxxx>
  • To: <thin@xxxxxxxxxxxxx>
  • Date: Thu, 21 Oct 2004 10:00:59 -0500

I like this one... it's a vbs script.


----------start code-----------

'~~[script]~~

' Script to delete all files older than a specified days w/detail logging
' Added provision for up to 10 filters on delete.
' Specify the date range, filter info and whether you
' want to actually delete the files.
'  Created - 02/18/2003 Christopher Checca

Option Explicit
Dim WSHShell, fs, Header, LogFile, LogName
Dim PCName, FilePath, File
Dim FDate, Count, DelCount, AllFilters, OlderThan
Dim DoDelete, ObjDirectory, TheFiles
Dim TimeIt, EndTime, StartTime
Dim FilterList(10)

Const ForReading = 1, ForWriting = 2

Set WSHShell = WScript.CreateObject("WScript.Shell")
Set fs = CreateObject("Scripting.FileSystemObject")
Header = WSHShell.ExpandEnvironmentStrings("%COMPUTERNAME%")
PCName = WSHShell.ExpandEnvironmentStrings("%COMPUTERNAME%")
Count = 0
DelCount = 0
AllFilters = 10
StartTime = Timer

' changeable Settings
LogName = "c:\Clean_IMail_Spool.LOG"


' Dont actually Delete the files, just log the ones that meet the criteria
' Change this to do the delete (TRUE = do it! or FALSE = don't do anything!)
DoDelete = TRUE


' path to start from and search anything below that
FilePath = "c:\imail\spool"
' ex: C:\TEMP

' date "olderthan" to delete
OlderThan = (Now() - (7)) ' older than 7 days

' File and directory filters  
' Populate FilterList
FilterList(1) = UCase("pagefile.sys")       ' system file
FilterList(2) = UCase(".dll")               ' system file
FilterList(3) = UCase(".exe")               ' dont delete any program files

   

'*****[ Script begin ]**************
' You can remove this POPUP if you are running this from cron
' WSHShell.Popup "Searching for Files Older than = " & CStr(OlderThan), 5,
Header, 64

' Open log file
StartLogging()
StartTime = Now()
LogEvent(" Searching for Files Older than = " & OlderThan)
LogEvent("  From " & FilePath & " on " & PCName & " @ " & Now())
Set ObjDirectory = fs.GetFolder(FilePath)
If NOT DoDelete Then
  LogEvent("   Files will not be Deleted.")
End If


' main subroutine
 Process ObjDirectory


LogEvent(" Total Files Counted = " & CStr(Count))
If DoDelete Then
  LogEvent(" Total Files Deleted = " & CStr(DelCount))
End If
EndTime = Timer
TimeIt = EndTime - StartTime
StopLogging()
Set fs = Nothing
' You can remove this POPUP if you are running this from cron
' WSHShell.Popup "Deleted files ... Completed.", 5, Header , 64
WshShell.LogEvent 0, "Clean_IMail_Spool - deleted files = " & CStr(DelCount)
wscript.Quit

 
' EOS '*******************
'*************************
'*************************

Sub RemoveFile(TheFile)
 Dim oFile
 DelCount = DelCount + 1
 Set oFile = fs.GetFile(theFile)
  on error resume next
 oFile.Delete
 LogEvent(TheFile & " -Deleted")
End Sub 'RemoveFile()


Function InFilter(AFile)
  Dim Z, TmpStr
  InFilter = FALSE
   For Z = 1 to AllFilters 
     TmpStr = CStr(FilterList(Z))
    If (Instr(UCase(AFile), TmpStr)> 1) Then
        InFilter = TRUE
    End If
  Next             
End Function 'InFilter


Sub Process(objDirectory)
 Dim MoreFolders, TempFolder
  Set TheFiles = objDirectory.Files

     For Each file in theFiles
            Count = Count +1        
            If FExist(File.Path) Then        
               IF NOT InFilter(File.Path) Then
                 FDate = GetFileDate(File.Path)
                 If (FDate < OlderThan) Then
                    If DoDelete Then
                      RemoveFile(File.Path)
                    Else
                      LogEvent(File.Path & " - " & FDate & " To Delete.")
                    End If
                 End If 
               End If            
            End If
        Next

 Set MoreFolders = objDirectory.SubFolders

 For Each TempFolder In MoreFolders
  Process TempFolder
 Next
End Sub   'Process()

Function GetFileDate(theFile)
  Dim oFile
  Set oFile = fs.GetFile(theFile)
  GetFileDate = oFile.DateLastModified
End Function 'GetFileDate()

Sub LogFileInfo()
' LogEvent(File.Path & " : " & FDate & ":   Is Older Than " & OlderThan)
 LogEvent(File.Path & " - " & FDate)
End Sub 'LogFileInfo()

Sub StartLogging()
On Error Resume Next
Set LogFile = fs.CreateTextFile(LogName,vbTrue)
 If (Err.Number <> 0) Then
     WSHShell.Popup "Could not create log file " & LogFile, 2, Header, 0
     Wscript.Quit(1)
 End If
LogFile.WriteLine " Logging Enabled : " & Now()
ScriptLoc = wscript.scriptfullname
LogFile.WriteLine " Script running from : " & ScriptLoc
End Sub 'StartLogging()

Sub StopLogging()
  On Error Resume Next
  LogFile.WriteLine " Logging Disabled : " & Now()
  LogFile.Close
End Sub

Sub LogEvent(StringtoWrite)
  on error resume next
  LogFile.WriteLine StringtoWrite
End Sub

Sub LogEventNoCR(StringtoWrite)
  on error resume next
  LogFile.Write StringtoWrite
End Sub

Sub show_msg(strText)
    MsgBox strText, vbInformation, Header
End Sub

Function FExist(filespec)                 ' File Exists
  FExist = FALSE
  If (fs.FileExists(filespec)) Then
    FExist = TRUE
  End If
End Function


-----------end code----------------

Christopher Checca
Packard Transport, Inc.
IT Department
24021 South Municipal Dr
PO Box 380
Channahon, IL.  60410
815 467 9260
815 467 6939 Fax
christopher.checca@xxxxxxxxxxxxxxxxxxxx
www.packardtransport.com
 

-----Original Message-----
From: thin-bounce@xxxxxxxxxxxxx [mailto:thin-bounce@xxxxxxxxxxxxx] On Behalf
Of David Demers
Sent: Thursday, October 21, 2004 8:49 AM
To: Thin (E-mail)
Subject: [THIN] Deleting files X days old

Hey guys,

I came across a need to regularly delete files over a certain age from a
folder. And while I am aware that there are better ways to acomplish this
task, I had some fun making this work in .bat form. I'm posting it here
incase someone else might find it usefull.

The limitations of it are:
-- It doesn't care what year it is, which isn't an issue in my usage of it
(regular pruning) as I will start with a manually cleaned folder.
-- During the first few days of March (dependant on how far back you want to
retain) it will think the files are a day younger than they really are
during leap years. Again not a big issue for my usage.

Other than that it seams sound. (Tested in Win2000 environment)

Usage:
Creat a scheduled task to kick off the file with the syntax of:

 Del_old Days "Folder"

Note: Not sure how text wrapping will effect this post.

============ Del_old.bat ================
@echo off
if {%2}=={} @echo Syntax:  Del_old.bat Days Folder&goto :EOF

SETLOCAL
REM ==== Grab Current Date ====
FOR /f "tokens=2-4 skip=1 delims=(-)" %%G IN ('echo.^|date') DO (
   FOR /f "tokens=2 delims= " %%A IN ('date /t') DO (
      SET v_first=%%G
      SET v_second=%%H
      SET v_third=%%I
      SET v_all=%%A
   )
)

SET %v_first%=%v_all:~0,2%
SET %v_second%=%v_all:~3,2%
SET %v_third%=%v_all:~6,4%
REM ==== The SET's above will be %mm% %dd% %yy% ====

REM ==== Incorporate Command Line Paramaters ====
SET days_old=%1
SET folder=%2#
SET folder=%folder:"=%
SET folder=%folder:\#=%
SET folder=%folder:#=%

REM ==== Convert to numerical date and assign Cut Off Date ====
CALL :JULIAN
echo Today's effective Julian Date: %julian_date%
SET /A cut_off_date=%julian_date%-%days_old%
echo Cut off date: %cut_off_date%

REM ==== Step through files in the directory ====
pushd "%folder%"
for /f "Tokens=*" %%G in ('dir /a /a-d /b') do (
 set file=%%G
 call :RESEARCH
)
popd
GOTO:EOF

REM ==== Sub Routine to determine numerical date ====
:JULIAN
IF /I "%mm%" EQU "01" SET month_in_days=365
IF /I "%mm%" EQU "02" SET month_in_days=31
IF /I "%mm%" EQU "03" SET month_in_days=59
IF /I "%mm%" EQU "04" SET month_in_days=90
IF /I "%mm%" EQU "05" SET month_in_days=120
IF /I "%mm%" EQU "06" SET month_in_days=151
IF /I "%mm%" EQU "07" SET month_in_days=181
IF /I "%mm%" EQU "08" SET month_in_days=212
IF /I "%mm%" EQU "09" SET month_in_days=243
IF /I "%mm%" EQU "10" SET month_in_days=273
IF /I "%mm%" EQU "11" SET month_in_days=304
IF /I "%mm%" EQU "12" SET month_in_days=334
SET /A julian_date=%month_in_days%+%dd%
GOTO:EOF

REM ==== Sub Routine to find date of files ====
:RESEARCH
for /f "Tokens=1-3 Delims=/ " %%a in ('dir "%file%" /a /tw^|Findstr /c:"/"')
do (
 set mm=%%a
 set dd=%%b
 call :JULIAN
 call :PERFORM
)
GOTO:EOF

REM ==== Sub Routine to delete files if necessary ====
:PERFORM
Echo Date: %julian_date% File: %file%
IF /i %julian_date% LEQ %cut_off_date% (
   echo Deleting file %file%
   del /q /f "%file%"
)
GOTO:EOF

ENDLOCAL

********************************************************
This Weeks Sponsor RTO Software
Do you know which applications are abusing your CPU and memory?
Would you like to learn? --   Free for a limited time!
Get the RTO Performance Analyzer to quickly learn the applications, users,
and time of day possible problems exist.
http://www.rtosoft.com/enter.asp?id20
********************************************************** 
Useful Thin Client Computing Links are available at:
http://thin.net/links.cfm
***********************************************************
For Archives, to Unsubscribe, Subscribe or 
set Digest or Vacation mode use the below link:
http://thin.net/citrixlist.cfm



********************************************************
This Weeks Sponsor RTO Software
Do you know which applications are abusing your CPU and memory?
Would you like to learn? --   Free for a limited time!
Get the RTO Performance Analyzer to quickly learn the applications, users,
and time of day possible problems exist.
http://www.rtosoft.com/enter.asp?id20
**********************************************************
Useful Thin Client Computing Links are available at:
http://thin.net/links.cfm
***********************************************************
For Archives, to Unsubscribe, Subscribe or
set Digest or Vacation mode use the below link:
http://thin.net/citrixlist.cfm

Other related posts: