Partager via


Handling Input and Output

Microsoft® Windows® 2000 Scripting Guide

Scripts have to interact with users. Output, for example, is a key element of many system administration scripts: A script that parses event logs for specific entries should display any entries it finds. Likewise, scripts need to be able to prompt users for input and then make use of that input. Suppose you write a script that retrieves information about the connectivity between two computers. You need to provide users with a simple way to specify the two computers being checked for connectivity.

WSH provides a means for interacting with users and, perhaps more important, provides a way to receive input from and direct output to the command window. Among other things, this allows you to create VBScript scripts that can run as command-line utilities, accepting input from the command prompt and displaying output within a command window. This is more useful than it might first seem, because VBScript has no intrinsic methods for receiving input from or directing output to the command window.

The WScript Echo method provides a simple way to display messages. It accepts an item (a string, a number, a date) as its only parameter and displays that item as a message to the user. The script in Listing 3.2 uses the WScript Echo method to display the version of WSH installed on the computer on which the script runs.

Listing 3.2 Displaying the Version of WSH on a Computer

  
1
Wscript.Echo "The version of WSH on this computer is: " & WScript.Version

In addition, the WScript object has properties that enable your scripts to access three objects that provide input and output functionality: StdOut, StdIn, and StdErr. These objects provide their own methods and properties for working with input and output, which are shown in Figure 3.6. In general, only scripts run under CScript can access StdOut, StdIn, and StdErr.

Figure 3.6 Methods and Properties of the TextStream Objects

sas_wsh_80c

Displaying Messages to Script Users

One of the primary purposes of system administration scripting is to answer questions. How much free hard disk space is available on this server? Which user account is Internet Information Service running under? Available memory is quite low on this mail server; what processes are running and using up the memory?

For a script to answer questions such as these, it must retrieve the answers and have a way to communicate those answers back to you. Although scripts can save retrieved information in text files or databases, it is more common to have the script display that information on the screen. WSH can display information by using the Echo method.

The WScript Echo method takes one or more items as parameters and displays those items to the user. If a script is run under CScript, the items are displayed in the command window. If a script is run under WScript, the items appear in message boxes. The Echo method can display almost any kind of data, including strings, numbers, dates and times, and even the results of mathematical calculations. For example, this line of code displays the value 4, the result of adding 2 and 2:

Wscript.Echo 2 + 2

The Echo method is easy to implement; you simply call the method, followed by the information you want to display on the screen. To display the value of a variable, specify the variable name as the parameter:

Wscript.Echo strMyVariable

This also holds true for VBScript variables such as Now and Time:

Wscript.Echo Now

To display a string, simply enclose it in quotation marks:

Wscript.Echo "This is my string."

In fact, the only real trick to working with Wscript.Echo is understanding the difference between what happens when a script using this method runs under CScript and what happens when that same script runs under WScript. For example, consider the script in Listing 3.3, which displays three status messages by using the WScript.Echo method.

Listing 3.3 Using the Echo Method to Display Three User Messages

  
1
2
3
Wscript.Echo "Examining System Drives"
Wscript.Echo "Determining Free Drive Space"
Wscript.Echo "Mapping Network Drives"

When run under CScript, the script displays the following in a command window all at once, without stopping or requiring any user interaction.

Examining System Drives
Determining Free Drive Space
Mapping Network Drives

When run under WScript, however, the script creates three separate message boxes, as shown in Figure 3.7. The message boxes are presented one at a time, and each requires a user to click the OK button before the next one can be displayed.

Figure 3.7 Three Separate Message Boxes Produced by the Echo Method Running Under WScript

sas_wsh_82s

Under WScript, each call to the WScript.Echo method results in the creation of a new message box. Depending on the script, this can be very important. If your script simply returns the amount of free disk space on drive C, the fact that this information is displayed in a message box rather than in the command window might be irrelevant. Suppose, however, that the script returns a list of all the services installed on a computer. Using WScript, you would need to respond to 100 or so message boxes, one for each service. In addition, as each message box was dismissed, that piece of information would disappear from the screen.

