A VBScript Tutorial for Writing or Appending to a File
This page deals specifically with writing data to a file using VBScript. Once you have successfully created your
FileSystemObject then you have the choice of reading, writing or appending data. Whilst my
examples are trivial, if you imagine this script as part of larger scripting project, then you will appreciate the power of the OpenTextFile.WriteLine method.
Topics for Writing or Appending to a File with VBScript
This page is the climax of
our three tasks. If you have been with me from the start, you may remember that we first created the parent folders. Then secondly, we created the child files, now here we are going to read, write or append text
data. (If necessary have a refresher on Part 1 or Part 2.)
This is the final part of our quest to control the output of a VBScript. Often, at least in testing, you can just echo output data to a message box. However, for complex production scripts, it
is far better to write that data into a text file using the OpenTextFile method.
I imagine that most of the time you want to write or append data to a text (.txt) file; if so then FileSystemObject
and OpenTextFile are the commands to learn. However, even though you can also amend OpenTextFile to read data; in my opinion, I would
prefer to employ the CreateObject("Excel.Application") method for reading text into a script. In summary, it's a case of horses for courses, OpenTextFile for writing, Excel.Application for
reading.
This is a long script, therefore I suggest that you break it up into sections. The best approach is to identify the create folder and create file sections, which are discussed on other pages (see menu
top left). Even though our mission is to write text to a file, our script must consider the folder's location and also remember that text has a parent object, the file. While the final
bonus or cosmetic section is not strictly necessary, I like file scripts to open explorer so that I can check what has happened.
Before we start, there are three
variations of the OpenTextFile method:
1) Reading the text.
2) Writing text (perhaps I should say over-writing text).
3) Appending data, as in the example below which we will examine in detail.
VBScript controls which variation of OpenTextFile you get with constants. 'CONST' is a VBScript subject in its own right. However, for the purposes of this script, I suggest that you just accept
the CONST values and focus on the OpenTextFile object and the .WriteLine method.
' OpenTextFile Method requires a Const value ' ForAppending = 8 ForReading = 1, ForWriting = 2 For this script I choose: ForAppending = 8
Prerequisites
This is a script that will execute equally well on a Windows server or an XP machine. Should you get permission errors, I recommend that you logon as
administrator.
Instructions for Creating Files
Copy and paste the example script below into notepad or a VBScript editor.
Decide whether to change the value for strDirectory, strFile and strText.
Save the file with a .vbs extension, for example: NewTextEC.vbs
Double click NewTextEC.vbs and check Windows Explorer for strDirectory.
Example Script to Append Text to a File
' NewTextEC.vbs ' Sample VBScript to write to a file. With added error-correcting ' Author Guy Thomas http://computerperformance.co.uk/ ' Version 1.5 - August 2005 '
---------------------------------------------------------------'
Option Explicit Dim objFSO, objFolder, objShell, objTextFile, objFile Dim strDirectory, strFile, strText strDirectory =
"e:\logs3" strFile = "\Summer.txt" strText = "Book Another Holiday"
' Create the File System Object Set objFSO = CreateObject("Scripting.FileSystemObject")
' Check that the
strDirectory folder exists If objFSO.FolderExists(strDirectory) Then Set objFolder = objFSO.GetFolder(strDirectory) Else Set objFolder = objFSO.CreateFolder(strDirectory)
WScript.Echo "Just created " & strDirectory End If
If objFSO.FileExists(strDirectory & strFile) Then Set objFolder = objFSO.GetFolder(strDirectory) Else Set objFile
= objFSO.CreateTextFile(strDirectory & strFile) Wscript.Echo "Just created " & strDirectory & strFile End If
set objFile = nothing set objFolder = nothing ' OpenTextFile Method
needs a Const value ' ForAppending = 8 ForReading = 1, ForWriting = 2 Const ForAppending = 8
Set objTextFile = objFSO.OpenTextFile _ (strDirectory & strFile, ForAppending, True)
' Writes
strText every time you run this VBScript objTextFile.WriteLine(strText) objTextFile.Close
' Bonus or cosmetic section to launch explorer to check file If err.number = vbEmpty then
Set objShell = CreateObject("WScript.Shell") objShell.run ("Explorer" &" " & strDirectory & "\" ) Else WScript.echo "VBScript Error: " & err.number End If
WScript.Quit
' End
of VBScript to write to a file with error-correcting Code
Note
2: As with many file scripts, the first task is to create an object. Once we have that crucial object then we can persuade it to manipulate the text, here is the classic FSO command: Set objFSO =
CreateObject("Scripting.FileSystemObject"). Once we create objFSO we can GetFolder and CreateTextFile.
Note 3: The central point of this script is the OpenTextFile method.
What we must also do is
control whether to read, write or append (as in this case). Examine carefully the CONST statement. This example uses: Const ForAppending = 8. However, if you wish to over-write the text
in the file, the command is ForWriting = 2, (not ForAppending = 2.
Note 4: You may well be asking, what is the point of an example such as this script? Well, try and imagine a
WMI script that has interrogated the operating system for disk information. Would it not be better to write the complex data to a file than merely echo the output to your screen?
Note 5: Without
adding these two lines this VBScript example fails with a permissions error: set objFile = nothing set objFolder = nothing
This is the definitive FSO script. I am sure that you will find many opportunities to adapt this VBScript code into a WMI script, or indeed any script which requires storing the output permanently in a file.
If you have
already learnt
how to create files and folders, then the OpenTextFile is the logical progression in controlling the data in the actual file. By configuring the 'CONST For xyz', you can append data or over-write the existing file.
The real power and joy of this FSO technique comes in projects where you want to store the output data permanently in a text file. Technically, the two key commands are FileSystemObject and
OpenTextFile.
Guy Thomas recommends
Computer Training Software. Their topics and material are ideal for getting you started with VBScript. The
videos are easy to follow and you can control the pace. Try their free demo material and then see if you want to buy the full package.
See more about VB Script Training CD.