Option Explicit

MsgBox "This program will trim lines from the beginning of a file until the file is below a designated size. You must pass a SHORT file name and a desired size on the command line:" & vbCrLf & "start /w TrimLogFiles.vbs C:\MYDOCU~1\BIGFILE.LOG 65535" & vbCrlf & "Please edit this file to remove this warning line. Then you can use this program!" : Wscript.Quit

'''''  This script reduces the size of line-oriented log files.
'''''  It erases the first (oldest) lines in a log file until
'''''  it gets the log down below the specified size. 
'''''  Usage: SCRIPTNAME FILENAME FILESIZE
'''''  Example: start /w TrimLogFiles.vbs c:\logs\server.log 32767
Dim ts 'As Scripting.TextStream
Dim fs 'As Scripting.FileSystemObject
Dim sText 'As String
Dim dDesiredSize 'As Double
Dim sFileName 'As String
Const MAXSIZE = 1000000
Const MINSIZE = 100
Const ForReading = 1 'Scripting.IOMode
Const ForWriting = 2 'Scripting.IOMode
	Set fs = CreateObject("Scripting.FileSystemObject")
	''''''''''This is a non-critical script. If it fails anywhere, just quit.
	On Error Resume Next
	''''''''''First check the filename and size arguments
	If Wscript.Arguments.Count <> 2 Then Wscript.Quit 1
	sFileName = Wscript.Arguments(0)
	dDesiredSize = CDbl(Wscript.Arguments(1))
	If Not fs.FileExists(sFileName) Then Wscript.Quit 1
	If dDesiredSize > MAXSIZE Then Wscript.Quit 1
	If dDesiredSize < MINSIZE Then Wscript.Quit 1
	''''''''''Read the file
	Set ts = fs.OpenTextFile(sFileName, ForReading)
	If Err.Number <> 0 Then 
		Set fs = Nothing
		Wscript.Quit 1
	End If
	sText = ts.ReadAll
	ts.Close
	''''''''''See if the file is already below desired size
	If Len(sText) < dDesiredSize Then
		sText = ""
		Set ts = Nothing
		Set fs = Nothing
		Wscript.Quit 0
	End If
	''''''''''Trim the file
	sText = Right(sText, dDesiredSize)
	If (Instr(sText, vbCrlf) = 0) Or (Instr(sText, vbCrlf) + 3 > Len(sText)) Then
		sText = ""
		Set ts = Nothing
		Set fs = Nothing
		Wscript.Quit 0
	Else
		sText = Mid(sText, Instr(sText, vbCrlf) + 2)
	End If
	''''''''''Write the shortened file
	Set ts = fs.OpenTextFile(sFileName, ForWriting)
	If Err.Number <> 0 Then 
		sText = ""
		Set ts = Nothing
		Set fs = Nothing
		Wscript.Quit 1
	End If
	ts.Write sText
	ts.Close
	sText = ""
	Set ts = Nothing
	Set fs = Nothing
	Wscript.Quit 0

