Logon Scripts Using Windows Script Host

Logon Scripts Using Windows Script Host

In the long term, batch-processing files are not the solution of choice for complex scripting tasks. Therefore, Microsoft developed the Windows Script Host (WSH) concept. The WSH technology was introduced with Windows 2000 and seamlessly fit into the Microsoft component architecture strategy before the .NET Framework was introduced. Windows Server 2003 comes with Windows Script Host 5.6 and can therefore easily handle complex administrative tasks.

The command prompt uses the WSH and the existing Component Object Model (COM) interfaces to automate applications. The underlying script interpreters have been in use since Microsoft Internet Explorer version 3.0, particularly the two language dialects, Microsoft Visual Basic Script (VBScript) and JScript (a variant of Netscape JavaScript). Third-party manufacturers offer additional WSH scripting languages.

To execute scripts, systemwide available COM components are used. The Windows Server 2003 operating system manages and provides these components. Communication is handled by COM interfaces as in many conventional applications.

The COM components are based on different libraries that define constants, functions, objects, and events that, in turn, can be used by other applications or scripts. In this way, these scripting engines supply functions for interpreting scripts in a defined language syntax. Scripting engines are realized as ActiveX components that can be used by the Windows Script Host.

WSH Runtime Environment

The command prompt’s script language can easily be expanded with this concept. The user or administrator uses object-oriented options for generating powerful console scripts and for controlling the entire user interface with command-line programs.

Windows Script Host can either run in a Windows mode (Wscript.exe) or in a command-line mode (Cscript.exe). There are three ways to run scripts with corresponding file extensions on a terminal server:

  • Double-clicking script files or their icons on the desktop

  • Using the Run... option in the Start menu by entering the complete script name

  • Executing Wscript.exe via the Run... option and the optional entry of parameters and arguments

If you run scripts in the command-line–based mode, use the following syntax:

Cscript [Parameters] Scriptname.Extension [Options] [Arguments]

