Solved

VB Script to Scan A Log File For Certain Strings and Output them to a Text File

Posted on 2012-04-07
5
527 Views
Last Modified: 2012-04-09
Hi All,

Loving the site its been a fantastic experience so far, need a bit of help with a script im trying to compile but getting nowhere with,
The Scenario:

I have a log file which is generated by a Windows Server but is very clumsy to read, Every morning my team have to open this file and search for certain lines, this confirms whether or not a certain scheduled task has been successful or not, I want to make this much more streamlined, I would like a VB Script that can read the log file and scan it for certain sentences/messages and output that whole line into a seperate text file

I would like each occurance piped to a text file so that in essence its just a text file with the important bits I need

To summarize:

A vbs script to read Scheduledtasklog.txt and look for 4 strings

"task one was completed successfully"
"task two was completed successfully"
"task 3 was completed successfully"
"The Scheduled Task Fund Loader Was Successfull 948 Records were processed."

Each time it finds one export them to a seperate log file called clean.txt the lines may appear more than once and the last one will contain a different value every day

Only other thing worth noting is that each message has its own line in the big log file if that makes writing the script any easier?

Thanks guys, REALLY APPRECITATED
0
Comment
Question by:crm84
5 Comments
 
LVL 45

Expert Comment

by:aikimark
ID: 37820299
You might want to use the Log Parser utility from Microsoft
http://www.microsoft.com/download/en/details.aspx?displaylang=en&id=24659
0
 

Author Comment

by:crm84
ID: 37820311
Hi there, alkimark,

I had checked this one to begin with and it doesnt have the option to repeat outputs, and would prefer VB and installing apps is restricted in our company,

RED tape everywhere!
0
 
LVL 10

Accepted Solution

by:
rscottvan earned 500 total points
ID: 37820319
Give this a try (search strings are case sensitive.)  Save it in the same folder as the Scheduledtasklog.txt file.

I obviously can't test on your log file, so let me know if you need some tweaks.

option explicit
on error resume next

'global vars, arrays, constants, objects
Dim oShell : Set oShell = CreateObject("WScript.Shell")
Dim oFSO : Set oFSO = CreateObject("Scripting.FileSystemObject")
Dim oArgs : Set oArgs = WScript.Arguments
Dim oHTMLLogFile
Dim sScriptPath : sScriptPath=mid(WScript.ScriptFullName,1,InStr(1,WScript.ScriptFullName, WScript.ScriptName,1)-2)
Dim sLogFile : sLogFile = "Scheduledtasklog.txt"
Dim sLineFromFile



'*******************************************************************************************************************************************
'*******************************************************************************************************************************************
'*******************************************************************************************************************************************
'***  Main Script  *************************************************************************************************************************
'*******************************************************************************************************************************************
'*******************************************************************************************************************************************
'*******************************************************************************************************************************************
Relaunch

'open a file to log to
OpenLogFile sScriptPath,"LogParser"

