Previous Page
Next Page

Writing to a Text File

Creating text files using VBScript is nice but rather useless unless you can also add information to them. Writing information to a text file gives you a way to save information. In addition, it's a good way to create a log file to track the progress of various automated administrative tasks. You use the WriteLine method to write to a text file.

Just the Steps

To write to a text file

1.
Create an instance of FileSystemObject.

2.
Use the appropriate parameter to indicate that you are going to either overwrite the file (2) or append data to the file (8).

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

4.
Close the text file.


Determining the Best Way to Write to a File

There are actually three different ways you can write to files. These methods are described in Table 6-4.

Table 6-4. Methods used to write to files

Method

Use

Write

Writes to the file without appending the carriage return. (With the carriage return, you might recall, the insertion point is moved to the beginning of the next line.)

WriteLine

Writes to the file and includes a carriage return and a line feed at the end of the line.

WriteBlankLines(n)

Writes blank lines to the file. The placeholder (n) specifies the number of lines to write.


Overwriting a File

You use the constant ForWriting in conjunction with the Write method to overwrite a file. I use this when I want to track the progress of an operation in a log file. By looking in the file, I can see when the operation last ran, as illustrated in the BasicLog.vbs script. The Header section of this script is left out below for clarity, however BasicLog.vbs does contain this information.

BasicLog.vbs

LogFile = "C:\fso\fso.txt"
Const ForWriting = 2
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objFile = objFSO.OpenTextFile(LogFile, ForWriting)
objFile.WriteLine "beginning process " & Now
objFile.WriteLine "working on process " & Now
objFile.WriteLine "Process completed at " & Now
objFile.Close

The script begins by defining the variable LogFile and assigning a text file to it. You do this to make it easier to reuse the code and to make it easier to change the file you want to write to.

You then define the constant ForWriting and set it equal to 2, which is the number that tells VBScript to overwrite any data found in the text file that might have been previously written to.

Tip

ForReading, ForWriting, ForAppending are listed in the VBScript documentation as constants, but they are not intrinisic constants for VBScript. Convention (and readability) dictates using these constant names, but they are always user defined constants.


The variable objFSO is then set to be equal to the object returned by the CreateObject command that is used to create an instance of FileSystemObject. In the next line, the variable objFile contains textStreamObject that is created when you use the OpenTextFile method. All the preceding steps are overhead for the Write operation. Once you have the ForWriting handle to the log file, you have completed the Reference information section of the script. You're now ready for the Output information section, which is the section of the script that actually does work. In the Output section, you use the WriteLine method.

Quick Check

Q.

What are three ways to write to files?

A.

You can write to files using the Write, WriteLine, and WriteBlankLines methods.

Q.

If you want to overwrite a file, what do you need to do?

A.

You need to specify the constant ForWriting.


In a logging situation, the dauntless network administrator is looking for two salient pieces of information: what operation completed and when it completed. Armed with this information, a network administrator can judge the success or failure of various procedures. In the BasicLog.vbs script, you can easily glean this information by incorporating the WriteLine method inside the For...Next loop of any working script. This is exactly the type of thing I do in a lab to estimate how long a certain script will take to complete. If, for instance, a certain Windows Management Instrumentation (WMI) script needs five minutes to complete, you might not want to launch it on 100 servers at the same time because doing so could have an adverse impact on the computing environment.

Using Temporary File Names

One of the problems when logging to a file is the issue of names. Just how many logfile.txt files can you have in the same directoryand what is the most obvious name for a log file? You begin to see the point. Often, we do not really want to perform "actual" logging; rather, we want a better output format. Notepad is almost as powerful a log file reader as it is a script editor. The solution is to use a temporary file name that is randomly created by the file system object. Use the following procedure for doing this.

Creating a temporary file in a temporary directory

1.
Create a new script based on the FSOTemplate.vbs script contained in the \My Documents\Microsoft Press\VBScriptSBS\Templates directory. Save the new script as YourNameCreateTempFileNameAndOpenInNotepad.vbs.

2.
Delete the four variables you will not use in this script: objFolder, strFile, strFolder, and colFiles.

3.
Delete the line that defines the constants.

4.
Declare two new variables: strPath and objShell.

5.
Assign objShell to hold the wshShell object that comes back from using the CreateObject command to create WScript.shell. This is seen below:

Set objShell = CreateObject("WScript.shell")

6.
Use strPath to hold the path that comes back from the FunTempFile function. Make sure you pass the objFSO variable to the function because it contains an instance of the file system object (a file system object is required for the FunTempFile function to work properly). This code is seen below, and must be placed after the CreateObject line from step 5.

strPath = FunTempFile(objFSO)

7.
Open the FunTempFile.vbs script (\My Documents\Microsoft Press \VBScriptSBS\Utilities) in Notepad or your favorite script editor. Copy the function that is defined at the bottom of this script. It looks like the following:

Function FunTempFile(objFSO)
Dim objfolder
Dim strName

Const TemporaryFolder = 2

Set objfolder = objfso.GetSpecialFolder(TemporaryFolder)
   strName = objfso.GetTempName
   strName = objfolder & "\" & strName
   FunTempFile = strName
End Function

8.
Use the CreateTextFile method from the file system object to create the text file that is specified in the path statement created by the FunTempFile function. You can use the Set objFile line of code that is remarked out in the file. The only revisions required are to change OpenTextFile to CreateTextFile, and to change strFile to strPath.. This is seen below, and will be placed below the code from the previous step.

