Subscribe to Windows IT Pro
August 12, 1999 12:00 AM

Scripting 101, Part 4

Windows IT Pro
InstantDoc ID #7112
Rating: (0)
Downloads
7112.zip

So far, I've explained how to access arguments individually. But accessing arguments individually can lead to problems. Let's suppose you use one of the previous examples, and a user fails to provide any arguments when using your script. The script will produce a runtime error because it tries to access a collection member that doesn't exist. You can use the collection's Count property to avoid this error, as the next example shows:

If WScript.Arguments.Count _
  > 1 Then
       strComputer = _
          WScript.Arguments(0)
       strUser = _
          WScript.Arguments(1)
End If

In this example, the condition checks the Arguments collection's Count property to ensure the user running the script provides a minimum of two arguments. If Count is greater than one, the If block assigns the first two arguments to the strComputer and strUser variables. If Count isn't greater than one, the script doesn't access the Arguments collection and thereby avoids a runtime error. As you can with arrays, you can also loop through arguments using a For Each loop:

If WScript.Arguments.Count Then
   For Each strArg In _
      WScript.Arguments
        WScript.Echo strArg
    Next
End If

Alternatively, you can use a For loop in conjunction with the Count property, as the next example shows. Be sure to specify Count - 1 as the For loop's ending value because collection membership starts at zero (i.e., the first member in a collection is Item(0)).

For i = _
      0 To WScript.Arguments.Count ­ 1
         WScript.Echo _
            WScript.Arguments(i)
Next

You can also be creative in some ways with the Arguments collection. I often implement arguments as switch=value pairs and store arguments as key=value pairs in a Dictionary object. For information about working with Dictionary objects, see Scripting Solutions, "Leveraging Components," January 1999. Storing arguments in a Dictionary object lets you easily determine whether a specific argument is available. I use the Dictionary object's Exists method for this purpose. In addition, by incorporating the Arguments collection and Dictionary object in a For Each loop, you can provide arguments in any order you want.

FileSystemObject's TextStream Object
Providing pieces of data to your script through the Arguments collection works, but sometimes you'll want to provide more data than you care to type on a command line. For example, you might want to provide your script with a long list of computer names or usernames, or you might want to record your script's actions to a log file. The FileSystemObject's TextStream object provides an easy way to read from and write to files.

The scripting runtime's FileSystemObject provides an object-oriented interface to work with virtually all aspects of a file system. With the FileSystemObject, you can read from files, write to files, and retrieve drive, directory, and file information. Like many objects you interact with using WSH, you can reference object models that express the objects, methods, and properties that FileSystemObject exposes. An object model is a graphical representation of an object's capabilities and the object's relationship to other objects in the model. Figure 2 shows the paths through which the FileSystemObject exposes the TextStream object, including the methods and properties that the TextStream object provides.

I'll explain Figure 2 to show that using the TextStream object is much easier than it seems. The FileSystemObject provides a hierarchical view of a file system in which a Drives collection contains Drive objects, a Folders collection contains Folder objects, and a Files collection contains File objects. In the FileSystemObject model, the FileSystemObject, the Folder object, and the File object expose the TextStream object and make it accessible. (The FileSystemObject, Folder, and File objects expose the TextStream-related methods.)

As you do with all objects that the FileSystemObject exposes, you must first create (using CreateObject) a reference to a FileSystemObject, before you can create a TextStream object. After you have a reference to a FileSystemObject, you can invoke one of the two TextStream-related methods (CreateTextFile, OpenTextFile) that the FileSystemObject provides. CreateTextFile creates a new (or overwrites an existing) text file and returns a reference that you use to write to the file. OpenTextFile opens an existing (or creates a new) text file and returns a reference that you use to read from, write to, or append to the file. In both cases, you use the reference that CreateTextFile or OpenTextFile returns to access the TextStream's methods and properties.

Suppose you have a text file named "c:\temp\servers.txt" that contains a list of servers, with one server name per line. You want to perform some action on each server in the list. You can use the FileSystemObject's TextStream object to read the server list and perform the action one server at a time, as Listing 1 shows. This example first creates a reference to the FileSystemObject named oFSO. (After you have a reference, you can call the methods that the FileSystemObject exposes.) Next, the example calls the TextStream-related method OpenTextFile and passes the method the name of the file to open. OpenTextFile creates a TextStream object and returns a reference (also called a handle) to the target file. The reference that OpenTextFile returns initializes the oTextStream variable. (After you obtain a reference to a TextStream object, you can access the methods and properties that the TextStream object exposes.)

The script uses the Do While loop in conjunction with the TextStream's AtEndOfStream property to traverse the servers.txt file. During each loop iteration, the TextStream's ReadLine method reads a server name from the file and assigns it to strServer. The script then performs some action on strServer. The script continues this process until the AtEndOfStream property becomes true, which signals that the process has reached the end of the file. At that point, the script exits the Do While loop and closes the file using the TextStream's Close method.

Simplify with ReadAll
TextStream's ReadAll method provides a smarter way to perform the previous input-related task. In the following example, you use the ReadAll method to read the servers.txt file in one fell swoop. You hand the result of this continuous text stream to the Split function (using vbNewline as a delimiter), which neatly returns an array that contains one server name per array element. Rather than looping through an open file as the previous example did, you end up with an array that you can easily traverse using a For Each loop, as Listing 2 shows. In addition, you can use the array for other purposes, without incurring the overhead of reopening and rereading the file one line at a time.

Creating a Log File
You might want to create a log file to record errors that your script encounters. In Listing 3, the example shows how to use the FileSystemObject's CreateTextFile method for this purpose.

Thus far, I've explained how you can create TextStream objects using the two methods exposed via the FileSystemObject. As I mentioned earlier, the Folder and File objects also expose TextStream-related methods. As such, you can also create and open files via references to these objects. For additional information about FileSystemObject capabilities, see the VBScript 5.0 documentation at http://msdn.microsoft.com/scripting.

The WSH Arguments collection and the FileSystemObject's TextStream object are only two of many ways to get data in and out of a WSH script. Other options include leveraging data that the directory services store via Active Directory Service Interfaces (ADSI), databases store via ADO, or Microsoft Excel stores via the Microsoft Office automation interfaces. For information about ADSI, ADO, and Office object models, see Scripting Solutions, "WSH Wise," May 1999. By incorporating the Arguments collection and the TextStream object in your scripts, you can produce flexible and reusable code. In the not-too-distant future, you'll have even more flexibility because WSH 2.0 will introduce support for standard input and output (STDIO) via the console. I'll discuss STDIO and other improvements to WSH 2.0 in the coming months.

Related Content:

ARTICLE TOOLS

Comments
  • Roy Mash
    8 years ago
    Jul 02, 2004

    I had hoped to find out how to use a script to test for a user's group membership (mentioned in the first lesson) only to be dissappointed.
    This elementary task is amazingly difficult to find in onling documentation.

  • Adrian Greaves
    13 years ago
    Nov 15, 1999

    Sorry if I'm being slow, but I cannot see the Listings which are referred to in the body of the text.

You must log on before posting a comment.

Are you a new visitor? Register Here

advertisement

advertisement

Windows is a trademark of the Microsoft group of companies. Windows IT Pro is used by Penton Media Inc. under license from owner.