Tuesday, October 04, 2005

My First Script

I’m looking at buying some backup software for the office.  It’s inexpensive and has some nice features (such as emailing results) but it comes up a little short in the logging department.  The program keeps a running log of backup jobs inside the program but creates a text log that only includes the results of the last backup.

For those of you who don’t understand scripting, don’t worry about it.  For those of you that do, I realize it’s simple (and if you have any suggestions for improvement, I’m all ears). I’m placing it here to share and to keep a record of it in case I ever have to rebuild it.

Here is my first VBScript that appends the contents of file A into file B -

'Define constants for opening text files
Const ForReading = 1
Const ForAppending = 8

'Create an instance of of the FileSystemObject (the scripting technology used to manipulate text files)
Set objFSO = CreateObject("Scripting.FileSystemObject")

'Define folder and file names as variables
strDirectory = "c:\logs"
strInFile = "\EXAMPLE.log"
strOutFile = "\OUTPUT.log"

'If output file doesn't exist, create it
If objFSO.FileExists(strDirectory & strOutFile) Then
Set objFolder = objFSO.GetFolder(strDirectory)
Else
Set objOutputFile = objFSO.CreateTextFile(strDirectory & strOutFile)
Wscript.Echo strDirectory & strFile & " created"
End If

'Open files and define aliases
Set objTextFile = objFSO.OpenTextFile(strDirectory & strInFile, ForReading)
Set objOutputFile = objFSO.OpenTextFile(strDirectory & strOutFile, ForAppending, True)

'Read contents of InFile and append to contents of OutFile
strSeparator = "------------------------------------------------"
strText = objTextFile.ReadAll
objTextFile.Close
objOutputFile.WriteLine
objOutputFile.WriteLine strSeparator
objOutputFile.WriteLine
objOutputFile.WriteLine strText

objOutputFile.Close

If you would like to test it, copy all of the blue and green text into notepad and save it somewhere as “appendlog.vbs”.  Create a “logs” folder on your C: drive and put a text file called “example.log” in there.  Make sure you have some text in the example.log file.  When that’s done, double-click the appendlog.vbs file. It will create the output.log file then copy the contents of the example.log file into it. Run it several times then check out your output.log file.

No comments: