Logging Events in WSH - Providing the Right Information
(Page 2 of 4 )
Administrators often run many different scripts. It would be useful to have the script identify itself in the log so you could tell easily which script log you were looking at. You may also be running the same script on many different machines, so we should record the machine name in our log file as well. WSH provides a way for us to do both.
object.ScriptFullname
object.ScriptName
object.ComputerName
The WshNetwork object’s ScriptFullName property returns the full path and file name of the currently running script. Its ScriptName property returns the file name by itself. The Wscript object has a ComputerName property that returns the computer name of the current machine.
Const logfile = "C:log.txt"
Set WshNetwork = CreateObject("Wscript.Network")
Set objFso = CreateObject("Scripting.FileSystemObject")
Set objLog = objFso.CreateTextFile(logfile, True)
objLog.WriteLine "Executing " & Wscript.ScriptFullName & " on " _
& WshNetwork.ComputerName
objLog.WriteLine "Execution of " & Wscript.ScriptName _
& " has completed."
Our log file is beginning to come together, but there are still a couple of important things we should take into consideration. First, we may not look at a log file for days or even weeks later so we should time stamp every event we write to it so that we can tell when the events occurred. Second, if we want to track this script every time it executes, we should append new data to our log file rather than overwriting it or creating a new one each time.
Const logfile = "C:log.txt"
Set WshNetwork = CreateObject("Wscript.Network")
Set objFso = CreateObject("Scripting.FileSystemObject")
If objFso.FileExists(logfile) Then
Set objLog = objFso.OpenTextFile(logfile, 8)
Else
Set objLog = objFso.CreateTextFile(logfile, True)
End If
objLog.WriteLine Time() & " " & Date() & " Executing " _
& Wscript.ScriptFullName & " on " & WshNetwork.ComputerName
objLog.WriteLine Time() & " Execution of " & Wscript.ScriptName _
& " has completed." & vbCrLf & vbCrLf
Here we’ve added an If statement to check and see if our log file exists. If it does we simply append new information to the existing file. If it doesn’t, we create a new one. Our last line has some added line feeds to be sure that each instance in our log file has some space between them for readability. Now our logging script produces this:
5:03:46 PM 2/12/2007 Executing C:logtest.vbs on DEVELOPE-J06OPO
5:03:46 PM Execution of logtext.vbs has completed.
I’ve used VBScript’s Date and Time functions to provide the appropriate time stamps. I’ve also take the time to make our messages a little prettier.
Next: Constructing the Subroutines >>
More Windows Scripting Articles
More By Nilpo/Developer Shed Staff Writer