The host parameters enable or disable different Windows Script Host options. These parameters always begin with a double slash (//). The script name is indicated by its extension—for example, Chart.vbs for a Visual Basic script. Script parameters (options and arguments) always begin with a single slash (/).

The most important host parameters of the Cscript command are listed in Table 7.6.

Table 7.6: Host Parameters of the Cscript Command




Interactive mode (opposite of //B).


Batch mode. Suppresses display of script errors and user queries.


Time limit in seconds. Maximum time for running a script (default value: unlimited). Suppresses uncontrolled script processes for an extended period of time.


Shows a WSH logo message at execution time (default setting, opposite of //nologo).


Suppresses display of WSH logo message.

//H:Cscript or Wscript

Defines Cscript or Wscript as the default application to run scripts (default setting: Wscript).


Saves the current command-line options for the current user.


Enables debug mode.


Executes the script in the debugger.


Specifies a job that is executed within the script. Different jobs are defined in XML syntax.


Displays help information. Corresponds to running Cscript without parameters.

The easiest way to generate scripts is by using Notepad, but Microsoft Script Debugger and Microsoft Script Editor are much more powerful.

Object-Oriented Programming Model

What exactly is an object? This is the question many administrators ponder if they have never had to do object-oriented programming before. First of all, an object is simply a thing with a set of characteristics and attributes that describe the object. In principle, objects are divided into several categories, all relating to different units: users, groups, computers, printers, networks, or applications. Each of these objects has a set of properties that describes it in detail. Furthermore, each object can perform actions using methods. You might, for instance, look at a user object with these properties: user name, ID, and password. It might have methods to create, delete, or modify passwords. However, you need to create the user object before you can interact with it.

Before accessing an object’s properties and methods, a corresponding instance needs to be created using two methods provided in the WSH runtime environment: CreateObject and GetObject. The concept of calling up a method within an object is radically different from using tools in batch-processing scripts as described previously. CreateObject is also a function in VBScript, which somewhat simplifies its use. As a result, the easiest syntax for creating an object instance is this:

set ObjectRef = CreateObject (“strApp.strObject” [, “strServerName"])

The CreateObject function returns the object instance that is to be used. The most important parameter for creating the object instance is ProgID (strApp.strObject, for example Scripting.FileSystemObject or Wscript.Shell). Using both object reference and point operator, the appropriate method can be found.

ObjectRef.ObjectMethod Parameter1, Parameter2

A special Wscript object library that comes with Windows Script Host allows access to the registry, file links, system folders, system properties, network drives, and network printers. The library can be invoked in the WSH Windows mode using Wscript and in the command-line mode using Cscript. Most of its objects are limited to the computer where the WSH script runs. This is why Windows Script Host is particularly suitable for logon scripts and standardized administration tasks.

The Wscript object has a number of properties and methods. These relate to Windows Script Host or the script being executed. Table 7.7 lists the most important methods in alphabetical order.

Table 7.7: The Most Important Wscript Object Methods




Adds printers


Creates an object and sets up system event processing


Disconnects an object from Windows Script Host


Displays the parameters in a window or in the command prompt


Gets an automation object from a file


Stops the script for the duration of n seconds


Controls older applications that do not have a COM interface by simulating keyboard input


Supports input and output via the command prompt


Ends the script execution

The Windows Script Host environment has additional COM-based libraries: WshNetwork, WshShell, and WshController. WshNetwork is used for network and printer connection access, while WshShell is suited for access to the desktop, environment variables, and the registry. The Collection, Environment, Shortcut, SpecialFolder, and UrlShortcut objects are not directly available. Instead, they are supplied by the methods of the other objects. Special Windows Server 2003 objects allow access to the Active Directory system information (ADSI) and Windows Management Instrumentation (WMI). The properties and methods of all these objects represent the entire functionality of Windows Script Hosts. Expansions through additional COM automation objects are possible at any time.


Using Windows Script Host requires solid knowledge of object-oriented programming. Normally, VBScript is the program language that is easiest to understand for beginners. JScript, on the other hand, is very well suited for administrators who are already familiar with Java, C, or C++. The objects available on the system, including all methods, can be analyzed with the OleView.exe tool.


In the following section, we will look at some WSH scripts that provide simple functions. Building on that information, new scripts can be created—for instance, for user logon, file administration, and adjusting the registry on a terminal server. In particular, we will highlight the possibility of performing very complex manipulations of character strings and modifying a user’s desktop settings.

Environment Variables

The Showvar.vbs script is used for displaying all environment variables. The shell object is needed to determine the data, and the echo method is needed to display the result.

Listing 7-9: The Showvar.vbs WSH Script
Start example
‘ Display all environment variables
‘ Origin: Showvar.vbs, Microsoft Corporation
CRLF = Chr(13) & Chr(10)

Dim WSHShell
Set WSHShell = WScript.CreateObject("WScript.Shell")

Sub show_env(strText)
 WScript.Echo "WSH—Environment Variables", CRLF, strText 
End Sub

intIndex = 0
strText = ""
intNumEnv = 0
For Each strEnv In WshShell.Environment("PROCESS")
 intIndex = intIndex + 1
 strText = strText & CRLF & Right(" " & intIndex, 4) & " " & strEnv
 intNumEnv = intNumEnv + 1

If intNumEnv >= 1 Then Call show_env(strText)
End example

This is an excellent example of showing how results are processed in a character string.

Network and Registry Access

Administrative scripts often need to access network resources. The WshNetwork object provides many methods for this purpose. The most popular one is mapping a shared network drive using MapNetworkDrive.

WSHNetwork.MapNetworkDrive strDrive, strShare

Another requirement for the administration of terminal server environments is the adequate access to the registry, including creating, modifying, and deleting registry keys and values. Listing 7-10 shows a sequence that creates and then deletes a key in the registry.

Listing 7-10: Creating and Deleting a Registry Key
Start example
Dim WSHShell
Set WSHShell = WScript.CreateObject("WScript.Shell")
WSHShell.RegWrite "HKCU\MyRegKey\", "Top level key"
WSHShell.RegWrite "HKCU\MyRegKey\Entry\", "Second level key"
WSHShell.RegWrite "HKCU\MyRegKey\Value", 1
WSHShell.RegWrite "HKCU\MyRegKey\Entry", 2, "REG_DWORD"
WSHShell.RegWrite "HKCU\MyRegKey\Entry\Value1", 3, "REG_BINARY"
WSHShell.RegDelete "HKCU\MyRegKey\Entry\Value1"
WSHShell.RegDelete "HKCU\MyRegKey\Entry\"
WSHShell.RegDelete "HKCU\MyRegKey\"
End example

Verifying the Group

Finally, we pick up the KiXtart example introduced earlier to verify a user’s group during logon. Depending on the group, the server containing the home directory is then assigned. This is a frequently performed action on terminal servers.

Listing 7-11: Verifying a Group
Start example
‘ Creation of required objects
Set WshNetwork = CreateObject("Wscript.Network")
Set UserObj = GetObject("WinNT://" & WshNetwork.UserDomain & "/" & WshNetwork.UserName)

‘ Check group
For each GroupObj in UserObj.Groups
 select case GroupObj.Name
 case "marketing"
 WshNetwork.MapNetworkDrive "U:", "\\FILESRV1\home\" & WshNetwork.UserName
 case "development"
 WshNetwork.MapNetworkDrive "U:", "\\FILESRV2\home\" & WshNetwork.UserName
 End Select
End example

The same concept can be used to modify the user’s terminal server settings. This example performs only two changes; the comments include additional options.

Listing 7-12: Changing a User’s Terminal Server Settings
Start example
‘ Creation of required objects
Set WshNetwork = CreateObject("Wscript.Network")
Set UserObj = GetObject("WinNT://" & WshNetwork.UserDomain & "/" & WshNetwork.UserName)

‘ Changing terminal server settings
UserObj.TerminalServicesInitialProgram = "C:\Program Files\Internet Explorer\iexplore.exe"
UserObj.TerminalServicesWorkDirectory = "C:\windows"
‘ UserObj.ConnectClientDrivesAtLogon = 1
‘ UserObj.ConnectClientPrintersAtLogon = 1 
‘ UserObj.DefaultToMainPrinter = 1
‘ UserObj.TerminalServicesProfilePath = "\\FILESRV1\profiles\" & WshNetwork.UserName
‘ UserObj.TerminalServicesHomeDirectory = "\\FILESRV2\home\" & WshNetwork.UserName
‘ UserObj.TerminalServicesHomeDrive = "U:"
‘ UserObj.AllowLogon = 1
‘ UserObj.MaxDisconnectionTime = 30
‘ UserObj.MaxConnectionTime = 0
‘ UserObj.MaxIdleTime = 120
‘ UserObj.BrokenConnectionAction = 0
‘ UserObj.ReconnectionAction = 0
‘ UserObj.EnableRemoteControl = 1
End example

It is easy to combine the script fragments introduced in this section with powerful tools. The diverse potential possibilities can, of course, only be hinted at in this book.