Under CScript, not only is the information displayed in the command window without the need for any user intervention (such as dismissing message boxes), but all the information also remains on the screen until the command window is dismissed. This allows you to copy the data and paste it into another application.

Getting Text into and out of Scripts

Command-line tools (including batch files) typically interact with three standard input and output streams. These are known as Standard In (StdIn), Standard Out (StdOut), and Standard Error (StdErr). Unless you specify otherwise, the command processor assumes that input will be received from the keyboard (StdIn) and output (StdOut) and error messages (StdErr) should be sent to the command window.

StdIn, StdOut, and StdErr (available only when your scripts run under CScript) provide your scripts with access to each of these streams. These streams serve several important purposes:

  • They provide a way to display output in a command window.

  • They provide a way for users to type input from a command prompt and have that input read by a script.

  • They provide a way for scripts to access output and standard error information generated by a script, a batch file, or a command-line tool.

Displaying Output Using StdOut

StdOut can be used to display output within a command window. StdOut includes the properties shown in Table 3.4.

Table 3.4 StdOut Methods

Method

Description

Write

Writes the supplied characters to the screen but does not append a carriage return/linefeed. For example, this script uses the Write method four times:

Wscript.StdOut.Write "ABCD" Wscript.StdOut.Write "EFGHIJKLMN" Wscript.StdOut.Write "OPQRSTUV" Wscript.StdOut.Write "WXYZ"

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

WriteLine

Similar to Wscript.Echo, WriteLine writes the supplied characters to the screen and then appends a carriage return/linefeed (as though a user had pressed ENTER). For example, this script uses the WriteLine method four times:

Wscript.StdOut.WriteLine "ABCD" Wscript.StdOut.WriteLine "EFGHIJKLMN" Wscript.StdOut.WriteLine "OPQRSTUV" Wscript.StdOut.WriteLine "WXYZ"

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

WriteBlankLines

Inserts a blank line in the output, as though a user had pressed ENTER twice without typing any characters. WriteBlankLines accepts a single parameter: the number of blank lines to insert.

For example, this script uses WriteBlankLines to insert first 1 and then 2 blanks lines in the output:

Wscript.StdOut.WriteLine "ABCD" Wscript.StdOut.WriteBlankLines 1 Wscript.StdOut.WriteLine "EFGHIJKLMN" Wscript.StdOut.WriteLine "OPQRSTUV" Wscript.StdOut.WriteBlankLines 2 Wscript.StdOut.WriteLine "WXYZ"

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

The script in Listing 3.4 displays a message in the command window by using the Write and WriteLine methods of the StdOut TextStream object.

Listing 3.4 Using the Write and WriteLine Methods to Display Messages in the Command Window

  
1
2
3
4
5
6
7
8
9
10
Set objNetwork = Wscript.CreateObject("Wscript.Network")
Set objStdOut = WScript.StdOut
objStdOut.Write "User: "
objStdOut.Write objNetwork.UserDomain
objStdOut.Write "\"
objStdOut.Write objNetwork.UserName
objStdOut.WriteBlankLines(1)
objStdOut.WriteLine objNetwork.ComputerName
objStdOut.Write "Information retrieved."
objStdOut.Close

The following is output from the script in Listing 3.4:

User: FABRIKAM\kenmyer
atl-wk-01
Information retrieved.

By contrast, here is what output from the same script would look like if Wscript.Echo were substituted for the StdOut methods:

User:
FABRIKAM
\
kenmeyer
atl-wk-01
Information retrieved.

Reading Input by Using StdIn

One way to provide a script with input is to use arguments (discussed later in this chapter). For example, the following command runs a script named DeleteUser.vbs, passing as an argument the name of the user account to be deleted:

cscript DeleteUser.vbs kenmyer

Arguments provide a quick and easy way to add input to a script. On the other hand, arguments require the user running the script to know which arguments need to be supplied and to know how to supply them. Instead of requiring users to memorize the syntax for your scripts, you can prompt users to supply the correct information after the script has started. For example:

