How-to: VBScript command line arguments

Positional arguments

Calling a script with unnamed arguments is a simple method of passing values into a VBScript, those values can then be picked up within the script by reading the properties of WScript.Arguments

cscript.exe demo.vbs December 500

strMonth = WScript.Arguments.Item(0)
strPrice = WScript.Arguments.Item(1)
wscript.echo strMonth & " and " & strPrice

This can be extended to cope with a large number of arguments .Item(n) but every time the script is called all of the arguments must be present and passed in the same order. If any are missed out then the numbers will change .Item(4) becomes .Item(3)etc.

The Unnamed property will return a collection of the positional arguments, presented in the order that they were entered on the command line.

Set myArgs = WScript.Arguments.Unnamed
For i = 0 to myargs.count -1
  wscript.Echo "Argument" & i & " = " & myArgs.item(i)

Passing an argument that starts with “//” to a VBscript, will by default be taken as options for the windows script host itself (cscript or wscript). To avoid this pass a double slash "//" to end the argument parsing of cscript/wscript. Alternatively use a named argument as below.

Named arguments

A named argument begins with a slash (/), and the name and the value are separated by a colon (:) those values can then be picked up within the script by reading the collection WScript.Arguments.Named

cscript.exe demo2.vbs /month:April /price:500

Set colArgs = WScript.Arguments.Named
strMonth = colArgs.Item("month")
strPrice = colArgs.Item("price")
wscript.echo strMonth & " and " & strPrice

Named arguments can be given in any order

cscript.exe demo2.vbs /price:500 /month:April

Named arguments are optional, so you can include a default:

If colArgs.Exists("month") Then
   strMonth = colArgs.Item("month") 
   strMonth = "January" 
End If

To count the number of arguments:

intCount = WScript.Arguments.Count
wscript.echo intCount

“Art, in itself, is an attempt to bring order out of chaos” ~ Stephen Sondheim


Arguments - Command line arguments.
Variables - Define VBScript constants and variables.
Windows 2000 Scripting Guide - Technet.

Copyright © 1999-2020
Some rights reserved