Handling User Input in WSH
(Page 1 of 6 )
Many of the scripts you write will require some form of user input. Whether the user is supplying some direction for the script or merely providing information that the script cannot determine on its own, this is a very common and useful technique. We’re going to explore some of the more common ways to handle user input.
There are basically two different ways to request user input for your script. The first is by using run time parameters supplied by the user at the time of script execution. The second is by accepting a user’s response to a prompt during the script’s execution.
We’ll start by learning how to handle parameters that are passed as arguments during the script’s execution. WSH allows for argument passing in two ways. You can supply them in the command line used to execute the script or you can drag-and-drop files onto a script’s icon.
The first is the method of choice for running a script with the Cscript engine and the second is the better choice for executing through the Wscript engine. However the two methods are not exclusive to these recommendations.
Using drag-and-drop to pass files or folders to a script will execute the script using the default scripting engine.
WSH provides a native object for us to handle these arguments called the WshArguments object. The WshArguments object returns a read-only collection of items that were passed during execution. The WshArguments object is returned by the Wscript object’s Arguments property.
object.Arguments
The process of handling the object and arguments is the same regardless of which method was used to pass them. Let’s take a look at the methods and properties provided by the WshArguments object.
Methods
object.Count
object.Item([Index])
Properties
object.length
The WshArguments object contains a collection of argument items. The Count method is used to return a Long value indicating the number if items in the collection. The Item method is used to return a specific item in the collection corresponding to the supplied zero-based Index value.
The length property returns a Long value indicating the number of items in the collection. For consistency when using Jscript, this length property should be typed in lower case.
Set colArgs = Wscript.Arguments
For Each Arg In colArgs
Wscript.Echo Arg
Next
This simple loop will iterate through each of the supplied arguments and Echo them back to the user. This is a very basic method of processing these arguments.
Next: Command Line Arguments >>
More Windows Scripting Articles
More By Nilpo/Developer Shed Staff Writer