Handling User Input in WSH - Using Named Arguments
(Page 3 of 6 )
Sometimes it’s just not feasible to worry about what order the command line parameters are given in. Often there are optional command lines that can be left out by the user. This can make it very difficult to parse the arguments without writing a lot of extra code. Thankfully, WSH provides a way to make this a little easier.
object.Named
object.Item(Name)
WSH allows us to use a named argument. The Named property of the Arguments object returns a dictionary of named arguments. The Item method is used to grab those dictionary entries according to the supplied Name. Let’s write a script that accepts two command line parameters: a name and an age. The command line might look like this:
C:>cscript.exe namedargs.vbs /name:Nilpo /age:26
The command line above demonstrates the use of named arguments. Each argument is listed as a command line switch with a name-value pair. The name and values are separated by a colon. Don’t forget to surround the names or values in double quotes if they contain spaces. Now let’s take a look at the code.
Set dicNamedArgs = Wscript.Arguments.Named
strName = dicNamedArgs.Item("name")
strAge = dicNamedArgs.Item("age")
Wscript.Echo "Your name is " & strName & ". You are " & strAge & "."
What we’ve done here is quite simple. We’ve assigned the variable dicNamedArgs to our dictionary object. Then we call for each of the command line Items. If we run the example command line above, our output should look like this:
Microsoft (R) Windows Script Host Version 5.6
Copyright (C) Microsoft Corporation 1996-2001. All rights reserved.
Your name is Nilpo. You are 26.
Now try this example again with the same code. This time we’ll switch the order of the command line arguments. Because we’re calling by name, and not by order, our script will run perfectly.
C:>cscript.exe namedargs.vbs /age:26 /name:Nilpo /uselesscommand:value
Microsoft (R) Windows Script Host Version 5.6
Copyright (C) Microsoft Corporation 1996-2001. All rights reserved.
Your name is Nilpo. You are 26.
Perfect! We got exactly the same output. Notice that it even ignored the extra command that it didn’t recognize. It’s also important to note that if two arguments have the same name, only the first will be processed. Any remaining arguments sharing that name will simply be ignored.
Next: Prompting Users in Cscript >>
More Windows Scripting Articles
More By Nilpo/Developer Shed Staff Writer