Dim oLogFile : Set oLogFile = oFSO.OpenTextFile(sScriptPath & "\" & sLogFile ,1)
errorcheck "opened Scheduledtasklog.txt for parsing"
Dim oOutput : Set oOutput = oFSO.OpenTextFile(sScriptPath & "\Results.txt" ,2,true)

Do Until oLogFile.AtEndOfStream
	on error resume next
	sLineFromFile = oLogFile.Readline
	If Instr(sLineFromFile,"task one was completed successfully") then 
		oOutput.WriteLine sLineFromFile
		errorcheck sLineFromFile
	ElseIf Instr(sLineFromFile,"task two was completed successfully") then 
		oOutput.WriteLine sLineFromFile
		errorcheck sLineFromFile
	ElseIf Instr(sLineFromFile,"task 3 was completed successfully") then 
		oOutput.WriteLine sLineFromFile
		errorcheck sLineFromFile 
	ElseIf Instr(sLineFromFile,"The Scheduled Task Fund Loader Was Successfull 948 Records were processed.") then 
		oOutput.WriteLine sLineFromFile
		errorcheck sLineFromFile
	End If
Loop

'close the log file
CloseLogFile
'*******************************************************************************************************************************************
'*******************************************************************************************************************************************
'*******************************************************************************************************************************************
'***  End Main Script  *********************************************************************************************************************
'*******************************************************************************************************************************************
'*******************************************************************************************************************************************
'*******************************************************************************************************************************************









'*******************************************************************************************************************************************
'*******************************************************************************************************************************************
'*******************************************************************************************************************************************
'***  Subroutines  *************************************************************************************************************************
'*******************************************************************************************************************************************
'*******************************************************************************************************************************************
'*******************************************************************************************************************************************









'*******************************************************************************************************************************************
'***  Relaunch using cscript engine  *******************************************************************************************************
'*******************************************************************************************************************************************
Sub ReLaunch
  on error resume next
  Set oShell = CreateObject("WScript.Shell")
  'Determine which script host was used to execute the script
  Dim sScriptHost : sScriptHost = UCase(Right(WScript.FullName, _
  	LEN(WScript.FullName) - InStrRev(WScript.FullName, "\")))

  'If the command line interface wasn't used, relaunch using CSCRIPT
  If uCase(sScriptHost) <> "CSCRIPT.EXE" Then
	Dim nCounter
  	Dim oArg : For each oArg in WScript.Arguments
  		Dim sArgString : sArgString = sArgString & WScript.Arguments(nNodeCounter) & " "
  		nCounter = nCounter + 1
  	Next
  	oShell.Run "CSCRIPT.EXE """ & WScript.ScriptFullName & """ " & sArgString
  	Set oShell = Nothing
  	WScript.Quit
  End If
End Sub
'*******************************************************************************************************************************************
'*******************************************************************************************************************************************
'*******************************************************************************************************************************************









'*******************************************************************************************************************************************
'***  Subroutine to open the log file  *****************************************************************************************************
'*******************************************************************************************************************************************
Sub OpenLogFile (sLogPath,sLogHeader)
	On Error Resume Next
	'verify the needed log folder exists.  create if necessary
	CreatePath sLogPath
	'split today's date into day and month and year
	Dim aDate : aDate = Split(Date(),"/")
	Dim sLogFileName : sLogFileName = sLogHeader & "_" & Right("0" & aDate(0),2) & "_" & Right("0" & aDate(1),2) & "_" & aDate(2) & ".htm"
	'determine if the file already exists (so we know later if we need to append
	'it, or if we need to start from scratch)
	If oFSO.FileExists(sLogPath & "\" & sLogFileName) then Dim bFileExists : bFileExists = True
	err.clear
	'open the log file
	Set oHTMLLogFile = oFSO.OpenTextFile (sLogPath & "\" & sLogFileName,8,True)
	If err.number <> 0 then
		MsgBox "We were unable to open a log file" & vblf & "(" & sLogPath & "\" & sLogFileName & ")" & vblf & " for writing.  Bailing out."& vblf & err.number & ":  " & err.Description
		WScript.Quit
	End If
	'create the header if needed
	If bFileExists <> True then
		oHTMLLogFile.WriteLine "<html><body>"
		oHTMLLogFile.WriteLine "<b>" & sLogHeader & " - " & Date() & "</b>"
	End If
	'now create the delimiter for this section of the file
	oHTMLLogFile.WriteLine "<hr>Script Started - " & Now() & " - <hr>"
	oHTMLLogFile.WriteLine "<table border=1 width=100%>"
End Sub
'*******************************************************************************************************************************************
'*******************************************************************************************************************************************
'*******************************************************************************************************************************************










'*******************************************************************************************************************************************
'***  Subroutine to close the log file  ****************************************************************************************************
'*******************************************************************************************************************************************
Sub CloseLogFile
	'write closing tags and close the log
	oHTMLLogFile.Writeline "</table>"
	oHTMLLogFile.WriteLine "<br><br>"
	oHTMLLogFile.WriteLine "<hr>Finished Processing - " & Now() & " - <hr>"
	oHTMLLogFile.Close
	Set oHTMLLogFile = Nothing
End Sub
'*******************************************************************************************************************************************
'*******************************************************************************************************************************************
'*******************************************************************************************************************************************










'*******************************************************************************************************************************************
'***  Subroutine to write success to the log  **********************************************************************************************
'*******************************************************************************************************************************************
Sub SuccessLog (sEvent)
	'write success to log file
	oHTMLLogFile.Write "<tr><td>" & Now() & "</td>"
	oHTMLLogFile.Write "<td>" & sEvent & "</td>"
	oHTMLLogFile.WriteLine "<td bgcolor=green><font color=white>SUCCESS</font></td></tr>"
End Sub
'*******************************************************************************************************************************************
'*******************************************************************************************************************************************
'*******************************************************************************************************************************************










'*******************************************************************************************************************************************
'***  Subroutine to write failure to the array  ********************************************************************************************
'*******************************************************************************************************************************************
Sub FailureLog (sEvent,nError,sErrorDescription)
	on error resume next
	'write failure to log
	oHTMLLogFile.Write "<tr><td>" & Now() & "</td>"
	oHTMLLogFile.Write "<td>" & sEvent & "</td>"
	oHTMLLogFile.WriteLine "<td bgcolor=red><font color=white>" & nError & ":  " & sErrorDescription & "</font></td></tr>"
End Sub
'*******************************************************************************************************************************************
'*******************************************************************************************************************************************
'*******************************************************************************************************************************************










'*******************************************************************************************************************************************
'***  Subroutine to check error status then write success or failure to the log  ***********************************************************
'*******************************************************************************************************************************************
Sub ErrorCheck (sEvent)
'check if we had an error
	If err.number = 0 then
		SuccessLog sEvent
	Else
		FailureLog sEvent,err.number,err.Description
	End If
	err.clear
End Sub
'*******************************************************************************************************************************************
'*******************************************************************************************************************************************
'*******************************************************************************************************************************************










'*******************************************************************************************************************************************
'***  Subroutine to create a path in the directory tree  ***********************************************************************************
'*******************************************************************************************************************************************
Sub CreatePath (sPathToCreate)
	on error resume next
	'split the path into an array
	Dim aPathToCreate : aPathToCreate = split(sPathToCreate,"\")
	'start the cumulative path string with the first value from the array
	Dim sCumulativePath : sCumulativePath = aPathToCreate(0)
	'loop through the array elements beginning with the second element,
	'since the first is already part of sCumulativePath
	Dim nLoop : For nLoop = 1 to uBound(aPathToCreate)
		'add the next element to the cumulative path
		sCumulativePath = sCumulativePath & "\" & aPathToCreate(nLoop)
		'check if the folder exists yet
		If Not oFSO.FolderExists (sCumulativePath) then
			'create the folder if needed
			oFSO.CreateFolder sCumulativePath
		End If
	Next
End Sub
'*******************************************************************************************************************************************
'*******************************************************************************************************************************************

Open in new window

0
 

Author Closing Comment

by:crm84
ID: 37820332
Tremendous 100% worked first time,

I could cry!
0
 
LVL 51

Expert Comment

by:Bill Prew
ID: 37823306
I know this is closed, but just wanted to mention that FINDSTR could probably do this easily as well, with a single command line.  Something like:
findstr /I /C:"task one was completed successfully" /C:"task two was completed successfully" /C:"task 3 was completed successfully" /C:"The Scheduled Task Fund Loader Was Successfull 948 Records were processed." inputfile.txt >errorfile.txt

Open in new window

You might want to play around with some of the options,but just wanted to pass this along in case it is ever something you can use.  At a command line you can do:

FINDSTR /?

to get more info on the options it supports.

~bp
0

Featured Post

How to run any project with ease

Manage projects of all sizes how you want. Great for personal to-do lists, project milestones, team priorities and launch plans.
- Combine task lists, docs, spreadsheets, and chat in one
- View and edit from mobile/offline
- Cut down on emails

Join & Write a Comment

Most everyone who has done any programming in VB6 knows that you can do something in code like Debug.Print MyVar and that when the program runs from the IDE, the value of MyVar will be displayed in the Immediate Window. Less well known is Debug.Asse…
This article is the result of a quest to better understand Task Scheduler 2.0 and all the newer objects available in vbscript in this version over  the limited options we had scripting in Task Scheduler 1.0.  As I started my journey of knowledge I f…
Get people started with the utilization of class modules. Class modules can be a powerful tool in Microsoft Access. They allow you to create self-contained objects that encapsulate functionality. They can easily hide the complexity of a process from…
Show developers how to use a criteria form to limit the data that appears on an Access report. It is a common requirement that users can specify the criteria for a report at runtime. The easiest way to accomplish this is using a criteria form that a…

705 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

16 Experts available now in Live!

Get 1:1 Help Now