VBscript: Sub WriteLog

Two versions of this script: a basic one which writes to a text file, and another which writes to a SQL table. The SQL option is needed if you are going to have any other processes using the log at the same time.

Const LOG_FILE = “log_file_path

Const ForReading = 1
Const ForWriting = 2
Const ForAppending = 8
 

Dim objFS, objLogFile

 

Set objFS = CreateObject(“Scripting.FileSystemObject”)
Set objLogFile = objFS.OpenTextFile(LOG_FILE, ForAppending, TRUE)

‘—————————————————–
‘  Sub WriteLog
‘  + Write messages to the log file
‘—————————————————–

Sub WriteLog(LogMessage)
  Dim objCon, sqlQuery

  wscript.echo Now() & “: ” & LogMessage
  objLogFile.Writeline(Now() & “: ” & LogMessage)

End Sub

 

 

Const DB_CONNECT_STRING = “Provider=SQLOLEDB;Data Source=(local);Initial Catalog=DB-name;Integrated Security=SSPI”

Const DB_TABLE_LOG = “log_table_name

‘—————————————————–
‘  Sub WriteLog
‘  + Write messages to the log table
‘—————————————————–

Sub WriteLog(LogMessage)
  Dim objCon, sqlQuery

  wscript.echo Now() & “: ” & LogMessage

  On error resume next
    Set objCon = CreateObject(“ADODB.Connection”) 
    objCon.Open(DB_CONNECT_STRING) 
    sqlQuery = “insert into ” & DB_TABLE_LOG & ” values (‘” & Now() & “‘,'” & LogMessage & “‘)” 
    objCon.Execute(sqlQuery) 
    objCon.Close
  On error goto 0

End Sub