Creating a simple datestamp-timestamp named text file with VBScript

The VBScript code below creates a text file in your %TEMP% directory using datestamp and timestamp data as part of the file name. The file name uses the following format: YYYYMMDD-HHMMSS.txt.

It seems like I am forever writing log files for my VBScript projects, and this is a pretty good way of giving them meaningful and generally unique file names. Extend it to suit your purposes.

Option Explicit

'#########################################################
'##  Initialize global variables and objects
'#########################################################

Dim WshShell
Dim strSafeDate, strSafeTime, strDateTime, strLogFilePath, strLogFileName

Set WshShell = CreateObject("WScript.Shell")

strLogFilePath = WshShell.ExpandEnvironmentStrings("%TEMP%")

strSafeDate = DatePart("yyyy",Date) & Right("0" & DatePart("m",Date), 2) & Right("0" & DatePart("d",Date), 2)

strSafeTime = Right("0" & Hour(Now), 2) & Right("0" & Minute(Now), 2) & Right("0" & Second(Now), 2)

'Set strDateTime equal to a string representation of the current date and time, for use as part of a valid Windows filename
strDateTime = strSafeDate & "-" & strSafeTime

'Assemble the path and filename
strLogFileName = strLogFilePath & "\" & strDateTime & ".txt"

'Create the file and write a line of text to it
CreateLog strLogFileName, strDateTime

'******************************************************
'* Subroutine: CreateLog(strLogFileName,strEventInfo)
'*   Creates text file containing a line of text
'******************************************************
Sub CreateLog(strLogFileName,strEventInfo)
	'http://msdn.microsoft.com/en-us/library/5t9b5c0c(v=vs.84).aspx
   Dim objFSO, objTextFile
   Set objFSO = CreateObject("Scripting.FileSystemObject")
   Set objTextFile = objFSO.CreateTextFile(strLogFileName, True)
   objTextFile.WriteLine(strEventInfo)
   objTextFile.Close
End Sub

Easy peasy.

One thought on “Creating a simple datestamp-timestamp named text file with VBScript

Leave a Reply

Your email address will not be published. Required fields are marked *