Set objFile = objFSO.CreateTextFile(strpath)

9.
Use the Write method to write to the log file you just created. The code to do this is detailed below:

 objFile.Write("Writing to a temporary file ") & now

10.
Use the Run command from the WScript.shell object to run Notepad and to open the temporary file. Normally you could just use the Run method and pass it the name of the text file. The problem is there is no file association between the temporary file name and Notepad, so we need to specifically launch Notepad. This is seen below:

objshell.Run("notepad " & strPath)

11.
Save and run the script. It should produce a Notepad window with a message about a temporary file. If it does not, then compare your results to the \My Documents\Microsoft Press\VBScriptSBS\ch06\CreateTempFileNameAndOpenInNotepad.vbs script.


In the DisplayAdminTools_Logged.vbs file, you merge BasicLog.vbs with the Display AdminTools.vbs file from Chapter 1. This script simply checks when the script begins and when it ends. You could add an extra line of code to compute the run time of the script (if you were so inclined). By consulting the log entries, you can estimate how long it will take to obtain the desired information.

DisplayAdminTools_Logged.vbs

LogFile = "C:\fso\fso.txt"
Const ForWriting = 2

Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objFile = objFSO.OpenTextFile(LogFile, ForWriting)

Set objshell = CreateObject("Shell.Application")
Set objNS = objshell.namespace(&h2f)
Set colItems = objNS.items

objFile.WriteLine "Process started at " & Now
   For Each objItem In colItems
         WScript.Echo objItem.name
   Next
objFile.WriteLine "Process completed at " & Now
objFile.Close

Logging tool names

1.
Open the DisplayAdminTools_Logged.vbs script (My Documents\Microsoft Press \VBScriptSBS\ch06) in Notepad or a different script editor. Save the file as YourNameListAdminTools_Logged.vbs.

2.
On the first non-commented line of your script, add Option Explicit.

Option Explicit

3.
Under Option Explicit, add On Error Resume Next, but comment it out.

'On Error Resume Next

4.
Declare the seven variables that are used in the DisplayAdminTools_Logged.vbs script. Add comments indicating their use in the DisplayAdminTools_Logged.vbs script. Your list will look like the following:

Dim objFSO     'the filesystemobject
Dim objFile    'file object
Dim LogFile    'path to log file
Dim objShell   'shell application object
Dim objNS      'special folder to connect to
Dim colItems   'collection of items in the folder
Dim objItem    'single file in the folder

5.
Declare two more variablesstrMSG and intNSthat will hold a standard message string and the namespace special folder constant value in hexadecimal from Appendix E. Add comments for these variables as well, as seen below:

Dim intNS        'shell special folder constant value
Dim strMSG       'the root message written to log

6.
In the Reference section of the script, above LogFile, assign the string "Enumerating Items:" to the strMSG variable, as seen below:

strMSG = "Enumerating items: "

7.
On the next line, assign the value &h2f to intNS.

intNS = &h2f  'hex value of 47 which is admin tools

Caution

Make sure you do not enclose &h2f with quotation marks, because it would turn this hexadecimal integer into a string and cause your script to fail.

8.
Under the Set objFile = objFSO.OpenTextFile(LogFile, ForWriting) line, use the WriteLine method to write a report header line to the text file. Include the current time stamp, the intNS variable, and the strMSG variable. The line will look like the following:

objFile.WriteLine strMSG & " in folder " & intNS & _
   " Started " & Now

9.
Delete the old objFile.WriteLine "Process started at" & Now line.

10.
Instead of just using WScript.Echo to list the file names, we want to write to our log file. To do this, you will use the WriteLine method. It will go within the For Each...Next loop. My line looks like the following:

objFile.WriteLine objItem.name

11.
Edit the Process Completed line so that it uses strMSG. My line looks like the following:

objFile.WriteLine strMSG & "completed " & Now

12.
Save and run the script. Open your log file, and you should see an output similar to the one in Figure 6-4. If your log does not look similar, compare your script with \My Documents\Microsoft Press\VBScriptSBS\ch06\ListAdminTools_Logged.vbs.

Figure 6-4. Logged output from ListAdminTools_Logged.vbs


Log multiple special folders

1.
Open ListAdminTools_Logged.vbs in Notepad or your favorite script editor and save it as YourName_ListMultipleSpecialFolders_logged.vbs.

2.
Declare a new variable aryNS:

Dim aryNS

3.
In the Reference section of the script, assign some special folders to the array. Make sure you use the Array function to turn aryNS into a static array.

aryNS = array(&ha,&h20,&h6) 'special folder values See Appendix E

4.
Delete the line containing intNS from the Reference section, because we will use this variable to hold an individual namespace from the array.

5.
After you have used the OpenTextFile method and assigned the file object to objFile, use For Each...Next to walk through the array. Use intNS to hold the individual namespace value, as seen below:

For Each intNS In aryNS

6.
On the line after you write to the log file that the script is completed, close out the For Each...Next loop with the word Next.

7.
Save and run your script. It should run fine. If not, compare it to ListAdminTools_Logged.vbs.

8.
Copy the subOpenLogFile subroutine from SubOpenLog.vbs in the Utilities folder. Paste it at the bottom of your script.

9.
After the final Next you entered to close out the For Each...Next loop, call your subOpenLogFile subroutine.

10.
Save and run the script. It should now open the log file for you automatically.


Previous Page
Next Page