C:\Scripts\cscript DeleteUser.vbs
Please enter the name of the user account to be deleted: _

StdIn can be used to read information entered at the command line. StdIn includes the methods and properties shown in Table 3.5.

Table 3.5 StdIn Methods and Properties

Method/Property

Description

Read

Reads the specified number of characters and then stops. For example, the following reads and echoes 3 characters at a time from StdIn until the entire line has been read:

Do Until Wscript.StdIn.AtEndOfLine strInput = Wscript.StdIn.Read(3) Wscript.Echo strInput Loop

If StdIn consists of the string "abcdefghijklmnopqrstuvwxyz", output from the script will look like this:

ReadLine

Reads one line from StdIn and then stops before reaching the newline character. ReadLine is particularly useful for reading input typed by users because it reads all the characters typed by the user before he or she pressed ENTER:

strInput = Wscript.StdIn.ReadLine Wscript.Echo strInput

If StdIn consists of the string "abcdefghijklmnopqrstuvwxyz", output from the script will look like this:

abcdefghijklmnopqrstuvwxyz

ReadLine is also useful for reading the output generated by a spawned command-line tool. For more information about this, see "Running Programs" later in this chapter.

ReadAll

Used only for reading the output generated by a spawned command-line tool, batch file, or shell command.

Skip

Skips the specified number of characters and then stops. For example, this script skips the first 23 characters in StdIn and then reads any remaining characters one at a time:

Wscript.StdIn.Skip(23) Do Until Wscript.StdIn.AtEndOfLine strInput = Wscript.StdIn.Read(1) Wscript.Echo strInput Loop

If StdIn consists of the string "abcdefghijklmnopqrstuvwxyz", output from the script will look like this:

SkipLine

Used to skip a line when reading the output generated by a spawned command-line tool, batch file, or shell command.

AtEndOfLine

Boolean value indicating whether the end of a line has been reached. When the Read method is used to retrieve input typed by a user, this property when True informs the script that the entire line has been read.Do Until Wscript.StdIn.AtEndOfLine strInput = Wscript.StdIn.Read(1) Wscript.Echo strInput Loop

AtEndOfStream

Boolean value indicating whether the end of the stream has been reached. Used only for reading the output generated by a spawned command-line tool, batch file, or shell command.

You can use StdIn to retrieve information from the user. To obtain input from the user, you do the following:

  1. Use the Write method to display a prompt on screen (such as, "Please enter your name:"). The Write method is used to ensure that the prompt and the response are included on the same line. Your screen will look similar to this, with the underscore representing the command prompt cursor:

    C:\Scripts> Please enter your name: _
    
  2. Use the ReadLine method to read anything the user types at the command prompt, and store this information in a variable. Information is read until the user presses ENTER. For example, if you type Ken Myer and then press ENTER, the value Ken Myer will be stored in the variable.

    ReadLine can read as many as 254 characters typed at the command prompt.

For instance, suppose you create a script that converts numbers from decimal to hexadecimal. You need to prompt the user to enter the decimal value to convert. The script in Listing 3.5 uses the ReadLine method of the WScript StdIn object to retrieve a decimal value from the user and store it in the strDecimal variable. The VBScript Hex function is used to convert the decimal value to hexadecimal, and the WriteLine method of the WScript StdOut object is used to display the results.

Listing 3.5 Convert Between Decimal and Hexadecimal

  
1
2
3
4
5
Wscript.StdOut.Write "Enter a Decimal Number: "
strDecimal = Wscript.StdIn.ReadLine
Wscript.StdOut.WriteLine strDecimal & " is equal to " & _
 Hex(strDecimal) & " in hex."

When run under CScript, the interaction between the script and the user looks similar to this:

C:\Scripts>cscript test.vbs
Microsoft (R) Windows Script Host Version 5.6
Copyright (C) Microsoft Corporation 1996-2001. All rights reserved.
Enter a Decimal Number: 256
256 is equal to 100 in hex.