Managing Enterprise Systems with the Windows Script Host
Authors: Borge S.
Published year: 2005
Pages: 12-13/242
Buy this book on amazon.com >>

Additional Resources

No one book or publication can cover all topics. There are a large number of resources available on the Internet that can complement the information provided in this book. Book errata will be available at the Apress Web site ( http://www.apress.com/ ) as well as http://www.EnterpriseWSH.com/ .

Newsgroups are probably the most important source of up-to-date information. The microsoft.public.scripting.wsh newsgroup is your best bet for WSH- related postings. This newsgroup is commonly hosted by ISP news servers, but you can also access it directly by pointing your newsreader at news://msnews.microsoft.com , which guarantees the speediest replies to any queries posted.

Chances are any question you may have has been answered before. Use the newsgroup search engines at http://groups.google.com/ to search newsgroup archives.

The Microsoft Developers Network (MSDN) is an enormous resource for Microsoft-related development material. There's a never-ending supply of articles on the latest technologies, including a scripting-specific site at http://msdn.microsoft.com/scripting .

Finally, there are a number of excellent Web sites that contain large amounts of additional information and scripting samples. The two standouts are Ian Morrish's site http://communities.msn.com/windowsscript and Clarence Washington's Win32Scripting site at http://cwashington.netreach.net/ .

Chapter 2: Shell Operations

The WSH shell object provides the ability to create Windows shortcuts, read environment variables , manipulate registry settings, and run external programs.

To create an instance of the WSH Shell object, pass the argument "WScript.Shell" to the CreateObject method:

Set objShell =CreateObject("WScript.Shell")

2.1 Reading the Command-Line Arguments

Problem

You want to read the command-line arguments.

Solution

All versions of WSH support the WScript object's Arguments property to get the command-line arguments. The following script attempts to set the read-only attribute for a file that is specified by a command-line argument:

'hidefile.vbs Dim objFileSystem, objFile 'check if the parameter count is a single parameter. ' If not then show the command syntax If WScript.Arguments.Count<>1 Then WScript.Echo "Syntax: "& WScript.ScriptName & _ " FileName " & vbCrLf & _ " Filename: the

path

of the file you wish to hide" WScript.Quit End If 'create FileSystem object Set objFileSystem = CreateObject("Scripting.FileSystemObject") On Error Resume Next 'get the file specified in command line Set objFile = objFileSystem.GetFile(WScript.Arguments(0)) 'check if error occured - file not found If Err Then WScript.Echo "Error:File:'" & WScript.Arguments(0) & "' not found" Else objFile.Attributes = 2 End If

WSH 5.6 introduces new elements to the WSF file format that allow for greater control in argument creation as well as a consistent method of script documentation. The following script performs the same operation as the first solution script using these new elements:

<job> <runtime> <description> The hidefile.wsf filename script sets the hidden attribute for a specified file </description> <named name="FileName" helpstring="

Name

of file to hide." type="string" required="True" /> <example> This is an example of how to use this script: Hidefile.wsf Filename:data.doc </example> </runtime> <script language=" VBScript"> If Not WScript.Arguments.Named.Exists("FileName") Then WScript.Arguments.ShowUsage WScript.Quit End If Set objFileSystem = CreateObject("Scripting.FileSystemObject") On Error Resume Next 'get the file specified in command line strFile = WScript.Arguments.Named("FileName") Set objFile = objFileSystem.GetFile(strFile) 'check if error occured - file not found If Err Then WScript.Echo "File:'" & strFile & "' not found" Else objFile.Attributes = 2 End If </script> </job>

Discussion

The Arguments collection contains the parameters that are passed to the script.

The Arguments collection is returned from the WScript object, which is a root WSH object and does not need to be created using CreateObject . The collection has a Count property that returns the number of items in the collection. The argument count is also accessible through the length property, which is included for JScript compatibility.

The Arguments collection is represented as an array with a 0 offset. The first argument would be stored as element 0, the second as 1, and so on. In the following command line, Fred is the first argument and Smith is the second:

Test.vbs Fred Smith

The following snippet represents the test.vbs script:

'test.vbs WScript.Echo "Argument 1 is " & WScript.Arguments(0) WScript.Echo "Argument 2 is " & WScript.Arguments(1)

If you want Fred Smith to be read as a single argument, it must be surrounded by double quotes ( " " ):

test.vbs "Fred Smith"

If you attempt to obtain an argument from the collection that has not been passed in the command line, an error will occur. In the previous example, passing "Fred Smith" to the test.vbs script will generate an error because the script attempts to display a second argument and "Fred Smith" is considered to be one argument.

The following example lists all parameters passed to the script:

'get a reference to the arguments collection 'output the first argument WScript.Echo WScript.Arguments(0) 'show each command line argument For Each arg in WScript.Arguments WScript.Echo arg Next

WSH version 2.0 and later supports drag-and-drop argument passing. Any files dragged onto a script file using Explorer can be obtained through the Arguments collection.

WSH version 5.6 (the version after 2.0) provides a more sophisticated command-line parameter handling using XML constructs in WSF files. This is provided through the XML <runtime> element.

The advantage of this new element is that it provides a consistent method of documenting WSH scripts, as well as easier parsing of command-line arguments, which leads to less code.

The <runtime> element appears at the beginning of a WSF file, inside the body of the job element. It can contain a number of elements that describe the script's arguments and provide examples.

The first element is the <description> element. Any text between the beginning and end element is used for a script description, or whatever you want to put there. This is much easier than attempting to format a large block using WScript Echo statements.

<description> Anything that appears between the description elements will appear as a script description. </description>

Following the <description> element is the <named> element. There can be one or more occurrences of this element, and it is used to describe parameters that can be passed to the script.

The <named> element contains a number of attributes, as listed in Table 2-1.

Table 2-1: <Named> Element Attributes

CONSTANT

TYPE

DESCRIPTION

Name

String

Argument name

Helpstring

String

Argument description

Type

String

Argument type: string, Boolean, or simple

Required

Boolean

Indicates whether parameter is required or not

The name attribute identifies the command-line parameter, while the helpstring attribute describes the parameter's function.

The type attribute identifies the parameter type. If the type is a string, the argument is expected to appear as /argumentname:stringvalue in the command line, where the argumentname represents the name of the argument as described with the name attribute and stringvalue is the argument value.

The following <named> element defines the parameter user , which is a string type and is required:

<named name=" user" helpstring=" The name of the user to modify." type=" string" required=" true" />

In the following command-line sample, FredS is passed as the user argument:

Deluser.wsf /user:FredS

If the string argument contains spaces, surround the argument in double quotes:

Deluser.wsf /user:" Fred Smith"

If the argument is Boolean, it is toggled using /argumentname+ to indicate True , or /argumentname- to indicate a False argument value:

Deluser.wsf /Update+

Setting the type to simple indicates that no value is required for the argument.

Once all arguments have been defined, an <example> element can be added to provide script usage samples. The <example> element is similar to the <description> element, where text can flow over multiple lines.

The following code snippet contains a complete sequence of argument elements that provides a script description, defines three command-line arguments, and displays example text on how to use the script:

<runtime> <description> This script is a sample script that

demonstrates

how to define command line arguments. </description> <named name=" StringArg" helpstring=" Sample string argument." type=" string" required=" True" /> <named name=" SimpleArg" helpstring=" Sample simple argument" type=" simple" required=" false" /> <named name=" BooleanArg" helpstring=" Boolean argument" type=" Boolean" required=" false" /> <example> This is an example of how to use this script: Argex.wsf StringArg:testing /SimpleArg BooleanArg+ </example> </runtime>

Note 

No validation is performed against the arguments defined using the named and unnamed elements. No error message is returned if a "required" argument is not passed or an invalid data type is passed for an argument. Checking if an argument is passed and is the correct data type should be performed in code. The <runtime> element is intended more for documentation than data validation purposes.

The named arguments are accessed through the WScript.Arguments.Named object. Use this object's Exists method to determine if an argument has been passed. The syntax is as follows :

bExists WScript.Arguments.Named.Exists(strArgument)

strArgument is the argument you want to check. It is not case-sensitive. The function returns True if the argument has been passed and False if not:

'check if name user argument has been passed If Not WScript.Arguments.Named.Exists("User") Then WScript.Echo "You must specify a user name" WScript.Quit End If

Named arguments are accessed through the WScript.Arguments.Named object's collection:

Value =WScript.Arguments.Named(strArgument)

strArgument is the argument you want to reference and it is not case-sensitive. If the argument does not exist, an empty string is returned and no error is generated.

Tip 

Any argument prefixed with a forward slash (/) can be referenced using the Named object, regardless if it has been defined in the <runtime> elements using the <named> tags.

Information defined in the <runtime> elements makes the script self-documenting , but it can also be displayed at script execution. If a script containing the <runtime> element is executed and /? is passed as a command-line parameter, the script information is displayed.

This information can be displayed by calling the WScript.Arguments.ShowUsage method from within a script. The solution script demonstrates this by executing this method if the argument count is 0.

WSH 5.6 also allows for "unnamed" arguments to be defined. An unnamed argument is an argument that does not have a corresponding named argument. In the following command line, the arguments joeb and 123456 are considered unnamed:

/name:freds joeb /flag+ /phone:5551234 123456

Any argument that does not have an associated argument name is stored in the Unnamed collection.

Unnamed arguments are useful when you have a mixture of arguments that might take an unknown number of values. To access unnamed arguments, reference the WScript.Arguments.Unnamed collection using a numeric value:

Value =WScript.Arguments.Unnamed(nArgument)

nArgument represents the argument position in the command line with a 0 offset.

Attempting to access the Unnamed collection when no unnamed arguments have been passed will generate an error. To determine if any unnamed arguments have been passed, use the WScript.Arguments.Unnamed.Count property, which returns the number of unnamed arguments in the command line.

Managing Enterprise Systems with the Windows Script Host
Authors: Borge S.
Published year: 2005
Pages: 12-13/242
Buy this book on amazon.com >>