Friday, October 1, 2010

VBScript: Easy output to a text file

When your script generates output a msgbox is seldom sufficient, especially if you want to maintain some kind of logfile or history.

Here are a couple of classes I wrote that make exporting output to a file simple and repeatable. These functions log text to a file one line at a time, with a return between each line. Not ideal for large output but sufficient for light to moderate logging needs.

'This version send output to a file in the same directory as then executing script,
'with a name the same as the script_Log.txt

Class Logger

Sub logThis(txtString)
Set objFSO = Createobject("Scripting.FileSystemObject")
objLogFile = Left(wscript.scriptname, Len(wscript.scriptname)-4) & "_Log.txt"
Set objfile1 = objFSO.OpenTextFile(objLogFile, 8, True)
objfile1.Write txtString
objfile1.Writeline
objfile1.close
end sub

end class


'Or if you need a little more flexibility as to where to put the file.

Class openLogger

Sub logThis(txtString, filePath)
Set objFSO = Createobject("Scripting.FileSystemObject")
Set objfile1 = objFSO.OpenTextFile(filePath, 8, True)
objfile1.Write txtString
objfile1.Writeline
objfile1.close
end sub

end class


To use one of these in a script, paste the class code somewhere at the bottom of the script and then define a variable as a member of that class in your main function and call the class sub.

Example, if you want to send the text "Computername: MZZ1005AH" to a text file you would do the following.

Set Worker = New Logger
Worker.logThis("Computername: MZZ1005AH")

Not flashy, but functional.

No comments: