Export (0) Print
Expand All

Reading Text Files

Microsoft® Windows® 2000 Scripting Guide

Reading data from a text file is a standard procedure used in many enterprise scripts. You might use this capability to:

  • Read in command-line arguments. For example, a text file might contain a list of computers, with the script designed to read in the list and then run against each of those computers.

  • Programmatically search a log file for specified conditions. For example, you might search a log file for any operations marked Error.

  • Add the contents of a log file to a database. For example, you might have a service or an application that saves information in plain-text format. You could write a script that reads in the text file and then copies the relevant information to a database.

The FileSystemObject can be used to read the contents of a text file. When using the FileSystemObject, keep the following limitations in mind:

  • The FSO can read only ASCII text files. You cannot use the FSO to read Unicode files or to read binary file formats such as Microsoft Word or Microsoft Excel.

  • The FileSystemObject reads a text file in one direction: from the beginning to the end of the text file. In addition, the FSO reads only line by line. If you need to go back to a previous line, you must return to the beginning of the file and read forward to the required line.

  • You cannot open a file for simultaneous reading and writing. If you open a file for reading, you must open the file a second time if you want to modify the contents. If you attempt to read a file after opening it in write mode, you will receive a "bad file mode" error.

The file-reading methods available through the FileSystemObject are listed in Table 4.8. The examples shown in the table are based on a text file of services and service properties that looks similar to this:



Alerter,Share Process,Running,Auto,LocalSystem,
AppMgmt,Share Process,Running,Manual,LocalSystem,
Ati HotKey Poller,Own Process,Stopped,Auto,LocalSystem,

Table 4.8 Read Methods Available to the FileSystemObject

Method

Description

Read

Reads the specified number of characters and then stops. For example, the following command would read the first 12 characters of the first line ("Alerter,Shar") into the variable strText and then stop:strText = objTextFile.Read(12)

ReadLine

Reads one line from a text file and then stops before reaching the newline character. For example, the following command would read the first line ("Alerter,Share Process,Running,Auto,LocalSystem") into the variable strText and then stop:strText = objTextFile.ReadLine

To read an entire text file on a line-by-line basis, place the ReadLine function within a loop.

ReadAll

Reads the entire contents of a text file into a variable.

Skip

Skips the specified number of characters and then stops. For example, the following command would skip the first 12 characters. Any subsequent read operations would begin with the 13th character and continue from there ("e Process,Running,Auto,LocalSystem"):objTextFile.Skip(12)

SkipLine

Skips an entire line in a text file. For example, this code reads the first and third lines of a text file, skipping the second line:strText = objTextFile.Readline objTextFile.SkipLine strText = objTextFile.Readline

Verifying the Size of a File

Windows will sometimes create text files that are empty - that is, files that contain no characters and have a file size of 0 bytes. This often occurs with log files, which remain empty until a problem is recorded there. For example, if problems occur with a user logon (such as a user attempting to log on with an incorrect password or user account), those problems will be recorded in the Netlogon.log file. Until such a problem occurs, however, the Netlogon.log file remains empty.

Empty files represent a problem for script writers, because a VBScript run-time error will occur if you attempt to read such a file. If you try to read an empty file, an error message similar to the one shown in Figure 4.8 appears.

Figure 4.8 Empty File Error Message

sas_scr_08s

If there is a chance that a file might be empty, you can avoid errors by checking the file size before attempting to read the file. To do this, the script must:

  1. Create an instance of the FileSystemObject.

  2. Use the GetFile method to bind to the file.

  3. Use the Size property to ensure that the file is not empty before attempting open it.

The script in Listing 4.37 binds to the file C:\Windows\Netlogon.log. The script checks the size of the file; if the size is greater than 0, the script opens and reads the file. If the file size is 0, the script echoes the message "The file is empty."

Listing 4.37 Verifying the Size of a File

  
1
2
3
4
5
6
7
8
9
10


Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objFile = objFSO.GetFile("C:\Windows\Netlogon.log")
If objFile.Size > 0 Then
 Set objReadFile = objFSO.OpenTextFile("C:\Windows\Netlogon.log", 1)
 strContents = objReadFile.ReadAll
 Wscript.Echo strContents
 objReadFile.Close
Else
 Wscript.Echo "The file is empty."
End If

Reading an Entire Text File

The ReadAll method provides the easiest way to read a text file: You simply call the method, and the entire text file is read and stored in a variable. Having the contents of the text file stored in a single variable can be useful in a number of situations. For example, if you want to search the file for a particular item (such as an error code), it is easier to search a single string than to search the file line by line.

Likewise, if you want to concatenate (combine) text files, the ReadAll method provides the quickest and easiest method. For example, suppose you have a set of daily log files that you want to combine into a single weekly log file. To do that, a script can:

  1. Open the text file for Monday and use ReadAll to store the entire contents in a variable.

  2. Open the weekly log file for appending, and write the contents of the variable to the file. This is possible because any formatting (such as line breaks or tabs) that is read in from the Monday file is preserved in the variable.

  3. Repeat steps 1 and 2 until the entire set of daily files has been copied into the weekly log.

Note

  • Although it is easier to search a single string, it is not necessarily faster. The ReadAll method took less than a second to search a 388-KB test file of approximately 6,000 lines. Reading and searching the file on a line-by-line basis also took less than a second.

To use the ReadAll method, open a text file for reading and then call ReadAll. (No parameters are needed.) For example, the script in Listing 4.38 opens the file C:\FSO\ScriptLog, reads in the contents of the file, and stores that data in the variable strContents. The script then echoes the value of strContents, which happens to be the contents of the text file as well.

Listing 4.38 Reading a Text File Using the ReadAll Method

  
1
2
3
4
5
6


Const ForReading = 1
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objFile = objFSO.OpenTextFile("C:\FSO\ScriptLog.txt", ForReading)
strContents = objFile.ReadAll
Wscript.Echo strContents
objFile.Close

Reading a Text File Line by Line

For system administration purposes, text files typically serve as flat-file databases, with each line of the file representing a single record in the database. For example, scripts often read in a list of server names and then carry out an action against each of those servers. In those instances, the text will look something like the following:



atl-dc-01
atl-dc-02
atl-dc-03
atl-dc-04

When a text file is being used as a flat-file database, a script will typically read each record (line) individually and then perform some action with that record. For example, a script (using the preceding sample text file) might read in the name of the first computer, connect to it, and carry out some action. The script would then read in the name of the second computer, connect to it, and carry out that same action. This process would continue until all the records (lines) in the text file have been read.

The ReadLine method allows a script to read individual lines in a text file. To use this method, open the text file, and then set up a Do Loop that continues until the AtEndOfStream property is True. (This simply means that you have reached the end of the file.) Within the Do Loop, call the ReadLine method, store the contents of the first line in a variable, and then perform some action. When the script loops around, it will automatically drop down a line and read the second line of the file into the variable. This will continue until each line has been read (or until the script specifically exits the loop).

For example, the script shown in Listing 4.39 opens the file C:\FSO\ServerList.txt and then reads the entire file line by line, echoing the contents of each line to the screen.

Listing 4.39 Reading a Text File Using the ReadLine Method

  
1
2
3
4
5
6
7


Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objFile = objFSO.OpenTextFile("C:\FSO\ServerList.txt", 1)
Do Until objFile.AtEndOfStream
 strLine = objFile.ReadLine
 Wscript.Echo strLine
Loop
objFile.Close

"Reading" a Text File from the Bottom to the Top

As noted previously, the FileSystemObject can read a text file only from the beginning to the end; you cannot start at the end and work your way backwards. This can sometimes be a problem when working with log files. Most log files store data in chronological order: The first line in the log is the first event that was recorded, the second line is the second event that was recorded, and so on. This means that the most recent entries, the ones you are perhaps most interested in, are always located at the very end of the file.

There might be times when you want to display information in reverse chronological order - that is, with the most recent records displayed first and the oldest records displayed last. Although you cannot read a text file from the bottom to the top, you can still display the information in reverse chronological order. To do this, a script must:

  1. Create an array to hold each line of the text file.

  2. Use the ReadLine method to read each line of the text file and store each line as a separate element in the array.

  3. Display the contents of the array on screen, starting with the last element in the array (the most recent record in the log file) and ending with the first element in the array (the oldest log file).

For example, the script in Listing 4.40 reads in the file C:\FSO\ScriptLog.txt, storing each line as an element in the array arrFileLines. After the entire file has been read, the contents are echoed to the screen, beginning with the last element in the array. To do this, the For Loop begins with the last element (the upper bound of the array) and incrementally works down to the first element (the lower bound).

Listing 4.40 "Reading" a Text File from the Bottom to the Top

  
1
2
3
4
5
6
7
8
9
10
11
12
13


Dim arrFileLines()
i = 0
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objFile = objFSO.OpenTextFile("C:\FSO\ScriptLog.txt", 1)
Do Until objFile.AtEndOfStream
 Redim Preserve arrFileLines(i)
 arrFileLines(i) = objFile.ReadLine
 i = i + 1
Loop
objFile.Close
For l = Ubound(arrFileLines) to LBound(arrFileLines) Step -1
 Wscript.Echo arrFileLines(l)
Next

If the contents of C:\FSO\ScriptLog.txt look like this:



6/19/2002   Success
6/20/2002   Failure
6/21/2002   Failure
6/22/2002   Failure
6/23/2002   Success

The following information will be echoed to the screen:



6/23/2002   Success
6/22/2002   Failure
6/21/2002   Failure
6/20/2002   Failure
6/19/2002   Success

Reading a Text File Character by Character

In a fixed-width text file, fields are delimited by length: Field 1 might consist of the first 15 characters on a line, Field 2 might consist of the next 10 characters, and so on. Thus a fixed-width text file might look like the following:



Server                    Value                      Status
atl-dc-01                 19345                      OK
atl-printserver-02        00042                      OK
atl-win2kpro-05           00000                      Failed

In some cases, you might want to retrieve only the values, or only the status information. The value information, to pick one, is easy to identify: Values always begin with the 26th character on a line and extend no more than 5 characters. To retrieve these values, you need to read only the 26th, 27th, 28th, 29th, and 30th characters on each line.

The Read method allows you to read only a specified number of characters. Its sole parameter is the number of characters to be read. For example, the following code sample reads the next 7 characters in the text file and stores those 7 characters in the variable strCharacters:



strCharacters = objFile.Read(7)

By using the Skip and SkipLine methods, you can retrieve selected characters from a text file. For example, the script in Listing 4.41 reads only the sixth character in each line of a text file. To do this, the script must:

  1. Skip the first five characters in a line, using Skip(5).

  2. Read the sixth character, using Read(1).

  3. Skip to the next line of the file.

Listing 4.41 Reading a Fixed-Width Text File

  
1
2
3
4
5
6
7
8


Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objFile = objFSO.OpenTextFile("C:\FSO\ScriptLog.txt", 1)
Do Until objFile.AtEndOfStream
 objFile.Skip(5)
 strCharacters = objFile.Read(1)
 Wscript.Echo strCharacters
 objFile.SkipLine
Loop

To better illustrate how this script works, suppose the file C:\FSO\ScriptLog.txt looks like the following:



XXXXX1XXXXXXXXXXXXXX
XXXXX2XXXXXXXXXXXXXXXXXXX
XXXXX3XXXXXXXXXXXX
XXXXX4XXXXXXXXXXXXXXXXXXXXXXXXX

For each line in this file, the first five characters are X's, the sixth character is a number, and the remaining characters are a random number of X's. When the script in Listing 4.41 runs, the script will:

  1. Open the text file and begin to read the first line.

  2. Skip the first five characters.

  3. Use the Read method to read the sixth character.

  4. Echo that character to the screen.

  5. Skip to the next line and repeat the process until all the lines have been read.

When the script is run under CScript, the following output appears in the command window:

  
1
2
3
4
Was this page helpful?
(1500 characters remaining)
Thank you for your feedback
Show:
© 2014 Microsoft