Logging Events in WSH - Constructing the Subroutines
(Page 3 of 4 )
Now is a good time to package our code up nicely into subroutines so it can be reused easily throughout our script. The example subroutines you’ll be seeing here have some extra functionality added. For the sake of time and space I won’t be going into detail for all of them. You should have no problem seeing how they work.
Const logfile = "C:log.txt"
Dim startTime, startDate
Set objFso = CreateObject("Scripting.FileSystemObject")
Set WshNetwork = CreateObject("WScript.Network")
Call startLogging
Call stopLogging
Sub startLogging
startTime = Time()
startDate = Date()
writeLog(Date() & " Executing " & Wscript.ScriptFullName _
& " on " & WshNetwork.ComputerName)
End Sub
Sub stopLogging
writeLog(Date() & " Execution started at " & startTime & " on " _
& startDate & " has completed" & vbCrLf & vbCrLf)
End Sub
Sub writeLog(strEvent)
If objFso.FileExists(logfile) Then
Set objLog = objFso.OpenTextFile(logfile, 8)
Else
Set objLog = objFso.CreateTextFile(logfile, True)
End If
objLog.WriteLine Time() & " " & strEvent
objLog.Close
End Sub
Here’s what our subroutines should look like. Our first subroutine is the startLogging subroutine. This subroutine writes the first line of our log file. We can call this sub whenever we are ready to start logging data. The stopLogging sub writes the final line of our log session and then closes the file to save changes.
I’ve also created a writeLog subroutine to actually perform the writing operation on the log file. It accepts a single attribute in the form of a string to write to the file. Running the script now produces the following log.
5:12:12 PM 2/12/2007 Executing C:logging.vbs on DEVELOPE-J06OPO
5:12:12 PM 2/12/2007 Execution started at 5:12:12 PM on 2/12/2007 has completed
Next: Incorporating Logging into Your Script >>
More Windows Scripting Articles
More By Nilpo/Developer Shed Staff Writer