Writing to Text Files

Microsoft® Windows® 2000 Scripting Guide

Writing data to a text file is another powerful aid in writing system administration scripts. Text files provide a way for you to permanently save data retrieved by a script; this data can be saved either instead of or in addition to being displayed on the screen. Text files also provide a way for you to keep a log of the actions carried out by a script. This can be especially useful when creating and debugging scripts. By having the script record its actions in a text file, you can later review the log to determine which procedures the script actually carried out and which ones it did not.

The FileSystemObject gives you the ability to write data to a text file. To write data using the FSO, a script must do the following:

  1. Create an instance of the FileSystemObject.

  2. Use the OpenTextFile method to open the text file. You can open the text file in one of two ways:

    • For writing (parameter value 2, constant = ForWriting). Files opened in this mode will have new data replace any existing data in its entirety. (That is, existing data will be deleted and the new data added.) Use this mode to replace an existing file with a new set of data.

    • For appending (parameter value 8, constant = ForAppending). Files opened in this mode will have new data appended to the end of the file. Use this mode to add data to an existing file.

  3. Use either the Write, WriteLine, or WriteBlankLines method to write to the file.

  4. Close the text file.

The three methods for writing to a text file are shown in Table 4.9.

Table 4.9 Write Methods Available to the FileSystemObject

Method

Description

Write

Writes data to a text file without appending a carriage-return/newline character at the end. For example, this code writes two separate strings to a text file:

objFile.Write ("This is line 1.")
objFile.Write ("This is line 2.")

The resulting text file looks like this:

This is line 1.This is line 2.

WriteLine

Writes data to a text file, appending a carriage-return/newline character at the end of each operation. For example, this code writes two separate strings to a text file:

objFile.WriteLine ("This is line 1.")
objFile.WriteLine ("This is line 2.")

The resulting text file looks like this:

This is line 1.
This is line 2.

WriteBlankLines

Writes a blank line to a text file. For example, this code writes two separate strings to a text file, separating the two with one blank line:

objFile.Writeline ("This is line 1.")
objFile.WriteBlankLines(1)
objFile.Writeline ("This is line 2.")

The resulting text file looks like this:

This is line 1.
This is line 2.

In addition to the methods shown in Table 4.9, the VBScript constant VbTab can be useful in writing data to text files. VbTab inserts a tab between characters. To create a tab-separated data file, use code similar to the following:

 objTextFile.WriteLine(objService.DisplayName & vbTab & objService.State)

One weakness with the FileSystemObject is that it cannot be used to directly modify specific lines in a text file; for example, you cannot write code that says, in effect, "Skip down to the fifth line in this file, make a change, and then save the new file." To modify line 5 in a 10-line text file, a script must instead:

  1. Read in the entire 10-line file.

  2. Write lines 1-4 back to the file.

  3. Write the modified line 5 to the file.

  4. Write lines 6-10 back to the file.

Overwriting Existing Data

In system administration, simplicity is often a virtue. For example, suppose you have a script that runs every night, retrieving events from the event logs on your domain controllers, writing those events to a database, and recording which computers were successfully contacted and which ones were not. For historical purposes, you might want to keep track of every success and every failure over the next year. This might be especially useful for a new script just being put into use, or for a network with suspect connectivity or other problems that crop up on a recurring basis.

On the other hand, you might simply want to know what happened the last time the script ran. In other words, you do not want a log file that contains data for the past 365 days. Instead, you want a log file that contains only the most recent information. That allows you to open the file and quickly verify whether or not the script ran as expected.

When you open a text file in ForWriting mode, any new data you write to the file replaces all the existing data in that file. For example, suppose you have the complete works of Shakespeare stored in a single text file. Suppose you then run a script that opens the file in ForWriting mode and writes the single letter a to the file. After the file has been written and closed, it will consist only of the letter a. All the previously saved data will be gone.

The script in Listing 4.42 opens the text file C:\FSO\ScriptLog.txt in ForWriting mode and then writes the current date and time to the file. Each time this script is run, the old date and time are replaced by the new date and time. The text file will never contain more than a single date-time value.

Listing 4.42 Overwriting Existing Data

  
1
2
3
4
5
Const ForWriting = 2
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objFile = objFSO.OpenTextFile("C:\FSO\ScriptLog.txt", ForWriting)
objFile.Write Now
objFile.Close

Appending New Data to Existing Data

Some scripts are designed to run at regularly scheduled intervals and then collect and save a specific kind of data. These scripts are often used to analyze trends and to look for usage over time. In these instances, you typically do not want to overwrite existing data with new data.

For example, suppose you have a script that monitors processor usage. At any given point in time, processor usage could be anywhere from 0 percent to 100 percent by itself, that single data point is meaningless. To get a complete picture of how much a processor is being utilized, you need to repeatedly measure and record processor usage. If you measure processor use every few seconds and get back data like 99 percent, 17 percent, 92 percent, 90 percent, 79 percent, 88 percent, 91 percent, you can assume processor use is very high. However, this can only be determined by comparing processor use over time.

By opening a text file in ForAppending mode, you can ensure that existing data is not overwritten by any new data; instead, that new data is appended to the bottom of the text file. For example, the script in Listing 4.43 opens a text file and writes the current date and time to the file. Because the file is opened for appending, the current date and time is simply added to the bottom of the file. If you run the script several times, you will end up with a text file similar to this:

6/25/2002 8:49:47 AM
6/25/2002 8:49:48 AM
6/25/2002 8:50:33 AM
6/25/2002 8:50:35 AM

Listing 4.43 Appending Data to a Text File

  
1
2
3
4
5
Const ForAppending = 8
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objFile = objFSO.OpenTextFile("C:\FSO\ScriptLog.txt", ForAppending)
objFile.WriteLine Now
objFile.Close

The script uses the WriteLine method to ensure that each new date and time entry is written to a separate line. If the script used the Write method instead, the entries would run together, and the text file would look like this:

6/25/2002 8:49:47 AM6/25/2002 8:49:48 AM6/25/2002 8:50:33 AM6/25/2002 8:50:35 AM