Handling User Input in WSH - Command Line Arguments
(Page 2 of 6 )
Let’s take a look at how to handle command line parameters that are supplied when calling a script. The user will simply append some information to the command line at the time of execution.
Multiple command line parameters are separated by spaces so any argument that contains spaces should be enclosed in quotation marks.
Let’s create a very simple script that accepts a text string parameter. We’ll simply Echo the text string back to the user. Copy the following text into any text editor such as Notepad and save it as echoscript.vbs.
Set colArgs = Wscript.Arguments
Wscript.Echo colArgs.Item(0)
This script simply assumes that there will be only one item in the colArgs collection. This string is returned using the Echo command. Let’s see how it works by taking a look at the following command line and results.
C:>cscript.exe arguments.vbs “Hello World!”
Microsoft (R) Windows Script Host Version 5.6
Copyright (C) Microsoft Corporation 1996-2001. All rights reserved.
Hello World!
There you have it. Our string was echoed back exactly as expected. What would happen if we tried this without the required quotation marks?
C:>cscript.exe arguments.vbs Hello World!
Microsoft (R) Windows Script Host Version 5.6
Copyright (C) Microsoft Corporation 1996-2001. All rights reserved.
Hello
Oops! Cscript encountered a space and processed the words as two separate parameters. Our script only echoes the argument located at Item 0. In other words, it will only return the first word.
So it’s obvious at this point that we need to process each of these arguments individually. We’ll do that by creating a loop.
Set colArgs = Wscript.Arguments
For i = 0 To colArgs.Count - 1
strText = strText & colArgs.Item(i) & " "
Next
Wscript.Echo strText
As you can see we’re looping through each item based on its index value. We used the Count method to determine how many times our loop needs to iterate. Don’t forget that indices are zero-based so our highest index value is our Count minus one.
There is one other important step that you should add to your scripts when dealing with arguments. What happens if the user doesn’t supply the required arguments? A little error-handling can both notify the user and also prevent unexpected errors.
If Wscript.Arguments.Count Then
Set colArgs = Wscript.Arguments
For i = 0 To colArgs.Count - 1
strText = strText & colArgs.Item(i) & " "
Next
Wscript.Echo strText
Else
Wscript.Echo "This script cannot be run without parameters."
End If
The Arguments object will always exist even if it is empty so we can build a simple If statement around the Count method. A count of 0 will be considered False while any other value will be considered True.
Next: Using Named Arguments >>
More Windows Scripting Articles
More By Nilpo/Developer Shed Staff Writer