Tuesday, June 29, 2010

Script to do file cleanup

The following VBScript can be used to clean files of certain age:


-----------------------------

'* Specify the folder Name & Location here

Foldername="D:\DB Backup"

'* Specify how many days worth of Backup files you wanted to keep on the drive
Days = 7

'* Specify the Output fiel Name & location
LogFileName= "D:\CleanUp.txt"

Counter = 0

Set objFSO = CreateObject("Scripting.FileSystemObject")
Set LogFile=objFSO.OpenTextFile(LogFileName,2,true)

LogFile.WriteBlankLines 1
LogFile.Writeline " **************************************************"
LogFile.Writeline " * Delete Backup files Older than 7 Days *"
LogFile.Writeline " **************************************************"
LogFile.WriteBlankLines 1
LogFile.Writeline " Backup Folder Name .........: " & Foldername
LogFile.Writeline " Deleting files older then...: " & Days & " days"
LogFile.Writeline " Output File ................: " & LogFileName
LogFile.Writeline " Date Deleted ...............: " & Date
LogFile.WriteBlankLines 2

Counter = ViewSubFolders(Foldername, LogFile)

LogFile.WriteBlankLines 3
LogFile.Writeline "Total Old file(s) Deleted.....: " & Counter
LogFile.WriteBlankLines 3

LogFile.Close


Function checkFolder(Foldername, LogFile)
Set objFolder = objFSO.GetFolder(Foldername)
Counter = 0
For Each file in objFolder.Files
FileName=file.name
FileFullName=Foldername & "\" & filename
Set objFile = objFSO.GetFile(FileFullName)

LastModifiedDate=objFile.DateLastModified

LogFile.Writeline "Checking: " & FileName & "," & LastModifiedDate

IsOld=DateCheck(LastModifiedDate)

If IsOld="old" then
objFSO.DeleteFile(FileFullName)
Counter = Counter + 1
LogFile.Writeline "Deleting: " & FileName & "," & LastModifiedDate
end if

FileName=null
FileFullName= null
LastModifiedDate= null
IsOld= null
Set objFile = Nothing
Next

checkFolder = Counter
End Function

Function ViewSubFolders(strFolder, LogFile)
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objFolder = objFSO.GetFolder(strFolder)

Counter = 0

CounterX = checkFolder(strFolder, LogFile)
Counter = Counter + CounterX

For Each SubFolder in objFolder.SubFolders
CounterY = ViewSubFolders(SubFolder,LogFile)
Counter = Counter + CounterY
Next

Set objFolder = Nothing
Set objFSO = Nothing

ViewSubFolders = Counter
End Function

Function DateCheck(Lastmodified)
If DateDiff("d", lastmodified,date) > Days Then
DateCheck="old"
else
DateCheck="new"
end if
end Function



---------------------------