What's New In WSH 5.6

Several areas of functionality have been addressed in this latest version of the Windows Script Host (version 5.6).

  • Argument handling has been improved — Handling and documenting command line arguments is simpler. The process of integrating your scripts with other command line scripts has been simplified, and it is easier to create scripts that can supply the user with help information. Refer to the following table for information on the WSH language features that connect you to this new functionality.
    To Learn About | See
    Grouping your script's switches together. | <runtime> Element
    Defining your script's named switches. | <named> Element
    Defining your script's unnamed switches. | <unnamed> Element
    Making your script self-documenting. <example> Element

    <description> Element
    Sharing the environment of the current process (IOW, WSH) with a spawned process. | Exec Method
    Accessing the standard streams programmatically. Exec Method

    WshScriptExec Object
    Accessing environment variables programmatically. Environment Property

    WshEnvironment Object

    ExpandEnvironmentStrings Method

    Remove Method
    Determining whether a spawned script process is currently running. | Status Property (WshScriptExec)
    Accessing the spawned script process's StdIn input stream. | StdIn Property (WshScriptExec)
    Accessing the spawned script process's StdOut output stream. | StdOut Property (WshScriptExec)
    Accessing the spawned script process' StdErr output stream. | StdErr Property (WshScriptExec)
    Terminating a spawned script process. | Terminate Method (WshScriptExec)
    Accessing the named command-line script arguments. | WshNamed Object
    Determining whether a specific key value exists in the WshNamed object. | Exists Method
    Determining the number of switches in the WshNamed or WshUnnamed objects. | Count Method
  • You can run scripts remotely — You can load scripts onto several remote computer systems and start them all running simultaneously. While a remote script is running, you can check its progress. After it has finished, you can ensure that it ran correctly or determine the cause of its premature termination. There is a new dispatch object used to create remote WSH objects — the Controller object. In addition, there is a new object that represents an instance of a running script — the Remote WSH object.
    To Learn About | See
    Creating a remote script object — the remote WSH interface. | WshController Object
    Creating a remote script object — using remote WSH interface. | CreateScript Method
    Creating a remote script object — getting a handle. | WshRemote Object
    Starting a remote script process. | Execute Method
    Determining whether a remote script is currently running. | Status Property (WshRemote)
    Determining why a remote script terminated. | Description Property (WshRemoteError)
    Identifying which statement in your remote script caused it to terminate. | Line Property (WshRemoteError)
    Accessing error information after a remote script terminates. | WshRemoteError Object
    Identifying the character in the line of code that contained the error. | Character Property
    Identifying the error number representing a script error. | Number Property
    Identifying the source of the script error. | Source Property
    Identifying the line of source code that caused an error. | SourceText Property
    Handling remote object events. Start Event

    End Event

    Error Event
  • When you start new processes, you can treat them as objects — You determine the status of spawned processes and access their standard I/O streams.
    To Learn About | See
    Spawning a process. | Exec Method
    Accessing the object that represents running processes. | WshScriptExec Object
    Accessing process status information. | Status Property (WshScriptExec)
    Accessing the standard I/O streams. | StdOut Property (WshScriptExec)
    StdIn Property (WshScriptExec)
    StdErr Property (WshScriptExec)
  • You can access the current working directory — You can determine/modify the active process's current working directory.
    To Learn About | See
    Accessing the active directory information. | CurrentDirectory Property
  • Security issues unique to scripts have been addressed — A new security model makes distributing and running scripts safer.
    To Learn About | See
    Script signing and verification. | Security and Windows Script Host


Upgrading

Upgrading Windows Script Host

If you are currently using Windows 2000 or Windows ME, you have version 2.0 of WSH installed on your computer system. If you are running Windows 95, 98, or Windows NT 4.0, you have version 1.0. To upgrade to WSH 5.6, visit the Microsoft Windows Script Technologies Web site at (http://msdn.microsoft.com/scripting/).

Note The latest version of WSH is 5.6 due to a file versioning issue that was easiest to resolve by skipping some version numbers.


Version Information

WSH Version Information

The following table lists the version of Windows Script Host implemented by Microsoft host applications.

Host Application | 1.0 | 2.0 | 5.6
Microsoft Windows 98 | x |  |
Microsoft Windows NT 4 Option Pack | x |  |
Microsoft Windows 2000 |  | X |

The following table lists Windows Script Host language elements and the version in which they were introduced.

Language Element | 1.0 | 2.0 | 5.6
<?job ?> Element |  | X |
<?XML ?> Element |  | X |
AddPrinterConnection Method | x |  |
AddWindowsPrinterConnection Method |  | X |
AppActivate Method |  | X |
Arguments Property | x |  |
AtEndOfLine Property |  | X |
AtEndOfStream Property |  | X |
Character Property |  |  | x
Close Method |  | X |
Column Property |  | X |
ComputerName Property | x |  |
ConnectObject Method |  | x |
Count Method | x |  |
CreateObject Method | x |  |
CreateScript Method |  |  | x
CreateShortcut Method | x |  |
Description Property | x |  |
Description Property (WshRemote) |  |  | x
DisconnectObject Method | x |  |
Echo Method | x |  |
EnumNetworkDrives Method | x |  |
EnumPrinterConnections Method | x |  |
Environment Property | x |  |
Error Property (WshRemote) |  |  | x
<example> Element |  |  | x
Exec Method |  |  | x
Execute Method |  |  | x
Exists Method |  |  | x
ExitCode Property |  |  | x
ExpandEnvironmentStrings Method | x |  |
FullName Property | x |  |
GetObject Method | x |  |
GetResource Method |  | x |
HotKey Property | x |  |
IconLocation Property | x |  |
Item Property | x |  |
Item Property (WshNamed) |  |  | x
Item Property (WshUnnamed) |  |  | x
<job> Element |  | x | x
Length Property | x |  |
Line Property |  | x |
Line Property (WshRemote) |  |  | x
LogEvent Method |  | x |
MapNetworkDrive Method | x |  |
Name Property | x |  |
<named> Element |  |  | x
Number Property |  |  | x
<object> Element |  | x |
<package> Element |  | x |
Path Property | x |  |
Popup Method | x |  |
ProcessID Property |  |  | x
Quit Method | x |  |
Read Method |  | x |
ReadAll Method |  | x |
ReadLine Method |  | x |
<reference> Element |  | x |
RegDelete Method | x |  |
RegRead Method | x |  |
RegWrite Method | x |  |
Remove Method | x |  |
RemoveNetworkDrive Method | x |  |
RemovePrinterConnection Method | x |  |
<resource> Element |  |  |
Run Method | x |  |
<runtime> Element |  |  | x
Save Method | x |  |
<script> Element |  | x |
ScriptFullName Property | x |  |
ScriptName Property | x |  |
SendKeys Method |  | x |
SetDefaultPrinter Method | x |  |
ShowUsage Method |  |  | x
Skip Method |  | x |
SkipLine Method |  | x |
Sleep Method |  | x |
Source Property |  |  | x
SourceText Property |  |  | x
SpecialFolders Property | x |  |
Status Property (WshRemote) |  |  | x
Status Property (WshScriptExec) |  |  | x
StdErr Property |  | x |
StdErr Property (WshScriptExec) |  |  | x
StdIn Property |  | x |
StdIn Property (WshScriptExec) |  |  | x
StdOut Property |  | x |
StdOut Property (WshScriptExec) |  |  | x
TargetPath Property | x |  |
Terminate Method (WshScriptExec) |  |  | x
<usage> Element |  |  | x
UserDomain Property | x |  |
UserName Property | x |  |
Version Property | x |  |
WindowStyle Property | x |  |
WorkingDirectory Property | x |  |
Write Method |  | x |
WriteBlankLines Method |  | x |
WriteLine Method |  | x |
WScript Object | x |  |
WshArguments Object | x |  |
WshController Object |  |  | x
WshEnvironment Object | x |  |
WshNamed Object |  |  | x
WshNetwork Object | x |  |
WshRemote Object |  |  | x
WshRemoteError Object |  |  | x
WshScriptExec Object |  |  | x
WshShell Object | x |  |
WshShortcut Object | x |  |
WshSpecialFolders Object | x |  |
WshUnnamed Object |  |  | x
WshUrlShortcut Object | x |  |


Types of Script Files

Stand-alone scripts come in several varieties, and each has its own extension. The following table is a list of some common types.

Extension | Script Type | Description
.bat | MS-DOS batch file | MS-DOS operating system batch file
.htm | ASP page | Active Server Page file
.html | HTML file | Web page
.js | JScript file | Windows script
.vbs | VBScript file | Windows script
.wsf | Windows Script Host file | Container or project file for a Windows script; supported by WSH 2.0 and later.
.wsh | Windows Script Host files | Property file for a script file; supported by WSH 1.0 and later.

Each script type is suited to different application needs, and each has strengths and weaknesses. The script type you choose depends on your needs.

Still, there are certain scenarios where you could divide your overall problem into several smaller parts, writing a separate script for each part with each script written in the most suitable scripting language.

This is where Windows Script Host files (WSF files) are useful. WSF files may include other script files as part of the script. Consequently, multiple WSF files can reference libraries of useful functions, which may be created and stored in a single place.

See Also

Windows Script Host Object Model


Using WSF files

Using Windows Script Files (.wsf)

A Windows script (*.wsf) file is a text document containing Extensible Markup Language (XML) code. It incorporates several features that offer you increased scripting flexibility. Because Windows script files are not engine-specific, they can contain script from any Windows Script compatible scripting engine. They act as a container.

With .wsf files, you can take advantage of the following features as you create your scripts:

.wsf files support | You can
Include statements | Incorporate functions from VBScript or JScript files into your Windows Script Host project.
Multiple engines | Use more than one scripting language per file.
Type libraries | Add constants to your code.
Tools | Edit files with any XML editor.
Multiple jobs in one file | Store all of your code in a single location.

Include Statements

If you have .js and .vbs files from previous Windows Script Host projects, a .wsf file enables you to use them with Windows Script Host. A .wsf file encapsulates a library of functions that can in turn be used by multiple .wsf files.

The following example shows a .wsf file that includes a JScript file (fso.js), plus a VBScript function that calls a function (GetFreeSpace) in the included file. The contents of fso.js are also shown.

<job id="IncludeExample">
   <script language="JScript" src="FSO.JS"/>
   <script language="VBScript">
      ' Get the free space for drive C.
      s = GetFreeSpace("c:")
      WScript.Echo s
   <sScript>
</job>

The fso.js file contains the following:

function GetFreeSpace(drvPath) {
   var fs, d, s;
   fs = new ActiveXObject("Scripting.FileSystemObject");
   d = fs.GetDrive(fs.GetDriveName(drvPath));
   s = "Drive " + drvPath + " - " ;
   s += d.VolumeName;
   s += " Free Space: " + d.FreeSpace/1024 + " Kbytes";
   return s;
}

Multiple-Engine Support

Since one scripting language may not have all the functionality you need, Windows Script Host allows you to combine multiple languages in a single .wsf file. The following example shows a .wsf file that includes both VBScript and PerlScript code:

<job id="PERLandVBS">
   <script language="PerlScript">
      sub PerlHello {
         my $str = @_[0];
         $WScript->Echo($str);
      }
   </script>

   <script language="VBScript">
      WScript.Echo "Hello from VBScript"
      PerlHello "Hello from PERLScript"
   </script>
</job>

Type Library Support

In the following example, "MyComponent" was developed with Microsoft Visual Basic 5.0. "MyComponent" defines the constant MyError with the following statement.

Public Const MyError = "You are not using MyComponent correctly"

The type library is contained in mycomponent.lib, which is installed in C:\MyComponent.

<job id="IncludeExample">
   <reference progid="MyComponent.MyClass">
   <script language="VBScript">
      Dim MyVar
      Set MyVar = CreateObject("MyComponent.MyClass")
      Currentreturn = MyVar.MyMethod
      If Currentreturn = False then
         WScript.Echo MyError
      End If
   </script>
</job>

Tools Support

Since the .wsf file is in XML format, you can use any editor that supports XML to edit .wsf files. This includes text editors, such as Notepad.

Multiple Jobs in One File

Instead of keeping all your scripts in separate files, you can incorporate them all into one .wsf file and break them into several different jobs. You can then run each job separately using syntax similar to the following example, where "MyFirstJob" is the name of the job contained in the MyScripts.wsf file.

CScript //Job:MyFirstJob MyScripts.wsf


Drag and drop support

WSH Drag and Drop Support

You can drag files onto a WSH script. The file names are translated into arguments on the command line. These file names can be displayed in a list, which you can use to manipulate files with any scripting object.

To display a script's argument list

  1. Create a file and give it a name with a script extension (for example, DragDrop.vbs).
  2. Add code to the script file, for example:
    Set objArgs = WScript.Arguments
For I = 0 to objArgs.Count - 1
   WScript.Echo objArgs(I)
Next
  3. Save the file to your hard disk.
  4. Drag and drop any file or files onto your saved file. In the example, the file names are echoed back to the screen.

The number of files you can drag onto a script is limited by the your system's maximum command-line length. If the total number of characters in all file names being dragged exceeds this limit, the drag and drop operation fails.


Script Properties - WSH File

Setting and Customizing Script Properties (.wsh)

You can record specific settings for each of your individual scripts by means of a Windows Script Host control (.wsh) file. The .wsh file is a text document in which you can customize execution of one or more of your scripts. It is created automatically when you set the properties for a supported script file.

If you create multiple .wsh files for a single script, you can tailor the way the script runs to the needs of specific groups or even individuals within an organization. For example, you could create a single logon script that is invoked by two different .wsh files that contain different settings and parameters.

When you double-click a .wsh file or run it from the command line, CScript.exe or WScript.exe reads the .wsh file to determine the specific settings that should be used to execute the script. CScript/WScript executes the original script, passing in the properties that are defined within the .wsh file.

To create a .wsh file for a given script

  1. Right-click the script file in Windows Explorer.
  2. Click Properties on the shortcut menu.
  3. Choose the settings you want for the script.
  4. Click OK or Apply.

    A .wsh file is created with the same name as the script file you selected.

The following example illustrates a typical .wsh file:

[ScriptFile]
Path=C:\WINNT\Samples\WSH\showprop.vbs
[Options]
Timeout=0
DisplayLogo=1
BatchMode=0

The path information in the [ScriptFile] section identifies the script file that is associated with the .wsh file. The keys in the [Options] section correspond to settings in the Script tab within the Properties dialog box.

Note You must have the original script file present when executing the .wsh file. If the .wsh file fails to run the script, check the Path= information in the .wsh file to ensure that it points to the script you are attempting to run.


Cscript and Wscript

Running Scripts from Windows

Windows Script Host enables you to run scripts from Windows. WScript.exe provides a Windows-based dialog box for setting script properties. Using WScript.exe, you can run scripts under Windows in the following ways. Whether you use WScript or CScript, you still run the scripts in the same manner. The difference is only in the output — WScript generates windowed output, while CScript sends its output to the command window in which it was started.

On initial installation, the default host is WScript. To change it to CScript, type the following at the command line:

cscript //h:cscript

Or, to change it from Cscript to Wscript:

wscript //h:cscript

To run a script using the default engine:

  1. Double click the script in Windows Explorer or on the desktop.
  2. Click Start, select Run, and enter the script name.
    Note On Windows NT and Windows 2000 only, simply enter the script name on a command line.

To run a script using a particular engine:

  • Right-click the script in Windows Explorer and select Open to run in WScript or Open in MS-DOS Window (Windows 9x) or Open in Command Window (Windows NT and Windows 2000) to run in CScript.

-or-

  • Click Start, select Run, enter "cscript" or "wscript" followed by the script name.

-or-

  • Enter "cscript" or "wscript" on the command line, followed by the script name.

To run scripts using WScript.exe

  • Double-click files or icons. These can be files or icons listed in My Computer, Windows Explorer, the Find window, the Start menu, or on the desktop.

-or-

  1. Click the Start button, and then click Run.
  2. In the Open field, type the full path of the script, and then click OK. You can also type WScript followed by the full name and path of the script you want to run.

If you double-click a script file whose extension has not yet been associated with WScript.exe, the Open With dialog box appears and asks which program to use to open the file. Choose WScript and check Always use this program to open this file to register WScript as the default application for all files with that extension.

The WScript.exe and CScript.exe properties dialog box provides the following options:

Property | Description
Stop script after specified number of seconds. | Specifies the maximum number of seconds that a script can run. The default is no limit. CScript.exe equivalent: //T:nn
Display logo when script is executed in command console. | Displays a banner before running the script. This is the default. The opposite is //nologo. CScript.exe equivalent: //logo or //nologo

Using the WScript.exe Properties dialog box, you can set global scripting options for all scripts that WScript runs on the local machine. You can also set options for individual scripts using a .wsf file.

WScript.exe and CScript.exe Options

For the most part, options listed in the following table are applicable to both WScript.exe and CScript.exe. Exceptions are noted.

Parameter | Description
//B | Batch mode; suppresses command-line display of user prompts and script errors. Default is Interactive mode.
//D | Turns on the debugger.
//E:engine | Executes the script with the specified script engine.
//H:CScript or //H:Wscript | Registers CScript.exe or WScript.exe as the default application for running scripts. If neither is specified, WScript.exe is assumed as the default.
//I | Default. Interactive mode; allows display of user prompts and script errors Opposite of Batch mode.
//Job:<JobID> | Runs the specified JobID from the .wsf file.
//logo | Default. Displays a banner. Opposite of nologo.
//nologo | Prevents display of an execution banner at run time. Default is logo.
//S | Saves the current command-line options for this user.
//T:nn | Enables time-out: the maximum number of seconds the script can run. The default is no limit. The //T parameter prevents excessive execution of scripts by setting a timer. When execution time exceeds the specified value, CScript interrupts the script engine using the IActiveScript::InterruptThread method and terminates the process.
//U | Used with Windows NT and Windows 2000 to force the command line output to be in Unicode. There is no way for CScript to determine whether to output in Unicode or ANSI; it defaults to ANSI.
//X | Launches the program in the debugger.
//? | Displays a brief description of and usage information for command parameters (the usage information).


Remote Script

Setting up Remote WSH

Remote WSH, which is a new technology included in WSH 5.6, provides the ability to run a script on a remote machine or machines. With Remote WSH, the script is physically copied from the local machine to the remote machine before executing. In order to enable Remote WSH functionality, you must first set up the remote machine with the proper security settings. The steps below perform the tasks that enable Remote WSH.

Note Both the remote and local machines must be running Windows NT 4 SP3 or greater in order to use Remote WSH.

To enable a machine to run remote scripts

  1. Install WSH V5.6 on the machine. If you are using Windows 2001 or have installed Internet Explorer 6 or greater, WSH 5.6 has already been installed.
    Note WSH 5.6 is available for download from the web at http://msdn.microsoft.com/scripting
  2. Add yourself to the remote machine's Local Administrators group.
  3. To enable Remote WSH, use Poledit.exe on the server.
    Note An administrator who wants to enable Remote WSH must either acquire the Windows 2000 resource kit, or use http://msdn.microsoft.com/scripting to acquire the necessary windowsscript.adm file that contains the WSH settings. The windowsscript.adm file must be copied to the server that sets the gapplicabel group's policies. Although it is not necessary to copy the file to the server's \WINNT\INF directory, this is nonetheless where the default adm files are located.
    Note For more information on Poledit.exe, see the Poledit.exe's online help system.
  4. WSH should now be enabled on the machine. To test it, do the following:

Running Scripts Remotely

WSH 5.6 can run scripts that reside on remote systems. The following scripts demonstrate this capability. These scripts make the assumption that the files are located on a local machine directory called "c:\wsh5.6"; change the local path and the remote machine name as necessary.

After initially running RemoteTest.WSF on the local machine, there may be a small pause as DCOM verifies your identity. After you see the "Done" message, a file named "c:\beenhere.txt" on the remote machine indicates the time that you executed the command (from the remote computer's clock).

// JScript.
RemoteTest.WSF
-------------------------------
<package>
<job>
<script language="JScript">
var oController = new ActiveXObject("WSHController");
var oProcess = oController.CreateScript("c:\\wsh5.6\\beenhere.wsf", "remmachine");
oProcess.Execute();
while (oProcess.Status != 2) WScript.Sleep(100);
WScript.Echo("Done");
</script>
</job>
</package>
-------------------------------
BeenHere.WSF
-------------------------------
<package>
<job>
<script language="JScript">
var fso = new ActiveXObject("Scripting.FileSystemObject");
var fout = fso.CreateTextFile("c:\\beenhere.txt", true);
fout.WriteLine(new Date);
fout.Close();
</script>
</job>
</package>
-------------------------------

' VBScript.
RemoteTest.WSF
-------------------------------
<package>
<job>
<script language="VBScript">
set oController = CreateObject("WSHController")
set oProcess = oController.CreateScript("c:\wsh5.6\beenhere.wsf", "remmachine")
oProcess.Execute
While oProcess.Status <> 2
   WScript.Sleep 100
WEnd
WScript.Echo "Done"
</script>
</job>
</package>
-------------------------------

BeenHere.WSF
-------------------------------
<package>
<job>
<script language="VBScript">
set fso = CreateObject("Scripting.FileSystemObject")
set fout = fso.CreateTextFile("c:\beenhere.txt", true)
fout.WriteLine Now
fout.Close
</script>
</job>
</package>


WMI - Windows Management Instrumentation

WSH and Windows Management Instrumentation (WMI)

With WSH you can easily use Windows Management Instrumentation (WMI). The following scripts demonstrate using WSH and WMI to retrieve a user's logon time via ADSI.

Note For more information on WMI, see the WMI SDK at (http://msdn.microsoft.com).
// JScript.
LoginProfiles = GetObject("winmgmts:").InstancesOf ("Win32_NetworkLoginProfile");
for(e = new Enumerator(LoginProfiles) ; !e.atEnd() ; e.moveNext())
{
   Profile = e.item();
   WScript.Echo(Profile.Name);
   WScript.Echo(Profile.LastLogon);
}

' VBScript.
Set LoginProfiles = GetObject("winmgmts:").InstancesOf ("Win32_NetworkLoginProfile")
   for each Profile in LoginProfiles
      WScript.Echo Profile.Name
      WScript.Echo Profile.LastLogon
   next

See Also

WSH Walkthrough

The following walkthrough describes how a typical Network Administrator or other IT professional might use WSH 5.6 to create procedures that accomplish useful tasks.

Note The walkthrough is presented in VBScript. The process for creating these scripts is nearly the same for developers using VBScript or JScript.

During the course of this walkthrough, you will perform the following activities:

  • Create a script that creates a common share on several remote machines and populate it with files.
  • Create a script that creates a common Printing Device connection on several remote machines and establish it as the default printing device.

To complete the walkthrough, all remote machines must be properly configured to enable Remote WSH. For more information on enabling these security settings, see Setting up Remote WSH.

Note The following code is from the sample included in this documentation. To view the entire sample, see WSH Network Administrator Sample Script.

Create Variables and Constants

To create the necessary variables and constants

  1. In your text-scripting editor, enter the variables.
    Dim FSO
Dim Services
Dim SecDescClass
Dim SecDesc
Dim Trustee
Dim ACE
Dim Share
Dim InParam
Dim Network
  2. In your text-scripting editor, enter the constants, changing the values to reflect the UNC names and paths applicable to your network environment.
    Const FolderName = "C:\Public"
Const AdminServer = "\\AdminMachine"
Const ShareName = "Pubs"
Const PrinterShare = "\\CorpPrinters\PrinterShare"

Connecting to a printer and setting it as default

To connect the machine to a common printing device

  • In your text-scripting editor, enter the code that creates a printing device. This code uses the Network variable and PrinterShare constant initialized in the previous step.
    Set Network = CreateObject("Wscript.Network")
Network.AddWindowsPrinterConnection PrinterShare

To set the machines default printing device

  • In your text-scripting editor, enter the code that sets the default printing device. This code uses the Network variable and PrinterShare constant initialized in the first step.
    Network.SetDefaultPrinter PrinterShare

Creating a common share, copying files to it, and sharing it

To create a common share on the machine

  • In your text-scripting editor, enter the code that creates a File System Object (FSO) and creates a folder. The script verifies the existence of the folder. If the folder does not exist, the script creates it. This code uses the FSO variable and the FolderName constant initialized in the first step.
    Set FSO = CreateObject("Scripting.FileSystemObject")
If Not FSO.FolderExists(FolderName) Then
   FSO.CreateFolder(FolderName)
End If

To copy files to the newly created folder

  • In your text-scripting editor, enter the code that creates a File System Object (FSO) and copies files from your local machine to the remote machine. This code uses the FSO variable and the FolderName constant initialized in the first step.
    Call FSO.CopyFile(AdminServer & "\Public\Images\*.*", FolderName)

To establish the newly created folder as a share with WMI

  • In your text-scripting editor, enter the code that creates a share using Windows Management Instrumentation (WMI). The share is established on the folder generated above. The script first connects to WMI. Next, it sets the security impersonation level and the Windows NT privilege that lets you set Discretionary Access Control Lists (DACLs) and Security Access Control Lists (SACLs). Next, it creates a new security descriptor and sets up a couple of Access Control Entries (ACEs) for the new share. Finally, it creates a new share with the new security descriptor. This code uses the Services, SecDescClass, SecDesc, Trustee, ACE, Share, and InParam variables, and the FolderName, AdminShare, and ShareName constants initialized in the first step.
    Note WMI is a powerful, sophisticated technology based on Web Based Enterprise Management (WBEM). WMI is primarily used for accessing and instrumenting management information in an enterprise environment. For more information on WMI, see Microsoft Windows Management Instrumentation: Background and Overview at (http://msdn.microsoft.com/library/default.htm?URL=/library/backgrnd/html/wmixwdm.htm).
    Set Services = GetObject("WINMGMTS:{impersonationLevel=impersonate,(Security)}!" & AdminServer & "\ROOT\CIMV2")
Set SecDescClass = Services.Get("Win32_SecurityDescriptor")
Set SecDesc = SecDescClass.SpawnInstance_()
Set Trustee = Services.Get("Win32_Trustee").SpawnInstance_
Trustee.Domain = Null
Trustee.Name = "EVERYONE"
Trustee.Properties_.Item("SID") = Array(1, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0)
Set ACE = Services.Get("Win32_Ace").SpawnInstance_
ACE.Properties_.Item("AccessMask") = 2032127
ACE.Properties_.Item("AceFlags") = 3
ACE.Properties_.Item("AceType") = 0
ACE.Properties_.Item("Trustee") = Trustee
SecDesc.Properties_.Item("DACL") = Array(ACE)
Set Share = Services.Get("Win32_Share")
Set InParam = Share.Methods_("Create").InParameters.SpawnInstance_()
InParam.Properties_.Item("Access") = SecDesc
InParam.Properties_.Item("Description") = "Public Share"
InParam.Properties_.Item("Name") = ShareName
InParam.Properties_.Item("Path") = FolderName
InParam.Properties_.Item("Type") = 0
Share.ExecMethod_("Create", InParam)

Running the Completed Script

The sample included in this documentation contains a complete, executable script with all of the functionality above. See WSH Network Administrator Sample Script.

Before running the script, ensure that all remote machines have been properly configured to run remote scripts. This is accomplished with Poledit.exe on the server. For more information, see Setting up Remote WSH.

When running remote WSH, the script is copied to the remote machines. Once the remote machine's security settings have been verified and the script is successfully copied, a return indicates success or failure. If successful, the script is then executed on the remote machines.

WSH Network Administrator Sample Script

This WSH network sample demonstrates how a typical network administrator may use a script on several remote machines on the network. The sample script performs useful administrative tasks including:

  • Connecting the machines to a network printing device
  • Setting the newly connected printing device as the default printer
  • Creating a common public folder on the machines
  • Copying files to the newly created folder
  • Establishing the newly created folder as a share using Windows Management Instrumentation (WMI).
    Note WMI is a powerful, sophisticated technology based on Web Based Enterprise Management (WBEM). WMI is primarily used for accessing and instrumenting management information in an enterprise environment. For more information on WMI, see Microsoft Windows Management Instrumentation: Background and Overview at (http://msdn.microsoft.com/library/default.htm?URL=/library/backgrnd/html/wmixwdm.htm).

The Administrator must establish the necessary security settings on the remote machines. For more information, see Setting up Remote WSH. Next the administrator must copy and paste the sample into the scripting editor and change the constants to reflect the corresponding network paths and machine names. Finally the administrator can run the script.

To run this sample

  1. Establish the necessary security settings on the remote machines.
  2. Copy the AdminScript.vbs script below into your scripting text editor.
  3. Change the constants to reflect your network paths and machine names.
  4. Replace remmachine with the applicable remote machine name and run the script:
    var oController = new ActiveXObject"WSHController"
var oProcess = oController.CreateScript "c:\MyLocalDir\\AdminScript.vbs", "remmachine"
oProcess.Execute()
while (oProcess.Status != 2)
     WScript.Sleep(100)
WScript.Echo"Done"

AdminScript.vbs Sample

' Remote WSH Admin Sample  AdminScript.vbs
'
' This sample code does a few common administrative tasks which a
' network administrator might want to do to a number of the machines
' on his or her network:  it creates a public directory, populates
' it with some files and shares the directory out.  It also sets
' up the machines default printer connection.

' Note that in the interests of keeping this example code small, error
' handling has been omitted.  Actual production code should use
' appropriate error handling as many of these operations could fail;
' the disks could run out of space, for instance.

Option Explicit

Dim FSO
Dim Services
Dim SecDescClass
Dim SecDesc
Dim Trustee
Dim ACE
Dim Share
Dim InParam
Dim Network

Const FolderName = "C:\Public"
Const AdminServer = "\\AdminMachine"
Const ShareName = "Pubs"
Const PrinterShare = "\\CorpPrinters\PrinterShare"

' First we add a printer to this machine and make it the default.

Set Network = CreateObject("Wscript.Network")
Network.AddWindowsPrinterConnection PrinterShare
Network.SetDefaultPrinter PrinterShare

' Next we create a folder and populate it with some files.

Set FSO = CreateObject("Scripting.FileSystemObject")
If Not FSO.FolderExists(FolderName) Then
   FSO.CreateFolder(FolderName)
End If

Call FSO.CopyFile(AdminServer & "\Public\Images\*.*", FolderName)

' Make the folder into a share using WMI
' See the WMI SDK for information on how this code works.

Set Services = GetObject("WINMGMTS:{impersonationLevel=impersonate,(Security)}!" & AdminServer & "\ROOT\CIMV2")
Set SecDescClass = Services.Get("Win32_SecurityDescriptor")
Set SecDesc = SecDescClass.SpawnInstance_()
Set Trustee = Services.Get("Win32_Trustee").SpawnInstance_
Trustee.Domain = Null
Trustee.Name = "EVERYONE"
Trustee.Properties_.Item("SID") = Array(1, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0)
Set ACE = Services.Get("Win32_Ace").SpawnInstance_
ACE.Properties_.Item("AccessMask") = 2032127
ACE.Properties_.Item("AceFlags") = 3
ACE.Properties_.Item("AceType") = 0
ACE.Properties_.Item("Trustee") = Trustee
SecDesc.Properties_.Item("DACL") = Array(ACE)
Set Share = Services.Get("Win32_Share")
Set InParam = Share.Methods_("Create").InParameters.SpawnInstance_()
InParam.Properties_.Item("Access") = SecDesc
InParam.Properties_.Item("Description") = "Public Share"
InParam.Properties_.Item("Name") = ShareName
InParam.Properties_.Item("Path") = FolderName
InParam.Properties_.Item("Type") = 0
Share.ExecMethod_("Create", InParam)

' And we're done.

See Also

WSH Walkthrough | Accessing Networks | Setting up Remote WSH | Running Scripts Remotely


WSH Objects

Objects

WshScriptExec ObjectWshSpecialFolders CollectionWshEnvironment CollectionWshUrlShortCut ObjectWshShortCut ObjectShell ObjectWshNetwork ObjectWshRemoteError ObjectWshRemote ObjectWshController ObjectWshUnnamed CollectionWshNamed CollectionWshArguments CollectionWScript Object

The Windows Script Host object model provides a logical, systematic way to perform many administrative tasks. The set of COM interfaces it provides can be placed into two main categories:

In this Section

WScript Object
Provides access to most of the objects, methods, and properties in the WSH object model.
WshArguments Object
Gives you access to the entire collection of command-line parameters — in the order in which they were originally entered.
WshController Object
Exposes the method CreateScript() that creates a remote script process.
WshEnvironment Object
Gives you access to the collection of Microsoft Windows system environment variables.
WshNamed Object
Provides access to the named command-line script arguments within the WshArguments object.
WshNetwork Object
Gives you access to the shared resources on the network to which your computer is connected.
WshRemote Object
Provides access to the remote script process.
WshRemoteError Object
Exposes the error information available when a remote script (a WshRemote object) terminates as a result of a script error.
WshScriptExec Object
Provides status and error information about a script run with Exec, along with access to the stdIn, stdOut, and stdErr channels.
WshShell Object
Gives you access to the native Windows shell functionality.
WshShortcut Object
Allows you to create a shortcut programmatically.
WshSpecialFolders Object
Allows you to access the Windows Special Folders.
WshUnnamed Object
Provides access to the unnamed command-line script arguments within the WshArguments object.
WshUrlShortcut Object
Allows you to create a shortcut to an Internet resource, programmatically.

Related Sections

WSH Reference
List of elements that make up WSH Reference.
WSH Basics
Learn the basics of WSH.


WScript Object

The WScript object is the root object of the Windows Script Host object model hierarchy. It never needs to be instantiated before invoking its properties and methods, and it is always available from any script file. The WScript object provides access to information such as:

  • command-line arguments,
  • the name of the script file,
  • the host file name,
  • and host version information.

The WScript object allows you to:

  • create objects,
  • connect to objects,
  • disconnect from objects,
  • sync events,
  • stop a script's execution programmatically,
  • output information to the default output device (either a Windows dialog box or the command console).

The WScript object can be used to set the mode in which the script runs (either interactive or batch).

Example

Since the WScript object is the root object for the Windows Script Host object model, many properties and methods apply to the object. For examples of specific syntax, visit the properties and methods links.

Properties

Arguments Property | FullName Property (WScript Object) | Interactive Property | Name Property | Path Property | ScriptFullName Property | ScriptName Property | StdErr Property | StdIn Property | StdOut Property | Version Property

Methods

CreateObject Method | ConnectObject Method | DisconnectObject Method | Echo Method | GetObject Method | Quit Method | Sleep Method

See Also

Running Your Scripts | WshShell Object | WshNetwork Object


Application

Wscript.Application

The Application property provides the IDispatch interface on the Wscript object.

Syntax

Wscript.Application = objWscript


Arguments

object
WScript object.

Remarks

The Arguments property contains the WshArguments object (a collection of arguments). Use a zero-based index to retrieve individual arguments from this collection.

Example

The following code samples display the entire set of command-line parameters associated with a script.

[VBScript]
Set objArgs = WScript.Arguments
For I = 0 to objArgs.Count - 1
   WScript.Echo objArgs(I)
Next
[JScript]
objArgs = WScript.Arguments;
for (i = 0; i < objArgs.length; i++)
{
   WScript.Echo(objArgs(i));
}

Example

' Display all command-line parameters
Set objArgs = Wscript.Arguments
For I = 0 to objArgs.Count - 1
          Wscript.Echo objArgs(I)
Next


WScript.FullName property

FullName Property (WScript Object)

Returns the fully qualified path of the host executable (CScript.exe or WScript.exe).

object.FullName

Arguments

object
WScript object.

Remarks

The FullName property is a read-only string representing the fully qualified path of the host executable.

Example

The following JScript code uses the FullName property:

WScript.Echo (WScript.FullName);

produces the following output.

C:\WINNT\System32\cscript.exe

See Also

Path Property | WScript Object | WshShortcut Object | WshUrlShortcut Object

Properties

Arguments Property | FullName Property (WScript Object) | Interactive Property | Name Property | Path Property | ScriptFullName Property | ScriptName Property | StdErr Property | StdIn Property | StdOut Property | Version Property

Methods

CreateObject Method | ConnectObject Method | DisconnectObject Method | Echo Method | GetObject Method | Quit Method | Sleep Method

See Also

Running Your Scripts | WshShell Object | WshNetwork Object


Interactive

Interactive Property

Sets the script mode, or identifies the script mode.

object.Interactive

Arguments

object
WScript object.

Remarks

The Interactive Property returns a Boolean value.

There are two modes, batch and interactive. In interactive mode (the default), the script provides user interaction. Input to and output from the Windows Script Host is enabled. The script can echo information to dialog boxes and can wait for the user to provide feedback. In batch mode, this type of user interaction is not supported — all input and output to WSH is disabled. You can also set the script mode using the Windows Script Host command line switches //I (for Interactive), and //B (for Batch).

Example

The following JScript code displays the script mode.

WScript.Echo WScript.Interactive;

The following JScript code sets the script mode to batch.

WScript.Interactive = false;

See Also

WScript Object


Name Property

Name Property (WScript Object)

Returns the name of the WScript object (the host executable file).

object.Name

Arguments

object
WScript object.

Remarks

The Name property is a read-only string.

Example

The following JScript code shows how to use the Name property.

WScript.Echo (WScript.Name);

See Also

WScript Object


Path Property

Returns the name of the directory containing the host executable (CScript.exe or WScript.exe).

object.Path

Arguments

object
WScript object.

Remarks

The Path property is a read-only string.

Example

The following VBScript code echoes the directory where the executable file resides.

WScript.Echo (WScript.Path);

See Also

FullName Property | WScript Object


ScriptFullName Property

Returns the full path of the currently running script.

object.ScriptFullName

Arguments

object
WScript object.

Remarks

The ScriptFullName property is a read-only string.

Example

The following example demonstrates the use of the ScriptFullName property.

<package>
   <job id="vbs">
      <script language="VBScript">
         set WshShell = WScript.CreateObject("WScript.Shell")
         strDesktop = WshShell.SpecialFolders("Desktop")
         set oShellLink = WshShell.CreateShortcut(strDesktop & "\Shortcut Script.lnk")
         oShellLink.TargetPath = WScript.ScriptFullName
         oShellLink.WindowStyle = 1
         oShellLink.Hotkey = "Ctrl+Alt+e"
         oShellLink.IconLocation = "notepad.exe, 0"
         oShellLink.Description = "Shortcut Script"
         oShellLink.WorkingDirectory = strDesktop
         oShellLink.Save
         set oUrlLink = WshShell.CreateShortcut(strDesktop & "\Microsoft Web Site.url")
         oUrlLink.TargetPath = "http://www.microsoft.com"
         oUrlLink.Save
      </script>
   </job>

   <job id="js">
      <script language="JScript">
         var WshShell = WScript.CreateObject("WScript.Shell");
         strDesktop = WshShell.SpecialFolders("Desktop");
         var oShellLink = WshShell.CreateShortcut(strDesktop + "\\Shortcut Script.lnk");
         oShellLink.TargetPath = WScript.ScriptFullName;
         oShellLink.WindowStyle = 1;
         oShellLink.Hotkey = "Ctrl+Alt+e";
         oShellLink.IconLocation = "notepad.exe, 0";
         oShellLink.Description = "Shortcut Script";
         oShellLink.WorkingDirectory = strDesktop;
         oShellLink.Save();
         var oUrlLink = WshShell.CreateShortcut(strDesktop + "\\Microsoft Web Site.url");
         oUrlLink.TargetPath = "http://www.microsoft.com";
         oUrlLink.Save();
      </script>
   </job>
</package>

See Also

Running Your Scripts | ScriptName Property | WScript Object


ScriptName Property

Returns the file name of the currently running script.

object.ScriptName

Arguments

object
WScript object.

Remarks

The ScriptName property is a read-only string.

Example

The following VBScript code echoes the name of the script being run.

WScript.Echo WScript.ScriptName

See Also

ScriptFullName Property | WScript Object


StdErr Property

StdErr Property (WScript)

Exposes the write-only error output stream for the current script.

object.StdErr

Arguments

object
WScript object.

Remarks

The StdErr property returns an object representing the standard error stream. The StdIn, StdOut, and StdErr streams can be accessed while using CScript.exe only. Attempting to access these streams while using WScript.exe produces an error.

See Also

Error Messages | WScript Object


StdIn Property

StdIn Property (WScript)

Exposes the read-only input stream for the current script.

object.StdIn

Arguments

object
WScript object.

Remarks

The StdIn property returns an object representing the standard input stream. The StdIn, StdOut, and StdErr streams can be accessed while using CScript.exe only. Attempting to access these streams while using WScript.exe produces an error.

Example VBScript

'RUN THIS WITH CSCRIPT
Dim its,ots,strInput,strOutput

WScript.echo "Calc - enter expression or 'end'"

set its = WScript.StdIn
set ots = WScript.StdOut

   ots.writeline("")

   on error resume next

do until its.atendofstream
   strinput = its.readline
   if UCASE(strinput) = "END" then exit do
   if strinput <> "" then
      strOutput = cstr(eval(strInput))
      if err.number <> 0 then
         ots.writeline(err.description)
         err.clear
      else
         ots.writeline("-- " + strOutput)
      end if
      ots.writeline
   end if
loop

Example JavaScript

//RUN THIS WITH CSCRIPT

calc();

function calc()
{
  var its,ots,strInput,strOutput;

  WScript.echo("Calc - enter expression or 'end'");

  var its = WScript.StdIn;
  var ots = WScript.StdOut;

  ots.writeline("");

  while(!its.atendofstream)
  {
    strInput = its.readline();
    if(strInput == "end" || strInput == "END") { break; }
    if(strInput != "")
    {
      //error cannot be trapped
      strOutput = eval(strInput)
      ots.writeline("-- " + strOutput);
      ots.writeline();
    }
  }
}

See Also

Error Messages | WScript Object | Read Method | ReadAll Method | ReadLine Method | Skip Method | SkipLine Method | AtEndOfLine Property | Close Method | Column Property | Line Property (WScript)


StdOut Property

StdOut Property (WScript)

Exposes the write-only output stream for the current script.

object.StdOut

Arguments

object
WScript object.

Remarks

The StdOut property returns an object representing the standard output stream. The StdIn, StdOut, and StdErr streams can be accessed while using CScript.exe only. Attempting to access these streams while using WScript.exe produces an error.

See Also

Error Messages | WScript Object | Write Method | WriteBlankLines Method | WriteLine Method | Close Method | Column Property | Line Property (WScript)


Version Property

Returns the version of Windows Script Host.

object.Version

Arguments

object
WScript object.

Remarks

String.

Example

The following VBScript code echoes the current version of Windows Script Host.

WScript.Echo WScript.Version

See Also

WScript Object


ConnectObject Method

Connects the object's event sources to functions with a given prefix.

object.ConnectObject(strObject, strPrefix)

Arguments

object
WScript object.
strObject
Required. String value indicating the name of the object you want to connect.
strPrefix
Required. String value indicating the function prefix.

Remarks

Connected objects are useful when you want to sync an object's events. The ConnectObject method connects the object's outgoing interface to the script file after creating the object. Event functions are a combination of this prefix and the event name.

Example

The following example demonstrates using the ConnectObject method to connect to the WshRemote object's Error event.

[VBScript]
Dim Controller, RemoteScript
Set Controller = WScript.CreateObject("WSHController")
Set RemoteScript = Controller.CreateScript("test.js", "remoteserver")
WScript.ConnectObject RemoteScript, "remote_"
RemoteScript.Execute

Do While RemoteScript.Status <> 2
    WScript.Sleep 100
Loop

Sub remote_Error
    Dim theError
    Set theError = RemoteScript.Error
    WScript.Echo "Error " & theError.Number & " - Line: " & theError.Line & ", Char: " & theError.Character & vbCrLf & "Description: " & theError.Description
    WScript.Quit -1
End Sub
[JScript]
var Controller = WScript.CreateObject("WSHController");
var RemoteScript = Controller.CreateScript("test.js", "remoteserver");
WScript.ConnectObject(RemoteScript, "remote_");
RemoteScript.Execute();

while (RemoteScript.Status != 2) {
    WScript.Sleep(100);
}

function remote_Error()
{
    var theError = RemoteScript.Error;
    WScript.Echo("Error " + theError.Number + " - Line: " + theError.Line + ", Char: " + theError.Character + "\nDescription: " + theError.Description);
    WScript.Quit(-1);
}

See Also

WScript Object | DisconnectObject Method | CreateObject Method | GetObject Method


CreateObject Method

Creates a COM object.

object.CreateObject(strProgID[,strPrefix])

Arguments

object
WScript object.
strProgID
String value indicating the programmatic identifier (ProgID) of the object you want to create.
strPrefix
Optional. String value indicating the function prefix.

Remarks

Objects created with the CreateObject method using the strPrefix argument are connected objects. These are useful when you want to sync an object's events. The object's outgoing interface is connected to the script file after the object is created. Event functions are a combination of this prefix and the event name. If you create an object and do not supply the strPrefix argument, you can still sync events on the object by using the ConnectObject method. When the object fires an event, WSH calls a subroutine with strPrefix attached to the beginning of the event name. For example, if strPrefix is MYOBJ and the object fires an event named OnBegin, Windows Script Host calls the MYOBJ_OnBegin subroutine located in the script. The CreateObject method returns a pointer to the object's IDispatch interface.

Example

The following VBScript code uses the CreateObject method to create a WshNetwork object:

Set WshNetwork = WScript.CreateObject("WScript.Network")

See Also

WScript Object | GetObject Method | ConnectObject Method | DisconnectObject Method


GetObject Method

Retrieves an existing object with the specified ProgID, or creates a new one from a file.

object.GetObject(strPathname [,strProgID], [strPrefix])

Arguments

object
WScript object.
strPathname
The fully qualified path name of the file that contains the object persisted to disk.
strProgID
Optional. The object's program identifier (ProgID).
strPrefix
Optional. Used when you want to sync the object's events. If you supply the strPrefix argument, WSH connects the object's outgoing interface to the script file after creating the object.

Remarks

Use the GetObject method when an instance of the object exists in memory, or when you want to create the object from a file. If no current instance exists and you do not want the object created from a file, use the CreateObject method. The GetObject method can be used with all COM classes, independent of the language used to create the object. If you supply the strPrefix argument, WSH connects the object's outgoing interface to the script file after creating the object. When the object fires an event, WSH calls a subroutine with strPrefix attached to the beginning of the event name. For example, if strPrefix is MYOBJ_ and the object fires an event named OnBegin, WSH calls the MYOBJ_OnBegin subroutine located in the script.

If an object is registered as a single-instance object, only one instance of the object is created (regardless of how many times GetObject is executed). The GetObject method always returns the same instance when called with the zero-length string syntax (""), and it causes an error if you do not supply the path parameter. You cannot use the GetObject method to obtain a reference to a Microsoft Visual Basic class created with Visual Basic 4.0 or earlier.

Example

The following VBScript code starts the application associated with the specified file (strPathname):

Dim MyObject As Object
Set MyObject = GetObject("C:\CAD\SCHEMA.CAD")
MyApp = MyObject.Application

Some applications allow you to activate part of a file. To do this, add an exclamation mark (!) to the end of the file name, and follow it with a string that identifies the part of the file you want to activate. For example, in a drawing application, a drawing stored in a file might have multiple layers. The following code activates a layer within a drawing file called SCHEMA.CAD:

Set LayerObject = GetObject("C:\CAD\SCHEMA.CAD!Layer3")

If you do not specify the object's class (strProgID), COM determines the application to start from the file name. Some files can support more than one class of object. For example, a drawing might support three different types of objects: an application object, a drawing object, and a toolbar object. All may be part of the same file.

In the following VBScript code, the drawing application FIGMENT starts and opens the object DRAWING from within the file SAMPLE.DRW.

Dim MyObject As Object
Set MyObject = GetObject("C:\DRAWINGS\SAMPLE.DRW", "FIGMENT.DRAWING")

See Also

WScript Object | CreateObject Method | DisconnectObject Method


DisconnectObject Method

Disconnects a connected object's event sources.

object.DisconnectObject(obj)

Arguments

object
WScript object.
obj
String value indicating the name of the object to disconnect.

Remarks

Once an object has been "disconnected," WSH will not respond to its events. The object is still capable of firing events, though. Note that the DisconnectObject method does nothing if the specified object is not already connected.

Example

The following example demonstrates using the DisconnectObject method to disconnect to the WshRemote object's Error event after a remote script has completed.

[VBScript]
Dim Controller, RemoteScript
Set Controller = WScript.CreateObject("WSHController")
Set RemoteScript = Controller.CreateScript("test.js", "remoteserver")
WScript.ConnectObject RemoteScript, "remote_"
RemoteScript.Execute

Do While RemoteScript.Status <> 2
    WScript.Sleep 100
Loop

WScript.DisconnectObject RemoteScript

Sub remote_Error
    Dim theError
    Set theError = RemoteScript.Error
    WScript.Echo "Error " & theError.Number & " - Line: " & theError.Line & ", Char: " & theError.Character & vbCrLf & "Description: " & theError.Description
    WScript.Quit -1
End Sub
[JScript]
var Controller = WScript.CreateObject("WSHController");
var RemoteScript = Controller.CreateScript("test.js", "remoteserver");
WScript.ConnectObject(RemoteScript, "remote_");
RemoteScript.Execute();

while (RemoteScript.Status != 2) {
    WScript.Sleep(100);
}

WScript.DisconnectObject(RemoteScript)

function remote_Error()
{
    var theError = RemoteScript.Error;
    WScript.Echo("Error " + theError.Number + " - Line: " + theError.Line + ", Char: " + theError.Character + "\nDescription: " + theError.Description);
    WScript.Quit(-1);
}

See Also

WScript Object | ConnectObject Method | CreateObject Method | GetObject Method


Echo Method

Outputs text to either a message box or the command console window.

object.Echo [Arg1] [,Arg2] [,Arg3] ...

Arguments

object
WScript object.
Arg1, Arg2, Arg3 ...
Optional. String value indicating the list of items to be displayed.

Remarks

The Echo method behaves differently depending on which WSH engine you are using.

WSH engine | Text Output
Wscript.exe | graphical message box
Cscript.exe | command console window

Each displayed item is separated with a space character. When using CScript.exe, each item is displayed with a newline character. If no items are provided as arguments to the Echo method, a blank line is output.

Example

The following example uses the Echo Method to display the domain name, computer name, and user name for the current machine, and to display network mapping information for the drives and printers.

<package>
   <job id="vbs">
      <script language="VBScript">
         Set WshNetwork = WScript.CreateObject("WScript.Network")
         Set oDrives = WshNetwork.EnumNetworkDrives
         Set oPrinters = WshNetwork.EnumPrinterConnections
         WScript.Echo "Domain = " & WshNetwork.UserDomain
         WScript.Echo "Computer Name = " & WshNetwork.ComputerName
         WScript.Echo "User Name = " & WshNetwork.UserName
         WScript.Echo
         WScript.Echo "Network drive mappings:"
         For i = 0 to oDrives.Count - 1 Step 2
            WScript.Echo "Drive " & oDrives.Item(i) & " = " & oDrives.Item(i+1)
         Next
         WScript.Echo
         WScript.Echo "Network printer mappings:"
         For i = 0 to oPrinters.Count - 1 Step 2
            WScript.Echo "Port " & oPrinters.Item(i) & " = " & oPrinters.Item(i+1)
         Next
      </script>
   </job>

   <job id="js">
      <script language="JScript">
         var WshNetwork = WScript.CreateObject("WScript.Network");
         var oDrives = WshNetwork.EnumNetworkDrives();
         var oPrinters = WshNetwork.EnumPrinterConnections();
         WScript.Echo("Domain = " + WshNetwork.UserDomain);
         WScript.Echo("Computer Name = " + WshNetwork.ComputerName);
         WScript.Echo("User Name = " + WshNetwork.UserName);
         WScript.Echo();
         WScript.Echo("Network drive mappings:");
         for(i=0; i<oDrives.Count(); i+=2){
            WScript.Echo("Drive " + oDrives.Item(i) + " = " + oDrives.Item(i+1));
         }
         WScript.Echo();
         WScript.Echo("Network printer mappings:");
         for(i=0; i<oPrinters.Count(); i+=2){
            WScript.Echo("Port " + oPrinters.Item(i) + " = " + oPrinters.Item(i+1));
         }
      </script>
   </job>
</package>

See Also

Running Your Scripts | WScript Object


Sleep Method

Suspends script execution for a specified length of time, then continues execution.

object.Sleep(intTime)

Arguments

object
WScript object.
intTime
Integer value indicating the interval (in milliseconds) you want the script process to be inactive.

Remarks

The thread running the script is suspended, releasing its CPU utilization. Execution resumes as soon as the interval expires. Using the Sleep method can be useful when you are running asynchronous operations, multiple processes, or if your script includes code triggered by an event. To be triggered by an event, a script must be continually active (a script that has finished executing will certainly not detect an event). Events handled by the script will still be executed during a sleep.

Note Passing the Sleep method a 0 or –1 does not cause the script to suspend indefinitely.

Example

The following example demonstrates the use of a single .wsf file for two jobs in different script languages (VBScript and JScript). The functionality of both jobs is the same — each runs the Windows calculator and sends it keystrokes to execute a simple calculation.

<package>
   <job id="vbs">
      <script language="VBScript">
         set WshShell = WScript.CreateObject("WScript.Shell")
         WshShell.Run "calc"
         WScript.Sleep 100
         WshShell.AppActivate "Calculator"
         WScript.Sleep 100
         WshShell.SendKeys "1{+}"
         WScript.Sleep 500
         WshShell.SendKeys "2"
         WScript.Sleep 500
         WshShell.SendKeys "~"
         WScript.Sleep 500
         WshShell.SendKeys "*3"
         WScript.Sleep 500
         WshShell.SendKeys "~"
         WScript.Sleep 2500
      </script>
   </job>

   <job id="js">
      <script language="JScript">
         var WshShell = WScript.CreateObject("WScript.Shell");
         WshShell.Run("calc");
         WScript.Sleep(100);
         WshShell.AppActivate("Calculator");
         WScript.Sleep(100);
         WshShell.SendKeys("1{+}");
         WScript.Sleep(500);
         WshShell.SendKeys("2");
         WScript.Sleep(500);
         WshShell.SendKeys("~");
         WScript.Sleep(500);
         WshShell.SendKeys("*3");
         WScript.Sleep(500);
         WshShell.SendKeys("~");
         WScript.Sleep(2500);
      </script>
   </job>
</package>

See Also

Running Your Scripts | WScript Object


Quit Method

Forces script execution to stop at any time.

object.Quit([intErrorCode])

Arguments

object
WScript object.
intErrorCode
Optional. Integer value returned as the process's exit code. If you do not include the intErrorCode parameter, no value is returned.

Remarks

The Quit method can return an optional error code. If the Quit method is the final instruction in your script (and you have no need to return a non-zero value), you can leave it out, and your script will end normally.

Example

The following JScript code snippet quits execution and returns an error code of 1:

WScript.Quit (1);

// This line of code is never executed.
var i = 0;

See Also

WScript Object


WshArguments

WshArguments Object

Provides access to the entire collection of command-line parameters — in the order in which they were originally entered.

Remarks

The WshArguments object is a collection returned by the WScript object's Arguments property (WScript.Arguments). Two of the WshArguments object's properties are filtered collections of arguments — one contains the named arguments (querying this property returns a WshNamed object), the other contains the unnamed arguments (querying this property returns a WshUnnamed object). There are three ways to access sets of command-line arguments.

  • You can access the entire set of arguments (those with and without names) with the WshArguments object.
  • You can access the arguments that have names with the WshNamed object.
  • You can access the arguments that have no names with the WshUnnamed object.

Example

The following code displays the command-line parameters in the WshArguments object.

[VBScript]
Set objArgs = WScript.Arguments
For I = 0 to objArgs.Count - 1
   WScript.Echo objArgs(I)
Next
[JScript]
objArgs = WScript.Arguments;
for (i = 0; i < objArgs.length; i++)
{
   WScript.Echo(objArgs(i));
}

Properties

Item Property | Length Property (WshArguments object) | Count Property | Named Property | Unnamed Property

Methods

Count Method | ShowUsage Method

See Also

Arguments Property | WshNamed Object | WshUnnamed Object


Item Property

Exposes a specified item from a collection.

Object.Item(natIndex)

Arguments

Object
The result of the EnumNetworkDrive or EnumPrinterConnections methods, or the object returned by the Environment or SpecialFolders properties.
natIndex
Item to retrieve.

Remarks

Item is the default property for each collection. For EnumNetworkDrive and EnumPrinterConnections collections, index is an integer; for the Environment and SpecialFolders collections, index is a string.

WshShell.SpecialFolders.Item (strFolderName) returns "Empty" in VBScript and "undefined" in JScript if the requested folder (strFolderName) is not available.

The following table lists special folders along with the version of Windows that supports them.

Folder | Windows version
AllUsersDesktop | Windows 2000
AllUsersStartMenu | Windows 2000
AllUsersPrograms | Windows 2000
AllUsersStartup | Windows 2000
Desktop | Windows 98/ME, Windows 2000
Favorites | Windows 98/ME, Windows 2000
Fonts | Windows 98/ME, Windows 2000
My Documents | Windows 98/ME, Windows 2000
NetHood | Windows 98/ME, Windows 2000
PrintHood | Windows 98/ME, Windows 2000
Programs | Windows 98/ME, Windows 2000
Recent | Windows 98/ME, Windows 2000
SendTo | Windows 98/ME, Windows 2000
Start Menu | Windows 98/ME, Windows 2000
StartupB | Windows 2000
Templates | Windows 2000

Example

The following code displays network mapping information for the drives and printers.

<package>
   <job id="vbs">
      <script language="VBScript">
         Set WshNetwork = WScript.CreateObject("WScript.Network")
         Set oDrives = WshNetwork.EnumNetworkDrives
         Set oPrinters = WshNetwork.EnumPrinterConnections
         WScript.Echo "Network drive mappings:"
         For i = 0 to oDrives.Count - 1 Step 2
            WScript.Echo "Drive " & oDrives.Item(i) & " = " & oDrives.Item(i+1)
         Next
         WScript.Echo
         WScript.Echo "Network printer mappings:"
         For i = 0 to oPrinters.Count - 1 Step 2
            WScript.Echo "Port " & oPrinters.Item(i) & " = " & oPrinters.Item(i+1)
         Next
      </script>
   </job>

   <job id="js">
      <script language="JScript">
         var WshNetwork = WScript.CreateObject("WScript.Network");
         var oDrives = WshNetwork.EnumNetworkDrives();
         var oPrinters = WshNetwork.EnumPrinterConnections();
         WScript.Echo();
         WScript.Echo("Network drive mappings:");
         for(i = 0; i < oDrives.length; i += 2){
            WScript.Echo("Drive " + oDrives.Item(i) + " = " + oDrives.Item(i + 1));
         }
         WScript.Echo();
         WScript.Echo("Network printer mappings:");
         for(i = 0; i < oPrinters.length; i += 2){
            WScript.Echo("Port " + oPrinters.Item(i) + " = " + oPrinters.Item(i + 1));
         }
      </script>
   </job>
</package>

See Also

EnumNetworkDrive Method | EnumPrinterConnections Method | Environment Property | SpecialFolders Property


Length Property

length Property (WshArguments object)

Returns the number of command-line parameters belonging to a script (the number of items in an argument's collection).

object.length

Arguments

object
WshArguments object.

Remarks

The length property is a read-only integer that you use in scripts when you write in JScript. It is similar to VBScript's Count method.

See Also

WshArguments Object | Arguments Property | Count Method


Count Property

Count Method

Returns the number of switches in the WshNamed or WshUnnamed objects.

object.Count

Arguments

object
Arguments object.

Remarks

The Count method returns an integer value. The Count method is primarily intended for VBScript users. JScript users should generally use the length property instead.

Example (WshNamed)

The following example demonstrates the Count method using the WshNamed object. Begin by typing the following text at the Command Prompt.

myScript.vbs /c:"WSH is a wonderful thing" /s:"scripts are wonderful"

Next, add the following VBScript code.

For i = 0 to WScript.Arguments.Count-1
    WScript.Echo WScript.Arguments.Named(i)
next i

Following is the result.

WSH is a wonderful thing
scripts are wonderful

Example (WshUnnamed)

The following example demonstrates the Count method using the WshUnnamed object. Begin by typing the following text at the command line.

myscript.vbs "WSH is a wonderful thing" "scripts are wonderful"

Next, add the following VBScript code.

For i = 0 to WScript.Arguments.Count-1
    WScript.Echo WScript.Arguments.Unnamed(i)
next i

Following is the result.

WSH is a wonderful thing
scripts are wonderful

See Also

Arguments Property | WshNamed Object | WshUnnamed Object | Item Property | Exists Method | Length Property


Named Property

Returns the WshNamed object (a collection of named arguments).

Object.Named

Parameters

Object
WshArguments object.

Remarks

The Named property returns the WshNamed collection, the collection of named arguments. Use the name of the argument to find out if the argument was included and to access its value.

Example

The following code displays the number of named and unnamed command-line arguments.

<package>
<job id="JS">
<script language="JScript">

var argsNamed = WScript.Arguments.Named;
var argsUnnamed = WScript.Arguments.Unnamed;

WScript.Echo("There are " + argsNamed.length + " named arguments.");
WScript.Echo("There are " + argsUnnamed.length + " unnamed arguments.");

</script>
</job>

<job id="VBS">
<script language="VBScript">

Dim argsNamed, argsUnnamed
Set argsNamed = WScript.Arguments.Named
Set argsUnnamed = WScript.Arguments.Unnamed

WScript.Echo "There are " & argsNamed.Count & " named arguments."
WScript.Echo "There are " & argsUnnamed.Count & " unnamed arguments."

</script>
</job>
</package>

See Also

WshArguments Object | WshNamed Object | Unnamed Property


Unnamed Property

Returns the WshUnnamed object (a collection of unnamed arguments).

Object.Unnamed

Parameters

Object
WshArguments object.

Remarks

The Unnamed property returns the WshUnnamed collection, the collection of unnamed arguments. The arguments are presented in the order that they were entered on the command line. The first unnamed argument at index 0.

Example

The following code displays the number of named and unnamed command-line arguments.

<package>
<job id="JS">
<script language="JScript">

var argsNamed = WScript.Arguments.Named;
var argsUnnamed = WScript.Arguments.Unnamed;

WScript.Echo("There are " + argsNamed.length + " named arguments.");
WScript.Echo("There are " + argsUnnamed.length + " unnamed arguments.");

</script>
</job>

<job id="VBS">
<script language="VBScript">

Dim argsNamed, argsUnnamed
Set argsNamed = WScript.Arguments.Named
Set argsUnnamed = WScript.Arguments.Unnamed

WScript.Echo "There are " & argsNamed.Count & " named arguments."
WScript.Echo "There are " & argsUnnamed.Count & " unnamed arguments."

</script>
</job>
</package>

See Also

WshArguments Object | WshUnnamed Object | Named Property


Count Method

Returns the number of switches in the WshNamed or WshUnnamed objects.

object.Count

Arguments

object
Arguments object.

Remarks

The Count method returns an integer value. The Count method is primarily intended for VBScript users. JScript users should generally use the length property instead.

Example (WshNamed)

The following example demonstrates the Count method using the WshNamed object. Begin by typing the following text at the Command Prompt.

myScript.vbs /c:"WSH is a wonderful thing" /s:"scripts are wonderful"

Next, add the following VBScript code.

For i = 0 to WScript.Arguments.Count-1
    WScript.Echo WScript.Arguments.Named(i)
next i

Following is the result.

WSH is a wonderful thing
scripts are wonderful

Example (WshUnnamed)

The following example demonstrates the Count method using the WshUnnamed object. Begin by typing the following text at the command line.

myscript.vbs "WSH is a wonderful thing" "scripts are wonderful"

Next, add the following VBScript code.

For i = 0 to WScript.Arguments.Count-1
    WScript.Echo WScript.Arguments.Unnamed(i)
next i

Following is the result.

WSH is a wonderful thing
scripts are wonderful

See Also

Arguments Property | WshNamed Object | WshUnnamed Object | Item Property | Exists Method | Length Property


ShowUsage Method

Makes a script self-documenting by displaying information about how it should be used.

object.ShowUsage

Parameters

object
WScript Object.

Remarks

When you run the ShowUsage method, a help screen (referred to as the usage) appears and displays details about the script's command line options. This information comes from the runtime section of the *.WSF file. Everything written between the <runtime> and </runtime> tags is pieced together to produce what is called a "usage statement." The usage statement tells the user how to use the script.

Note The usage can also be displayed using the /? switch.

Example

The following example demonstrates how to set up usage information in a *.WSF script file.

<job>
    <runtime>
        <description>This script reboots a server</description>
        <named
            name = "Server"
            helpstring = "Server to run the script on"
            type = "string"
            required = "true"
        />
        <example>Example: reboot.wsf /server:scripting</example>
    </runtime>
<script language="VBScript">

If WScript.Arguments.Count <> 1 Then
   WScript.Arguments.ShowUsage
   WScript.Quit
End If

</script>
</job>

The JScript code for the equivalent script block would be:

if (WScript.Arguments.length != 1)
{
   WScript.Arguments.ShowUsage();
   WScript.Quit();
}

Calling the ShowUsage method from this script results in the following output:

This script reboots a server
Usage: reboot.wsf /server:value

Options:

server : Server to run the script onExample:
reboot.wsf /server:scripting

See Also

WScript Object


WshShell Object

Provides access to the native Windows shell.

Remarks

You create a WshShell object whenever you want to run a program locally, manipulate the contents of the registry, create a shortcut, or access a system folder. The WshShell object provides the Environment collection. This collection allows you to handle environmental variables (such as WINDIR, PATH, or PROMPT).

Example

The following example demonstrates the creation of a shortcut to the script being run and a URL shortcut to www.microsoft.com:

<package>
   <job id="vbs">
      <script language="VBScript">
         set WshShell = WScript.CreateObject("WScript.Shell")
         strDesktop = WshShell.SpecialFolders("Desktop")
         set oShellLink = WshShell.CreateShortcut(strDesktop & "\Shortcut Script.lnk")
         oShellLink.TargetPath = WScript.ScriptFullName
         oShellLink.WindowStyle = 1
         oShellLink.Hotkey = "CTRL+SHIFT+F"
         oShellLink.IconLocation = "notepad.exe, 0"
         oShellLink.Description = "Shortcut Script"
         oShellLink.WorkingDirectory = strDesktop
         oShellLink.Save
      </script>
   </job>

   <job id="js">
      <script language="JScript">
         var WshShell = WScript.CreateObject("WScript.Shell");
         strDesktop = WshShell.SpecialFolders("Desktop");
         var oShellLink = WshShell.CreateShortcut(strDesktop + "\\Shortcut Script.lnk");
         oShellLink.TargetPath = WScript.ScriptFullName;
         oShellLink.WindowStyle = 1;
         oShellLink.Hotkey = "CTRL+SHIFT+F";
         oShellLink.IconLocation = "notepad.exe, 0";
         oShellLink.Description = "Shortcut Script";
         oShellLink.WorkingDirectory = strDesktop;
         oShellLink.Save();
      </script>
   </job>
</package>

Properties

CurrentDirectory Property | Environment Property | SpecialFolders Property

Methods

AppActivate Method | CreateShortcut Method | ExpandEnvironmentStrings Method | LogEvent Method | Popup Method | RegDelete Method | RegRead Method | RegWrite Method | Run Method | SendKeys Method | Exec Method

See Also

Running Your Scripts


CurrentDirectory Property

Retrieves or changes the current active directory.

object.CurrentDirectory

Arguments

object
WshShell object.

Remarks

The CurrentDirectory returns a string that contains the fully qualified path of the current working directory of the active process.

Example

The following code displays the current active directory.

[VBScript]
Dim WshShell
Set WshShell = WScript.CreateObject("WScript.Shell")
WScript.Echo WshShell.CurrentDirectory
[JScript]
var WshShell = WScript.CreateObject ("WScript.Shell");
WScript.Echo (WshShell.CurrentDirectory);

See Also

WshShell Object


Environment Property

Returns the WshEnvironment object (a collection of environment variables).

object.Environment ([strType])

Arguments

object
WshShell object.
strType
Optional. Specifies the location of the environment variable.

Remarks

The Environment property contains the WshEnvironment object (a collection of environment variables). If strType is supplied, it specifies where the environment variable resides with possible values of System, User, Volatile, or Process. If strType is not supplied, the Environment property returns different environment variable types depending on the operating system.

Type of Environment Variable | Operating System
System | Microsoft Windows NT/2000
Process | Windows 95/98/Me
Note For Windows 95/98/Me, only one strType is permitted — Process.

The following table lists some of the variables that are provided with the Windows operating system. Scripts can access environment variables that have been set by other applications.

Note None of the following variables are available from the Volatile type.
Name | Description | System | User | Process (NT/ 2000) | Process (98/ME)
NUMBER_OF_PROCESSORS | Number of processors running on the machine. | X | - | X | -
PROCESSOR_ARCHITECTURE | Processor type of the user's workstation. | X | - | X | -
PROCESSOR_IDENTIFIER | Processor ID of the user's workstation. | X | - | X | -
PROCESSOR_LEVEL | Processor level of the user's workstation. | X | - | X | -
PROCESSOR_REVISION | Processor version of the user's workstation. | X | - | X | -
OS | Operating system on the user's workstation. | X | - | X | -
COMSPEC | Executable file for the command prompt (typically cmd.exe). | X | - | X | X
HOMEDRIVE | Primary local drive (typically the C drive). | - | - | X | -
HOMEPATH | Default directory for users (typically \users\default in Windows 2000). | - | - | X | -
PATH | PATH environment variable. | X | X | X | X
PATHEXT | Extensions for executable files (typically .com, .exe, .bat, or .cmd). | X | - | X | -
PROMPT | Command prompt (typically $P$G). | - | - | X | X
SYSTEMDRIVE | Local drive on which the system directory resides (typically c:\). | - | - | X | -
SYSTEMROOT | System directory (for example, c:\winnt). This is the same as WINDIR. | - | - | X | -
WINDIR | System directory (for example, c:\winnt). This is the same as SYSTEMROOT. | X | - | X | X
TEMP | Directory for storing temporary files (for example, c:\temp). | - | X | X | X
TMP | Directory for storing temporary files (for example, c:\temp). | - | X | X | X

Example

The following code retrieves the system environment variable NUMBER_OF_PROCESSORS.

[VBScript]
Set WshShell = WScript.CreateObject("WScript.Shell")
Set WshSysEnv = WshShell.Environment("SYSTEM")
WScript.Echo WshSysEnv("NUMBER_OF_PROCESSORS")
[JScript]
var WshShell = WScript.CreateObject("WScript.Shell");
var WshSysEnv = WshShell.Environment("SYSTEM");
WScript.Echo(WshSysEnv("NUMBER_OF_PROCESSORS"));

See Also

WshEnvironment Object | WshShell Object


AppActivate Method

Activates an application window.

object.AppActivate title

Arguments

object
WshShell object.
title
Specifies which application to activate. This can be a string containing the title of the application (as it appears in the title bar) or the application's Process ID.

Remarks

The AppActivate method returns a Boolean value that identifies whether the procedure call is successful. This method changes the focus to the named application or window, but it does not affect whether it is maximized or minimized. Focus moves from the activated application window when the user takes action to change the focus (or closes the window).

In determining which application to activate, the specified title is compared to the title string of each running application. If no exact match exists, any application whose title string begins with title is activated. If an application still cannot be found, any application whose title string ends with title is activated. If more than one instance of the application named by title exists, one instance is arbitrarily activated.

Example

The following example demonstrates the use of a single .wsf file for two jobs in different script languages (VBScript and JScript). The functionality of both jobs is the same — each runs the Windows calculator and sends it keystrokes to execute a simple calculation.

The following example starts the Windows calculator and uses AppActivate to ensure that the calculator is at the top.

<package>
   <job id="vbs">
      <script language="VBScript">
         set WshShell = WScript.CreateObject("WScript.Shell")
         WshShell.Run "calc"
         WScript.Sleep 100
         WshShell.AppActivate "Calculator"
         WScript.Sleep 100
         WshShell.SendKeys "1{+}"
         WScript.Sleep 500
         WshShell.SendKeys "2"
         WScript.Sleep 500
         WshShell.SendKeys "~"
         WScript.Sleep 500
         WshShell.SendKeys "*3"
         WScript.Sleep 500
         WshShell.SendKeys "~"
         WScript.Sleep 2500
      </script>
   </job>

   <job id="js">
      <script language="JScript">
         var WshShell = WScript.CreateObject("WScript.Shell");
         WshShell.Run("calc");
         WScript.Sleep(100);
         WshShell.AppActivate("Calculator");
         WScript.Sleep(100);
         WshShell.SendKeys("1{+}");
         WScript.Sleep(500);
         WshShell.SendKeys("2");
         WScript.Sleep(500);
         WshShell.SendKeys("~");
         WScript.Sleep(500);
         WshShell.SendKeys("*3");
         WScript.Sleep(500);
         WshShell.SendKeys("~");
         WScript.Sleep(2500);
      </script>
   </job>
</package>

See Also

Running Your Scripts | WshShell Object | SendKeys Method


CreateShortcut Method

Creates a new shortcut, or opens an existing shortcut.

object.CreateShortcut(strPathname)

Arguments

object
WshShell object.
strPathname
String value indicating the pathname of the shortcut to create.

Remarks

The CreateShortcut method returns either a WshShortcut object or a WshURLShortcut object. Simply calling the CreateShortcut method does not result in the creation of a shortcut. The shortcut object and changes you may have made to it are stored in memory until you save it to disk with the Save method. To create a shortcut, you must:

  1. Create an instance of a WshShortcut object.
  2. Initialize its properties.
  3. Save it to disk with the Save method.
    Note A common problem is putting arguments in the TargetPath property of the shortcut object, which doesn't work. All arguments to the shortcut must be put in the Arguments property.

Example

The following example creates a WshShell object and uses the CreateShortcut method to create two shortcuts.

<package>
   <job id="vbs">
      <script language="VBScript">
         set WshShell = WScript.CreateObject("WScript.Shell")
         strDesktop = WshShell.SpecialFolders("Desktop")
         set oShellLink = WshShell.CreateShortcut(strDesktop & "\Shortcut Script.lnk")
         oShellLink.TargetPath = WScript.ScriptFullName
         oShellLink.WindowStyle = 1
         oShellLink.Hotkey = "CTRL+SHIFT+F"
         oShellLink.IconLocation = "notepad.exe, 0"
         oShellLink.Description = "Shortcut Script"
         oShellLink.WorkingDirectory = strDesktop
         oShellLink.Save
         set oUrlLink = WshShell.CreateShortcut(strDesktop & "\Microsoft Web Site.url")
         oUrlLink.TargetPath = "http://www.microsoft.com"
         oUrlLink.Save
      </script>
   </job>

   <job id="js">
      <script language="JScript">
         var WshShell = WScript.CreateObject("WScript.Shell");
         strDesktop = WshShell.SpecialFolders("Desktop");
         var oShellLink = WshShell.CreateShortcut(strDesktop + "\\Shortcut Script.lnk");
         oShellLink.TargetPath = WScript.ScriptFullName;
         oShellLink.WindowStyle = 1;
         oShellLink.Hotkey = "CTRL+SHIFT+F";
         oShellLink.IconLocation = "notepad.exe, 0";
         oShellLink.Description = "Shortcut Script";
         oShellLink.WorkingDirectory = strDesktop;
         oShellLink.Save();
         var oUrlLink = WshShell.CreateShortcut(strDesktop + "\\Microsoft Web Site.url");
         oUrlLink.TargetPath = "http://www.microsoft.com";
         oUrlLink.Save();
      </script>
   </job>
</package>

See Also

Running Your Scripts | WshShortcut Object | WshUrlShortcut Object | WshShell Object


ExpandEnvironmentStrings Method

Returns an environment variable's expanded value.

object.ExpandEnvironmentStrings(strString)

Arguments

object
WshShell object.
strString
String value indicating the name of the environment variable you want to expand.

Remarks

The ExpandEnvironmentStrings method expands environment variables defined in the PROCESS environment space only. Environment variable names, which must be enclosed between "%" characters, are not case-sensitive.

Example

The following code expands the Windows Directory environment variable and displays it:

[VBScript]
set WshShell = WScript.CreateObject("WScript.Shell")
WScript.Echo "WinDir is " & WshShell.ExpandEnvironmentStrings("%WinDir%")
[JScript]
var WshShell = WScript.CreateObject("WScript.Shell");
WScript.Echo("WinDir is " + WshShell.ExpandEnvironmentStrings("%WinDir%"));

See Also

WshShell Object


LogEvent Method

Adds an event entry to a log file.

object.LogEvent(intType, strMessage [,strTarget])

Arguments

object
WshShell object.
intType
Integer value representing the event type.
strMessage
String value containing the log entry text.
strTarget
Optional. String value indicating the name of the computer system where the event log is stored (the default is the local computer system). Applies to Windows NT/2000 only.

Remarks

The LogEvent method returns a Boolean value (true if the event is logged successfully, otherwise false). In Windows NT/2000, events are logged in the Windows NT Event Log. In Windows 9x/Me, events are logged in WSH.log (located in the Windows directory). There are six event types.

Type | Value
0 | SUCCESS
1 | ERROR
2 | WARNING
4 | INFORMATION
8 | AUDIT_SUCCESS
16 | AUDIT_FAILURE

Example

The following code logs SUCCESS or ERROR depending on the outcome of the function runLoginScript().

[VBScript]
Set WshShell = WScript.CreateObject("WScript.Shell")
rc = runLoginScript()      'Returns true if logon succeeds.

if rc then
   WshShell.LogEvent 0, "Logon Script Completed Successfully"
else
   WshShell.LogEvent 1, "Logon Script failed"
end if
[JScript]
var WshShell = WScript.CreateObject("WScript.Shell");
var rc = runLoginScript();

if (rc)
   WshShell.LogEvent(0, "Logon Script Completed Successfully");
else
   WshShell.LogEvent(1, "Logon Script failed");

See Also

WshShell Object


Popup Method

Displays text in a pop-up message box.

intButton = object.Popup(strText,[nSecondsToWait],[strTitle],[nType])

Arguments

object
WshShell object.
strText
String value containing the text you want to appear in the pop-up message box.
nSecondsToWait
Optional. Numeric value indicating the maximum length of time (in seconds) you want the pop-up message box displayed.
strTitle
Optional. String value containing the text you want to appear as the title of the pop-up message box.
nType
Optional. Numeric value indicating the type of buttons and icons you want in the pop-up message box. These determine how the message box is used.
IntButton
Integer value indicating the number of the button the user clicked to dismiss the message box. This is the value returned by the Popup method.

Remarks

The Popup method displays a message box regardless of which host executable file is running (WScript.exe or CScript.exe). If nSecondsToWaitis equals zero (the default), the pop-up message box remains visible until closed by the user. If nSecondsToWaitis is greater than zero, the pop-up message box closes after nSecondsToWait seconds. If you do not supply the argument strTitle, the title of the pop-up message box defaults to "Windows Script Host." The meaning of nType is the same as in the Microsoft Win32® application programming interface MessageBox function. The following tables show the values and their meanings. You can combine values in these tables.

Note To display text properly in RTL languages such as Hebrew or Arabic, add hex &h00100000 (decimal 1048576) to the nType parameter.

Button Types

Value | Description
0 | Show OK button.
1 | Show OK and Cancel buttons.
2 | Show Abort, Retry, and Ignore buttons.
3 | Show Yes, No, and Cancel buttons.
4 | Show Yes and No buttons.
5 | Show Retry and Cancel buttons.

Icon Types

Value | Description
16 | Show "Stop Mark" icon.
32 | Show "Question Mark" icon.
48 | Show "Exclamation Mark" icon.
64 | Show "Information Mark" icon.

The previous two tables do not cover all values for nType. For a complete list, see the Microsoft Win32 documentation.

The return value intButton denotes the number of the button that the user clicked. If the user does not click a button before nSecondsToWait seconds, intButton is set to -1.

Value | Description
1 | OK button
2 | Cancel button
3 | Abort button
4 | Retry button
5 | Ignore button
6 | Yes button
7 | No button

Example

The following code generates a simple pop-up window.

[VBScript]
Dim WshShell, BtnCode
Set WshShell = WScript.CreateObject("WScript.Shell")

BtnCode = WshShell.Popup("Do you feel alright?", 7, "Answer This Question:", 4 + 32)

Select Case BtnCode
   case 6      WScript.Echo "Glad to hear you feel alright."
   case 7      WScript.Echo "Hope you're feeling better soon."
   case -1     WScript.Echo "Is there anybody out there?"
End Select
[JScript]
var WshShell = WScript.CreateObject("WScript.Shell");
var BtnCode = WshShell.Popup("Do you feel alright?", 7, "Answer This Question:", 4 + 32);
switch(BtnCode) {
   case 6:
      WScript.Echo("Glad to hear you feel alright.");
      break;
   case 7:
      WScript.Echo("Hope you're feeling better soon.");
      break;
   case -1:
      WScript.Echo("Is there anybody out there?");
      break;
}

See Also

WshShell Object | Echo Method


RegDelete Method

Deletes a key or one of its values from the registry.

object.RegDelete(strName)

Arguments

object
WshShell object.
strName
String value indicating the name of the registry key or key value you want to delete.

Remarks

Specify a key-name by ending strName with a final backslash; leave it off to specify a value-name. Fully qualified key-names and value-names are prefixed with a root key. You may use abbreviated versions of root key names with the RegDelete method. The five possible root keys you can use are listed in the following table.

Root key Name | Abbreviation
HKEY_CURRENT_USER | HKCU
HKEY_LOCAL_MACHINE | HKLM
HKEY_CLASSES_ROOT | HKCR
HKEY_USERS | HKEY_USERS
HKEY_CURRENT_CONFIG | HKEY_CURRENT_CONFIG

Example

The following code creates a key and two values, reads them, and deletes them.

[VBScript]
Dim WshShell, bKey
Set WshShell = WScript.CreateObject("WScript.Shell")

WshShell.RegWrite "HKCU\Software\ACME\FortuneTeller\", 1, "REG_BINARY"
WshShell.RegWrite "HKCU\Software\ACME\FortuneTeller\MindReader", "Goocher!", "REG_SZ"

bKey = WshShell.RegRead("HKCU\Software\ACME\FortuneTeller\")
WScript.Echo WshShell.RegRead("HKCU\Software\ACME\FortuneTeller\MindReader")

WshShell.RegDelete "HKCU\Software\ACME\FortuneTeller\MindReader"
WshShell.RegDelete "HKCU\Software\ACME\FortuneTeller\"
WshShell.RegDelete "HKCU\Software\ACME\"
[JScript]
var WshShell = WScript.CreateObject("WScript.Shell");

WshShell.RegWrite ("HKCU\\Software\\ACME\\FortuneTeller\\", 1, "REG_BINARY");
WshShell.RegWrite ("HKCU\\Software\\ACME\\FortuneTeller\\MindReader", "Goocher!", "REG_SZ");

var bKey =    WshShell.RegRead ("HKCU\\Software\\ACME\\FortuneTeller\\");
WScript.Echo (WshShell.RegRead ("HKCU\\Software\\ACME\\FortuneTeller\\MindReader"));

WshShell.RegDelete ("HKCU\\Software\\ACME\\FortuneTeller\\MindReader");
WshShell.RegDelete ("HKCU\\Software\\ACME\\FortuneTeller\\");
WshShell.RegDelete ("HKCU\\Software\\ACME\\");

See Also

WshShell Object | RegRead Method | RegWrite Method


RegRead Method

Returns the value of a key or value-name from the registry.

object.RegRead(strName)

Arguments

object
WshShell object.
strName
String value indicating the key or value-name whose value you want.

Remarks

The RegRead method returns values of the following five types.

Type | Description | In the Form of
REG_SZ | A string | A string
REG_DWORD | A number | An integer
REG_BINARY | A binary value | A VBArray of integers
REG_EXPAND_SZ | An expandable string (e.g., "%windir%\\calc.exe") | A string
REG_MULTI_SZ | An array of strings | A VBArray of strings

You can specify a key-name by ending strName with a final backslash. Do not include a final backslash to specify a value-name. A value entry has three parts: its name, its data type, and its value. When you specify a key-name (as opposed to a value-name), RegRead returns the default value. To read a key's default value, specify the name of the key itself. Fully qualified key-names and value-names begin with a root key. You may use abbreviated versions of root key names with the RegRead method. The five possible root keys are listed in the following table.

Root key Name | Abbreviation
HKEY_CURRENT_USER | HKCU
HKEY_LOCAL_MACHINE | HKLM
HKEY_CLASSES_ROOT | HKCR
HKEY_USERS | HKEY_USERS
HKEY_CURRENT_CONFIG | HKEY_CURRENT_CONFIG

Example

The following code creates a key and two values, reads them, and deletes them.

[VBScript]
Dim WshShell, bKey
Set WshShell = WScript.CreateObject("WScript.Shell")

WshShell.RegWrite "HKCU\Software\ACME\FortuneTeller\", 1, "REG_BINARY"
WshShell.RegWrite "HKCU\Software\ACME\FortuneTeller\MindReader", "Goocher!", "REG_SZ"

bKey = WshShell.RegRead("HKCU\Software\ACME\FortuneTeller\")
WScript.Echo WshShell.RegRead("HKCU\Software\ACME\FortuneTeller\MindReader")

WshShell.RegDelete "HKCU\Software\ACME\FortuneTeller\MindReader"
WshShell.RegDelete "HKCU\Software\ACME\FortuneTeller\"
WshShell.RegDelete "HKCU\Software\ACME\"
[JScript]
var WshShell = WScript.CreateObject ("WScript.Shell");

WshShell.RegWrite ("HKCU\\Software\\ACME\\FortuneTeller\\", 1, "REG_BINARY");
WshShell.RegWrite ("HKCU\\Software\\ACME\\FortuneTeller\\MindReader", "Goocher!", "REG_SZ");

var bKey =    WshShell.RegRead ("HKCU\\Software\\ACME\\FortuneTeller\\");
WScript.Echo (WshShell.RegRead ("HKCU\\Software\\ACME\\FortuneTeller\\MindReader"));

WshShell.RegDelete ("HKCU\\Software\\ACME\\FortuneTeller\\MindReader");
WshShell.RegDelete ("HKCU\\Software\\ACME\\FortuneTeller\\");
WshShell.RegDelete ("HKCU\\Software\\ACME\\");

See Also

WshShell Object | RegDelete Method | RegWrite Method


RegWrite Method

Creates a new key, adds another value-name to an existing key (and assigns it a value), or changes the value of an existing value-name.

object.RegWrite(strName, anyValue [,strType])

Arguments

object
WshShell object.
strName
String value indicating the key-name, value-name, or value you want to create, add, or change.
anyValue
The name of the new key you want to create, the name of the value you want to add to an existing key, or the new value you want to assign to an existing value-name.
strType
Optional. String value indicating the value's data type.

Remarks

Specify a key-name by ending strName with a final backslash. Do not include a final backslash to specify a value name. The RegWrite method automatically converts the parameter anyValue to either a string or an integer. The value of strType determines its data type (either a string or an integer). The options for strType are listed in the following table.

Converted to | strType
String | REG_SZ
String | REG_EXPAND_SZ
Integer | REG_DWORD
Integer | REG_BINARY
Note The REG_MULTI_SZ type is not supported for the RegWrite method.
Tip RegWrite will write at most one DWORD to a REG_BINARY value. Larger values are not supported with this method.

Fully qualified key-names and value-names are prefixed with a root key. You may use abbreviated versions of root key names with the RegWrite method. The five root keys are listed in the following table.

Root key Name | Abbreviation
HKEY_CURRENT_USER | HKCU
HKEY_LOCAL_MACHINE | HKLM
HKEY_CLASSES_ROOT | HKCR
HKEY_USERS | HKEY_USERS
HKEY_CURRENT_CONFIG | HKEY_CURRENT_CONFIG

The four possible data types you can specify with strType are listed in the following table.

Type | Description | In the Form of
REG_SZ | A string | A string
REG_DWORD | A number | An integer
REG_BINARY | A binary value | An integer
REG_EXPAND_SZ | An expandable string (e.g., "%windir%\\calc.exe") | A string

Example

The following code creates a key and two values, reads them, and deletes them.

[VBScript]
Dim WshShell, bKey
Set WshShell = WScript.CreateObject("WScript.Shell")

WshShell.RegWrite "HKCU\Software\ACME\FortuneTeller\", 1, "REG_BINARY"
WshShell.RegWrite "HKCU\Software\ACME\FortuneTeller\MindReader", "Goocher!", "REG_SZ"

bKey = WshShell.RegRead("HKCU\Software\ACME\FortuneTeller\")
WScript.Echo WshShell.RegRead("HKCU\Software\ACME\FortuneTeller\MindReader")

WshShell.RegDelete "HKCU\Software\ACME\FortuneTeller\MindReader"
WshShell.RegDelete "HKCU\Software\ACME\FortuneTeller\"
WshShell.RegDelete "HKCU\Software\ACME\"
[JScript]
var WshShell = WScript.CreateObject("WScript.Shell");

WshShell.RegWrite ("HKCU\\Software\\ACME\\FortuneTeller\\", 1, "REG_BINARY");
WshShell.RegWrite ("HKCU\\Software\\ACME\\FortuneTeller\\MindReader", "Goocher!", "REG_SZ");

var bKey =    WshShell.RegRead ("HKCU\\Software\\ACME\\FortuneTeller\\");
WScript.Echo (WshShell.RegRead ("HKCU\\Software\\ACME\\FortuneTeller\\MindReader"));

WshShell.RegDelete ("HKCU\\Software\\ACME\\FortuneTeller\\MindReader");
WshShell.RegDelete ("HKCU\\Software\\ACME\\FortuneTeller\\");
WshShell.RegDelete ("HKCU\\Software\\ACME\\");

See Also

WshShell Object | RegDelete Method | RegRead Method


Run Method

Runs a program in a new process.

object.Run(strCommand, [intWindowStyle], [bWaitOnReturn])

Arguments

object
WshShell object.
strCommand
String value indicating the command line you want to run. You must include any parameters you want to pass to the executable file.
intWindowStyle
Optional. Integer value indicating the appearance of the program's window. Note that not all programs make use of this information.
bWaitOnReturn
Optional. Boolean value indicating whether the script should wait for the program to finish executing before continuing to the next statement in your script. If set to true, script execution halts until the program finishes, and Run returns any error code returned by the program. If set to false (the default), the Run method returns immediately after starting the program, automatically returning 0 (not to be interpreted as an error code).

Remarks

The Run method returns an integer. The Run method starts a program running in a new Windows process. You can have your script wait for the program to finish execution before continuing. This allows you to run scripts and programs synchronously. Environment variables within the argument strCommand are automatically expanded. If a file type has been properly registered to a particular program, calling run on a file of that type executes the program. For example, if Word is installed on your computer system, calling Run on a *.doc file starts Word and loads the document. The following table lists the available settings for intWindowStyle.

intWindowStyle | Description
0 | Hides the window and activates another window.
1 | Activates and displays a window. If the window is minimized or maximized, the system restores it to its original size and position. An application should specify this flag when displaying the window for the first time.
2 | Activates the window and displays it as a minimized window.
3 | Activates the window and displays it as a maximized window.
4 | Displays a window in its most recent size and position. The active window remains active.
5 | Activates the window and displays it in its current size and position.
6 | Minimizes the specified window and activates the next top-level window in the Z order.
7 | Displays the window as a minimized window. The active window remains active.
8 | Displays the window in its current state. The active window remains active.
9 | Activates and displays the window. If the window is minimized or maximized, the system restores it to its original size and position. An application should specify this flag when restoring a minimized window.
10 | Sets the show-state based on the state of the program that started the application.

Example 1

The following VBScript code opens a copy of the currently running script with Notepad.

Set WshShell = WScript.CreateObject("WScript.Shell")
WshShell.Run "%windir%\notepad " & WScript.ScriptFullName

The following VBScript code does the same thing, except it specifies the window type, waits for Notepad to be shut down by the user, and saves the error code returned from Notepad when it is shut down.

Set WshShell = WScript.CreateObject("WScript.Shell")
Return = WshShell.Run("notepad " & WScript.ScriptFullName, 1, true)

Example 2

The following VBScript code opens a command window, changes to the path to C:\ , and executes the DIR command.

Dim oShell
Set oShell = WScript.CreateObject ("WSCript.shell")
oShell.run "cmd /K CD C:\ & Dir"
Set oShell = Nothing

See Also

WshShell Object


SendKeys Method

Sends one or more keystrokes to the active window (as if typed on the keyboard).

object.SendKeys(string)

Arguments

object
WshShell object.
string
String value indicating the keystroke(s) you want to send.

Remarks

Use the SendKeys method to send keystrokes to applications that have no automation interface. Most keyboard characters are represented by a single keystroke. Some keyboard characters are made up of combinations of keystrokes (CTRL+SHIFT+HOME, for example). To send a single keyboard character, send the character itself as the string argument. For example, to send the letter x, send the string argument "x".

Note To send a space, send the string " ".

You can use SendKeys to send more than one keystroke at a time. To do this, create a compound string argument that represents a sequence of keystrokes by appending each keystroke in the sequence to the one before it. For example, to send the keystrokes a, b, and c, you would send the string argument "abc". The SendKeys method uses some characters as modifiers of characters (instead of using their face-values). This set of special characters consists of parentheses, brackets, braces, and the:

  • plus sign "+",
  • caret "^",
  • percent sign "%",
  • and tilde "~"

Send these characters by enclosing them within braces "{}". For example, to send the plus sign, send the string argument "{+}". Brackets "[ ]" have no special meaning when used with SendKeys, but you must enclose them within braces to accommodate applications that do give them a special meaning (for dynamic data exchange (DDE) for example).

  • To send bracket characters, send the string argument "{[}" for the left bracket and "{]}" for the right one.
  • To send brace characters, send the string argument "{{}" for the left brace and "{}}" for the right one.

Some keystrokes do not generate characters (such as ENTER and TAB). Some keystrokes represent actions (such as BACKSPACE and BREAK). To send these kinds of keystrokes, send the arguments shown in the following table:

Key | Argument
BACKSPACE | {BACKSPACE}, {BS}, or {BKSP}
BREAK | {BREAK}
CAPS LOCK | {CAPSLOCK}
DEL or DELETE | {DELETE} or {DEL}
DOWN ARROW | {DOWN}
END | {END}
ENTER | {ENTER} or ~
ESC | {ESC}
HELP | {HELP}
HOME | {HOME}
INS or INSERT | {INSERT} or {INS}
LEFT ARROW | {LEFT}
NUM LOCK | {NUMLOCK}
PAGE DOWN | {PGDN}
PAGE UP | {PGUP}
PRINT SCREEN | {PRTSC}
RIGHT ARROW | {RIGHT}
SCROLL LOCK | {SCROLLLOCK}
TAB | {TAB}
UP ARROW | {UP}
F1 | {F1}
F2 | {F2}
F3 | {F3}
F4 | {F4}
F5 | {F5}
F6 | {F6}
F7 | {F7}
F8 | {F8}
F9 | {F9}
F10 | {F10}
F11 | {F11}
F12 | {F12}
F13 | {F13}
F14 | {F14}
F15 | {F15}
F16 | {F16}

To send keyboard characters that are comprised of a regular keystroke in combination with a SHIFT, CTRL, or ALT, create a compound string argument that represents the keystroke combination. You do this by preceding the regular keystroke with one or more of the following special characters:

Key | Special Character
SHIFT | +
CTRL | ^
ALT | %
Note When used this way, these special characters are not enclosed within a set of braces.

To specify that a combination of SHIFT, CTRL, and ALT should be held down while several other keys are pressed, create a compound string argument with the modified keystrokes enclosed in parentheses. For example, to send the keystroke combination that specifies that the SHIFT key is held down while:

  • e and c are pressed, send the string argument "+(ec)".
  • e is pressed, followed by a lone c (with no SHIFT), send the string argument "+ec".

You can use the SendKeys method to send a pattern of keystrokes that consists of a single keystroke pressed several times in a row. To do this, create a compound string argument that specifies the keystroke you want to repeat, followed by the number of times you want it repeated. You do this using a compound string argument of the form {keystroke number}. For example, to send the letter "x" ten times, you would send the string argument "{x 10}". Be sure to include a space between keystroke and number.

Note The only keystroke pattern you can send is the kind that is comprised of a single keystroke pressed several times. For example, you can send "x" ten times, but you cannot do the same for "Ctrl+x".
Note You cannot send the PRINT SCREEN key {PRTSC} to an application.

Example

The following example demonstrates the use of a single .wsf file for two jobs in different script languages (VBScript and JScript). Each job runs the Windows calculator and sends it keystrokes to execute a simple calculation.

<package>
   <job id="vbs">
      <script language="VBScript">
         set WshShell = WScript.CreateObject("WScript.Shell")
         WshShell.Run "calc"
         WScript.Sleep 100
         WshShell.AppActivate "Calculator"
         WScript.Sleep 100
         WshShell.SendKeys "1{+}"
         WScript.Sleep 500
         WshShell.SendKeys "2"
         WScript.Sleep 500
         WshShell.SendKeys "~"
         WScript.Sleep 500
         WshShell.SendKeys "*3"
         WScript.Sleep 500
         WshShell.SendKeys "~"
         WScript.Sleep 2500
      </script>
   </job>

   <job id="js">
      <script language="JScript">
         var WshShell = WScript.CreateObject("WScript.Shell");
         WshShell.Run("calc");
         WScript.Sleep(100);
         WshShell.AppActivate("Calculator");
         WScript.Sleep(100);
         WshShell.SendKeys ("1{+}");
         WScript.Sleep(500);
         WshShell.SendKeys("2");
         WScript.Sleep(500);
         WshShell.SendKeys("~");
         WScript.Sleep(500);
         WshShell.SendKeys("*3");
         WScript.Sleep(500);
         WshShell.SendKeys("~");
         WScript.Sleep(2500);
      </script>
   </job>
</package>

See Also

WshShell Object | Run Method


Exec Method

Runs an application in a child command-shell, providing access to the StdIn/StdOut/StdErr streams.

object.Exec(strCommand)

Arguments

object
WshShell object.
strCommand
String value indicating the command line used to run the script. The command line should appear exactly as it would if you typed it at the command prompt.

Remarks

The Exec method returns a WshScriptExec object, which provides status and error information about a script run with Exec along with access to the StdIn, StdOut, and StdErr channels. The Exec method allows the execution of command line applications only. The Exec method cannot be used to run remote scripts. Do not confuse the Exec method with the Execute method (of the WshRemote object).

Example

The following example demonstrates the basics of the Exec method.

[VBScript]
Dim WshShell, oExec
Set WshShell = CreateObject("WScript.Shell")

Set oExec = WshShell.Exec("calc")

Do While oExec.Status = 0
     WScript.Sleep 100
Loop

WScript.Echo oExec.Status
[JScript]
var WshShell = new ActiveXObject("WScript.Shell");
var oExec = WshShell.Exec("calc");

while (oExec.Status == 0)
{
     WScript.Sleep(100);
}

WScript.Echo(oExec.Status);

See Also

WshScriptExec Object


WshController Object

Provides access to the CreateScript() method (for creating a remote script process).

Example

The following example uses a controller object to create a WshRemote object.

[VBScript]
Dim Controller, RemoteScript
Set Controller = WScript.CreateObject("WSHController")
Set RemoteScript = Controller.CreateScript("remote1.js")
RemoteScript.Execute

Do While RemoteScript.Status <> 2
    WScript.Sleep 100
Loop
[JScript]
var Controller = WScript.CreateObject("WSHController");
var RemoteScript = Controller.CreateScript("test.js", "remoteserver");
RemoteScript.Execute();

while (RemoteScript.Status != 2) {
    WScript.Sleep(100);
}

Methods

CreateScript Method

See Also

CreateObject Method


CreateScript Method

Creates a WshRemote object.

object.CreateScript(CommandLine,[MachineName])

Parameters

object
WshController Object.
Commandline
Required. String value indicating the script's path and switches as they would be typed at the command prompt. The path to the script should appear as seen from the controller computer system rather than the computer system on which you want to run the script.
MachineName
Optional. String value indicating the name of the remote computer system (the computer on which you want to run the remote script). It is specified in the Uniform Naming Convention (UNC).

Remarks

The CreateScript method returns a handle to an instance of a WshRemote object. The path part of the script name does not need to be local — it can refer to a script on a network share. This makes it possible to sit at one computer system, retrieve a script from another computer system, and run it on a third computer system. If a machine name is not provided, the remote script object runs on the controller computer system (this is the default). If a machine name is provided, the remote script object runs on the named computer system. The CreateScript method establishes a connection with the remote computer system and sets it up to run the script, but the script does not actually start until you call the Execute method of the WshRemote object.

Example

The following example demonstrates how the CreateScript method of the WshController object is used to create a WshRemote object (an instance of a remote script).

[VBScript]
Dim Controller, RemoteScript
Set Controller = WScript.CreateObject("WSHController")
Set RemoteScript = Controller.CreateScript("test.js", "remoteserver")
WScript.ConnectObject RemoteScript, "remote_"
RemoteScript.Execute

Do While RemoteScript.Status <> 2
    WScript.Sleep 100
Loop

WScript.DisconnectObject RemoteScript

Sub remote_Error
    Dim theError
    Set theError = RemoteScript.Error
    WScript.Echo "Error " & theError.Number & " - Line: " & theError.Line & ", Char: " & theError.Character & vbCrLf & "Description: " & theError.Description
    WScript.Quit -1
End Sub
[JScript]
var Controller = WScript.CreateObject("WSHController");
var RemoteScript = Controller.CreateScript("test.js", "remoteserver");
WScript.ConnectObject(RemoteScript, "remote_");
RemoteScript.Execute();

while (RemoteScript.Status != 2) {
    WScript.Sleep(100);
}

WScript.DisconnectObject(RemoteScript);

function remote_Error()
{
    var theError = RemoteScript.Error;
    WScript.Echo("Error " + theError.Number + " - Line: " + theError.Line + ", Char: " + theError.Character + "\nDescription: " + theError.Description);
    WScript.Quit(-1);
}

See Also

CreateObject Method | CreateScript Method | WshRemote Object | Execute Method


Environment Object

WshEnvironment Object

Environment PropertyWshShell Object

Provides access to the collection of Windows environment variables.

Remarks

The WshEnvironment object is a collection of environment variables that is returned by the WshShell object's Environment property. This collection contains the entire set of environment variables (those with names and those without). To retrieve individual environment variables (and their values) from this collection, use the environment variable name as the index.

Example

The following code displays an environment variable.

[VBScript]
Set WshShell = WScript.CreateObject("WScript.Shell")
Set WshSysEnv = WshShell.Environment("SYSTEM")
WScript.Echo WshSysEnv("NUMBER_OF_PROCESSORS")
[JScript]
var WshShell = WScript.CreateObject("WScript.Shell");
var WshSysEnv = WshShell.Environment("SYSTEM");
WScript.Echo(WshSysEnv("NUMBER_OF_PROCESSORS"));

Properties

Item Property | Length Property (WshEnvironment object)

Methods

Count Method | Remove Method

See Also

Environment Property


Remove Method

Removes an existing environment variable.

object.Remove(strName)

Arguments

object
WshEnvironment object.
strName
String value indicating the name of the environment variable you want to remove.

Remarks

The Remove method removes environment variables from the following types of environments: PROCESS, USER, SYSTEM, and VOLATILE. Environment variables removed with the Remove method are not removed permanently; they are only removed for the current session.

Example

The following code removes the Process environment variable TestVar.

[VBScript]
Dim WshShell, WshEnv
Set WshShell = WScript.CreateObject("WScript.Shell")
Set WshEnv = WshShell.Environment("PROCESS")
WshEnv("TestVar") = "Windows Script Host"
WScript.Echo WshShell.ExpandEnvironmentStrings("The value of the test variable is: '%TestVar%'")
WshEnv.Remove "TestVar"
WScript.Echo WshShell.ExpandEnvironmentStrings("The value of the test variable is: '%TestVar%'")
[JScript]
var WshShell = WScript.CreateObject("WScript.Shell");
var WshEnv = WshShell.Environment("PROCESS");
WshEnv("TestVar") = "Windows Script Host";
WScript.Echo(WshShell.ExpandEnvironmentStrings("The value of the test variable is: '%TestVar%'"));
WshEnv.Remove("TestVar");
WScript.Echo(WshShell.ExpandEnvironmentStrings("The value of the test variable is: '%TestVar%'"));

See Also

WshEnvironment Object | Environment Property


Named Object

WshNamed Object

Named PropertyWshArguments Object

Provides access to the named arguments from the command line.

Remarks

The Named property of the WshArguments object returns the WshNamed object, which is a collection of arguments that have names. This collection uses the argument name as the index to retrieve individual argument values. There are three ways to access sets of command-line arguments.

  • You can access the entire set of arguments (those with and without names) with the WshArguments object.
  • You can access the arguments that have names with the WshNamed object.
  • You can access the arguments that have no names with the WshUnnamed object.

Example

The following code displays the number of named and unnamed command-line arguments.

<package>
<job id="JS">
<script language="JScript">

var argsNamed = WScript.Arguments.Named;
var argsUnnamed = WScript.Arguments.Unnamed;

WScript.Echo("There are " + argsNamed.length + " named arguments.");
WScript.Echo("There are " + argsUnnamed.length + " unnamed arguments.");

</script>
</job>

<job id="VBS">
<script language="VBScript">

Dim argsNamed, argsUnnamed
Set argsNamed = WScript.Arguments.Named
Set argsUnnamed = WScript.Arguments.Unnamed

WScript.Echo "There are " & argsNamed.Count & " named arguments."
WScript.Echo "There are " & argsUnnamed.Count & " unnamed arguments."

</script>
</job>
</package>

Properties

Item Property | Length Property

Methods

Count Method | Exists Method

See Also

WshArguments Object | WshUnnamed Object


Item Property

Item Property (WshNamed)

Provides access to the items in the WshNamed object.

Object.Item(key)

Parameters

Object
WshNamed object
key
The name of the item you want to retrieve.

Remarks

The Item property returns a string. For collections, it returns an item based on the specified key. When entering the arguments at the command line, you can use blanks in string arguments if you enclose the string in quotes. Consider the following example:
myscript.vbs /stringarg:"This string has spaces"

The quotes will be removed in the WshNamed collection. For an argument to be in the WshNamed collection, it must have been used on the command line. If the argument has no value (such as a simple argument or an empty string), the Item property returns an empty string. Requesting a non-existent named argument from the Item property causes an error. To check if an argument exists, use the Exists method.

Example 1

In the following example, two named arguments are supplied to run a script. Inside the script, code causes the named arguments to be output. The Item property is used to index into the named arguments collection.

The following line is typed at the command prompt to run the script.

myScript.vbs /c:arg1 /d:arg2

If the following code is executed inside the script:

WScript.Echo WScript.Arguments.Named.Item("c")
WScript.Echo WScript.Arguments.Named.Item("d")

then the following output is produced:

arg1
arg2

See Also

WshNamed Object | WshUnnamed Object | Count Method | Item Property | Exists Method


Exists Method

Indicates whether a specific key value exists in the WshNamed object.

object.Exists(key)

Parameters

object
WshNamed object.
Key
String value indicating an argument of the WshNamed object.

Remarks

The Exists method returns a Boolean value. It returns true if the requested argument was specified on the command line (otherwise, it returns false).

Example

Consider the following information typed at the command line.

myScript.vbs /c:"WSH is a wonderful thing"

You could use these two lines of JScript code to find out whether the following command line switches were used to start the script.

WScript.Echo(WScript.Arguments.Named.Exists("C"));
WScript.Echo(WScript.Arguments.Named.Exists("D"));

See Also

Arguments Property | WshNamed Object | WshUnnamed Object | Count Method | Item Property


WshNetwork Object

WScript Object

Provides access to the shared resources on the network to which your computer is connected.

Remarks

You create a WshNetwork object when you want to connect to network shares and network printers, disconnect from network shares and network printers, map or remove network shares, or access information about a user on the network.

Example

The following example demonstrates displaying the domain name, computer name, and user name for the current computer system using the WshNetwork object.

<package>
   <job id="vbs">
      <script language="VBScript">
         Set WshNetwork = WScript.CreateObject("WScript.Network")
         WScript.Echo "Domain = " & WshNetwork.UserDomain
         WScript.Echo "Computer Name = " & WshNetwork.ComputerName
         WScript.Echo "User Name = " & WshNetwork.UserName
      </script>
   </job>

   <job id="js">
      <script language="JScript">
         var WshNetwork = WScript.CreateObject("WScript.Network");
         WScript.Echo("Domain = " + WshNetwork.UserDomain);
         WScript.Echo("Computer Name = " + WshNetwork.ComputerName);
         WScript.Echo("User Name = " + WshNetwork.UserName);
      </script>
   </job>
</package>

Properties

ComputerName Property | UserDomain Property | UserName Property

Methods

AddWindowsPrinterConnection Method | AddPrinterConnection Method | EnumNetworkDrives Method | EnumPrinterConnection Method | MapNetworkDrive Method | RemoveNetworkDrive Method | RemovePrinterConnection Method | SetDefaultPrinter Method

See Also

Running Your Scripts | WScript Object


UserDomain Property

Returns a user's domain name.

object.UserDomain

Arguments

object
WshNetwork object.

Remarks

String.

The UserDomain property does not work on Windows98 and Windows ME unless the USERDOMAIN environment variable is set. The variable is not set by default.

Example

The following example demonstrates the use of the UserDomain property:

<package>
   <job id="vbs">
      <script language="VBScript">
         Set WshNetwork = WScript.CreateObject("WScript.Network")
         WScript.Echo "Domain = " & WshNetwork.UserDomain
         WScript.Echo "Computer Name = " & WshNetwork.ComputerName
         WScript.Echo "User Name = " & WshNetwork.UserName
      </script>
   </job>

   <job id="js">
      <script language="JScript">
         var WshNetwork = WScript.CreateObject("WScript.Network");
         WScript.Echo("Domain = " + WshNetwork.UserDomain);
         WScript.Echo("Computer Name = " + WshNetwork.ComputerName);
         WScript.Echo("User Name = " + WshNetwork.UserName);
         }
      </script>
   </job>
</package>

See Also

Running Your Scripts | WshNetwork Object


UserName Property

Returns the name of a user.

object.UserName

Arguments

object
WshNetwork object.

Remarks

String.

If you are using this property in a login script, see Creating an Automated Login Script.

Example

The following example demonstrates the use of the UserName property:

<package>
   <job id="vbs">
      <script language="VBScript">
         Set WshNetwork = WScript.CreateObject("WScript.Network")
         WScript.Echo "Domain = " & WshNetwork.UserDomain
         WScript.Echo "Computer Name = " & WshNetwork.ComputerName
         WScript.Echo "User Name = " & WshNetwork.UserName
      </script>
   </job>

   <job id="js">
      <script language="JScript">
         var WshNetwork = WScript.CreateObject("WScript.Network");
         WScript.Echo("Domain = " + WshNetwork.UserDomain);
         WScript.Echo("Computer Name = " + WshNetwork.ComputerName);
         WScript.Echo("User Name = " + WshNetwork.UserName);
         }
      </script>
   </job>
</package>

See Also

Running Your Scripts | WshNetwork Object


ComputerName Property

Returns the name of the computer system.

object.ComputerName

Arguments

object
WshNetwork object.

Remarks

The ComputerName property contains a string value indicating the name of the computer system.

Example

The following example demonstrates the use of the ComputerName property.

<package>
   <job id="vbs">
      <script language="VBScript">
         Set WshNetwork = WScript.CreateObject("WScript.Network")
         WScript.Echo "Domain = " & WshNetwork.UserDomain
         WScript.Echo "Computer Name = " & WshNetwork.ComputerName
         WScript.Echo "User Name = " & WshNetwork.UserName
      </script>
   </job>

   <job id="js">
      <script language="JScript">
         var WshNetwork = WScript.CreateObject("WScript.Network");
         WScript.Echo("Domain = " + WshNetwork.UserDomain);
         WScript.Echo("Computer Name = " + WshNetwork.ComputerName);
         WScript.Echo("User Name = " + WshNetwork.UserName);
         }
      </script>
   </job>
</package>

See Also

Running Your Scripts | WshNetwork Object


AddWindowsPrinterConnection Method

Adds a Windows-based printer connection to your computer system.

Windows NT/2000:
object.AddWindowsPrinterConnection(
   strPrinterPath
)
Windows 9x/Me:
object.AddWindowsPrinterConnection(
   strPrinterPath,
   strDriverName[,strPort]
)

Arguments

object
WshNetwork object.
strPrinterPath
String value indicating the path to the printer connection.
strDriverName
String value indicating the name of the driver (ignored if used on Windows NT/Windows 2000).
strPort
Optional. String value specifying a printer port for the printer connection (ignored on Windows NT/Windows 2000).

Remarks

Using this method is similar to using the Printer option on Control Panel to add a printer connection. Unlike the AddPrinterConnection method, this method allows you to create a printer connection without directing it to a specific port, such as LPT1. If the connection fails, an error is thrown. In Windows 9x/Me, the printer driver must already be installed on the machine for the AddWindowsPrinterConnection method to work. If the driver is not installed, Windows returns an error message.

Example 1

The following code uses the AddWindowsPrinterConnection method to connect a network printer to a Windows NT/2000 computer system.

[VBScript]
Set WshNetwork = WScript.CreateObject("WScript.Network")
PrinterPath = "\\printserv\DefaultPrinter"
WshNetwork.AddWindowsPrinterConnection PrinterPath
[JScript]
var WshNetwork = WScript.CreateObject("WScript.Network");
var PrinterPath = "\\\\printserv\\DefaultPrinter";
WshNetwork.AddWindowsPrinterConnection(PrinterPath);

Example 2

The following code uses the AddWindowsPrinterConnection method to connect a network printer to a Windows 9x/Me computer system.

[VBScript]
Set WshNetwork = WScript.CreateObject("WScript.Network")
PrinterPath = "\\printserv\DefaultPrinter"
PrinterDriver = "Lexmark Optra S 1650"
WshNetwork.AddWindowsPrinterConnection PrinterPath, PrinterDriver
[JScript]
var WshNetwork = WScript.CreateObject("WScript.Network");
var PrinterPath = "\\\\printserv\\DefaultPrinter";
var PrinterDriver = "Lexmark Optra S 1650";
WshNetwork.AddWindowsPrinterConnection(PrinterPath, PrinterDriver);

See Also

WshNetwork Object | AddPrinterConnection Method | EnumPrinterConnections Method | RemovePrinterConnection Method | SetDefaultPrinter Method


AddPrinterConnection Method

Adds a remote MS-DOS-based printer connection to your computer system.

object.AddPrinterConnection(strLocalName, strRemoteName[,bUpdateProfile][,strUser][,strPassword])

Arguments

object
WshNetwork object.
strLocalName
Sting value indicating the local name to assign to the connected printer.
strRemoteName
Sting value indicating the name of the remote printer.
bUpdateProfile
Optional. Boolean value indicating whether the printer mapping is stored in the current user's profile. If bUpdateProfile is supplied and is true, the mapping is stored in the user profile. The default value is false.
strUser
Optional. String value indicating the user name. If you are mapping a remote printer using the profile of someone other than current user, you can specify strUser and strPassword.
strPassword
Optional. String value indicating the user password. If you are mapping a remote printer using the profile of someone other than current user, you can specify strUser and strPassword.

Remarks

The AddPrinterConnection method adds a network printer to an MS-DOS printer port, such as LPT1. You cannot use this method to add a remote Windows-based printer connection. To add a remote Windows-based printer connection, use the AddWindowsPrinterConnection method.

Example

The following code uses the AddPrinterConnection method to connect a network printer to LPT1.

[VBScript]
Set WshNetwork = WScript.CreateObject("WScript.Network")
WshNetwork.AddPrinterConnection "LPT1", "\\Server\Print1"
[JScript]
var WshNetwork = WScript.CreateObject("WScript.Network");
WshNetwork.AddPrinterConnection ("LPT1", "\\\\Server\\Print1");

See Also

WshNetwork Object | AddWindowsPrinterConnection Method | EnumPrinterConnections Method | RemovePrinterConnection Method | SetDefaultPrinter Method


EnumNetworkDrives Method

Returns the current network drive mapping information.

objDrives = object.EnumNetworkDrives

Arguments

object
WshNetwork object.
objDrives
Variable that holds the network drive mapping information.

Remarks

The EnumNetworkDrives method returns a collection. This collection is an array that associates pairs of items — network drive local names and their associated UNC names. Even-numbered items in the collection represent local names of logical drives. Odd-numbered items represent the associated UNC share names. The first item in the collection is at index zero (0).

Example

The following example uses EnumNetworkDrives to generate a list of the networked drives and displays the mapping information.

<package>
   <job id="vbs">
      <script language="VBScript">
         Set WshNetwork = WScript.CreateObject("WScript.Network")
         Set oDrives = WshNetwork.EnumNetworkDrives
         Set oPrinters = WshNetwork.EnumPrinterConnections
         WScript.Echo "Network drive mappings:"
         For i = 0 to oDrives.Count - 1 Step 2
            WScript.Echo "Drive " & oDrives.Item(i) & " = " & oDrives.Item(i+1)
         Next
         WScript.Echo
         WScript.Echo "Network printer mappings:"
         For i = 0 to oPrinters.Count - 1 Step 2
            WScript.Echo "Port " & oPrinters.Item(i) & " = " & oPrinters.Item(i+1)
         Next
      </script>
   </job>

   <job id="js">
      <script language="JScript">
         var WshNetwork = WScript.CreateObject("WScript.Network");
         var oDrives = WshNetwork.EnumNetworkDrives();
         var oPrinters = WshNetwork.EnumPrinterConnections();
         WScript.Echo("Network drive mappings:");
         for(i = 0; i < oDrives.length; i += 2) {
            WScript.Echo("Drive " + oDrives.Item(i) + " = " + oDrives.Item(i + 1));
         }
         WScript.Echo();
         WScript.Echo("Network printer mappings:");
         for(i = 0; i < oPrinters.length; i += 2) {
            WScript.Echo("Port " + oPrinters.Item(i) + " = " + oPrinters.Item(i + 1));
         }
      </script>
   </job>
</package>

See Also

Running Your Scripts | WshNetwork Object | MapNetworkDrive Method | RemoveNetworkDrive Method


EnumPrinterConnections Method

Returns the current network printer mapping information.

objPrinters = object.EnumPrinterConnections

Arguments

object
WshNetwork object.
objPrinters
Variable that holds the network printer mapping information.

Remarks

The EnumPrinterConnections method returns a collection. This collection is an array that associates pairs of items — network printer local names and their associated UNC names. Even-numbered items in the collection represent printer ports. Odd-numbered items represent the networked printer UNC names. The first item in the collection is at index zero (0).

Example

The following example uses the EnumPrinterConnections method to generate a list of networked printers and displays this mapping information.

<package>
   <job id="vbs">
      <script language="VBScript">
         Set WshNetwork = WScript.CreateObject("WScript.Network")
         Set oDrives = WshNetwork.EnumNetworkDrives
         Set oPrinters = WshNetwork.EnumPrinterConnections
         WScript.Echo "Network drive mappings:"
         For i = 0 to oDrives.Count - 1 Step 2
            WScript.Echo "Drive " & oDrives.Item(i) & " = " & oDrives.Item(i+1)
         Next
         WScript.Echo
         WScript.Echo "Network printer mappings:"
         For i = 0 to oPrinters.Count - 1 Step 2
            WScript.Echo "Port " & oPrinters.Item(i) & " = " & oPrinters.Item(i+1)
         Next
   </script>
</job>

   <job id="js">
      <script language="JScript">
         var WshNetwork = WScript.CreateObject("WScript.Network");
         var oDrives = WshNetwork.EnumNetworkDrives();
         var oPrinters = WshNetwork.EnumPrinterConnections();
         WScript.Echo("Network drive mappings:");
         for(i = 0; i < oDrives.length; i += 2) {
            WScript.Echo("Drive " + oDrives.Item(i) + " = " + oDrives.Item(i + 1));
         }
         WScript.Echo();
         WScript.Echo("Network printer mappings:");
         for(i = 0; i < oPrinters.length; i += 2) {
            WScript.Echo("Port " + oPrinters.Item(i) + " = " + oPrinters.Item(i + 1));
         }
      </script>
   </job>
</package>

See Also

Running Your Scripts | WshNetwork Object | AddPrinterConnection Method | AddWindowsPrinterConnection Method | RemovePrinterConnection Method | SetDefaultPrinter Method


MapNetworkDrive Method

Adds a shared network drive to your computer system.

object.MapNetworkDrive(strLocalName, strRemoteName, [bUpdateProfile], [strUser], [strPassword])

Arguments

object
WshNetwork object.
strLocalName
String value indicating the name by which the mapped drive will be known locally.
strRemoteName
String value indicating the share's UNC name (\\xxx\yyy).
bUpdateProfile
Optional. Boolean value indicating whether the mapping information is stored in the current user's profile. If bUpdateProfile is supplied and has a value of true, the mapping is stored in the user profile (the default is false).
strUser
Optional. String value indicating the user name. You must supply this argument if you are mapping a network drive using the credentials of someone other than the current user.
strPassword
Optional. String value indicating the user password. You must supply this argument if you are mapping a network drive using the credentials of someone other than the current user.

Remarks

An attempt to map a non-shared network drive results in an error.

Example

The following code maps the logical drive "E" to a network share with the UNC name "\\Server\Public."

[VBScript]
Dim WshNetwork
Set WshNetwork = WScript.CreateObject("WScript.Network")
WshNetwork.MapNetworkDrive "E:", "\\Server\Public"
[JScript]
var WshNetwork = WScript.CreateObject("WScript.Network");
WshNetwork.MapNetworkDrive ("E:", "\\\\Server\\Public");

See Also

WshNetwork Object | EnumNetworkDrives Method | RemoveNetworkDrive Method


RemoveNetworkDrive Method

Removes a shared network drive from your computer system.

object.RemoveNetworkDrive(strName, [bForce], [bUpdateProfile])

Arguments

object
WshNetwork object.
strName
String value indicating the name of the mapped drive you want to remove. The strName parameter can be either a local name or a remote name depending on how the drive is mapped.
bForce
Optional. Boolean value indicating whether to force the removal of the mapped drive. If bForce is supplied and its value is true, this method removes the connections whether the resource is used or not.
bUpdateProfile
Optional. String value indicating whether to remove the mapping from the user's profile. If bUpdateProfile is supplied and its value is true, this mapping is removed from the user profile. bUpdateProfile is false by default.

Remarks

If the drive has a mapping between a local name (drive letter) and a remote name (UNC name), then strName must be set to the local name. If the network path does not have a local name (drive letter) mapping, then strName must be set to the remote name.

Example

The following code removes the logical drive "E."

[VBScript]
Dim WshNetwork
Set WshNetwork = WScript.CreateObject("WScript.Network")
WshNetwork.RemoveNetworkDrive "E:"
[JScript]
var WshNetwork = WScript.CreateObject("WScript.Network");
WshNetwork.RemoveNetworkDrive ("E:");

See Also

WshNetwork Object | EnumNetworkDrives Method | MapNetworkDrive Method


RemovePrinterConnection Method

Removes a shared network printer connection from your computer system.

object.RemovePrinterConnection(strName, [bForce], [bUpdateProfile])

Arguments

object
WshNetwork object.
strName
String value indicating the name that identifies the printer. It can be a UNC name (in the form \\xxx\yyy) or a local name (such as LPT1).
bForce
Optional. Boolean value indicating whether to force the removal of the mapped printer. If set to true (the default is false), the printer connection is removed whether or not a user is connected.
bUpdateProfile
Optional. Boolean value. If set to true (the default is false), the change is saved in the user's profile.

Remarks

The RemovePrinterConnection method removes both Windows and MS-DOS based printer connections. If the printer was connected using the method AddPrinterConnection, strName must be the printer's local name. If the printer was connected using the AddWindowsPrinterConnection method or was added manually (using the Add Printer wizard), then strName must be the printer's UNC name.

Example

The following code disconnects a network printer.

[VBScript]
Set WshNetwork = WScript.CreateObject("WScript.Network")
PrinterPath = "\\printserv\DefaultPrinter"
WshNetwork.RemovePrinterConnection PrinterPath, true, true
[JScript]
var WshNetwork = WScript.CreateObject("WScript.Network");
var PrinterPath = "\\\\PRN-CORP1\\B41-4523-A";
WshNetwork.RemovePrinterConnection(PrinterPath, true, true);

See Also

WshNetwork Object | AddPrinterConnection Method | AddWindowsPrinterConnection Method | EnumPrinterConnections Method | SetDefaultPrinter Method


SetDefaultPrinter Method

Assigns a remote printer the role Default Printer.

object.SetDefaultPrinter(strPrinterName)

Arguments

object
WshNetwork object.
strPrinterName
String value indicating the remote printer's UNC name.

Remarks

The SetDefaultPrinter method fails when using a DOS-based printer connection. You cannot use the SetDefaultPrinter method to determine the name of the current default printer.

Example

The following code uses the AddWindowsPrinterConnection method to connect a network printer and set it as the default printer.

[VBScript]
Set WshNetwork = WScript.CreateObject("WScript.Network")
PrinterPath = "\\research\library1"
WshNetwork.AddWindowsPrinterConnection PrinterPath
WshNetwork.SetDefaultPrinter PrinterPath
[JScript]
var WshNetwork = WScript.CreateObject("WScript.Network");
var PrinterPath = "\\\\research\\library1";
WshNetwork.AddWindowsPrinterConnection(PrinterPath);
WshNetwork.SetDefaultPrinter(PrinterPath);

See Also

WshNetwork Object | AddPrinterConnection Method | AddWindowsPrinterConnection Method | EnumPrinterConnections Method | RemovePrinterConnection Method


WshRemote Object

WshController Object

Provides access to the remote script process.

Remarks

The WshRemote object allows you to remotely administer computer systems on a computer network. It represents an instance of a WSH script, i.e., a script file with one of the following extensions: .wsh, .wsf, .js, .vbs, .jse, .vbe, and so on. An instance of a running script is a process. You can run the process either on the local machine or on a remote machine. If you do not provide a network path, it will run locally. When a WSHRemote object is created (by using the CreateScript() method), the script is copied to the target computer system. Once there, the script does not begin executing immediately; it begins executing only when the WSHRemote method Execute is invoked. Through the WshRemote object interface, your script can manipulate other programs or scripts. Additionally, external applications can also manipulate remote scripts. The WshRemote object works asynchronously over DCOM.

Example

The following example demonstrates how the WshRemote object is used to start a remote script.

[VBScript]
Dim Controller, RemoteScript
Set Controller = WScript.CreateObject("WSHController")
Set RemoteScript = Controller.CreateScript("test.js", "remoteserver")
RemoteScript.Execute

Do While RemoteScript.Status <> 2
    WScript.Sleep 100
Loop
[JScript]
var Controller = WScript.CreateObject("WSHController");
var RemoteScript = Controller.CreateScript("test.js", "remoteserver");
RemoteScript.Execute();

while (RemoteScript.Status != 2) {
    WScript.Sleep(100);
}

Properties

Status Property | Error Property

Methods

Execute Method | Terminate Method

Events

Start Event | End Event | Error Event

See Also

WshController Object


Status Property

Status Property (WshScriptExec)

Provides status information about a script run with the Exec() method.

Object.Status

Arguments

Object
WshScriptExec object.

Remarks

The Status property is used when a program is run asynchronously.

Return Values

The Status property returns a value from an enumerated type.

WshRunning ( = 0)
The job is still running.
WshFinished ( = 1)
The job has completed.

Example

The following code runs calc.exe and echoes the final status to the screen.

[VBScript]
Dim WshShell, oExec
Set WshShell = CreateObject("WScript.Shell")

Set oExec = WshShell.Exec("calc")

Do While oExec.Status = 0
     WScript.Sleep 100
Loop

WScript.Echo oExec.Status
[JScript]
var WshShell = new ActiveXObject("WScript.Shell");
var oExec = WshShell.Exec("calc");

while (oExec.Status == 0)
{
     WScript.Sleep(100);
}

WScript.Echo(oExec.Status);

See Also

Exec Method | WshScriptExec Object


Error Property

Error Property (WshRemote)

Exposes the WshRemoteError object, which holds information about the error that caused the remote script to terminate prematurely.

Object.Error

Arguments

Object
WshRemote object.

Remarks

The Error property returns a WshRemoteError object.

Example

The following code demonstrates how the Error property of the WshRemote object exposes a WshRemoteError object, which exposes the line, character, and description of the error.

[VBScript]
Dim Controller, RemoteScript
Set Controller = WScript.CreateObject("WSHController")
Set RemoteScript = Controller.CreateScript("test.js", "remoteserver")
WScript.ConnectObject RemoteScript, "remote_"
RemoteScript.Execute

Do While RemoteScript.Status <> 2
    WScript.Sleep 100
Loop

Sub remote_Error
    Dim theError
    Set theError = RemoteScript.Error
    WScript.Echo "Error - Line: " & theError.Line & ", Char: " & theError.Character & vbCrLf & "Description: " & theError.Description
    WScript.Quit -1
End Sub
[JScript]
var Controller = WScript.CreateObject("WSHController");
var RemoteScript = Controller.CreateScript("test.js", "remoteserver");
WScript.ConnectObject(RemoteScript, "remote_");
RemoteScript.Execute();

while (RemoteScript.Status != 2) {
    WScript.Sleep(100);
}

function remote_Error()
{
    var theError = RemoteScript.Error;
    WScript.Echo("Error - Line: " + theError.Line + ", Char: " + theError.Character + "\nDescription: " + theError.Description);    WScript.Quit(-1);
}

See Also

WshController Object | WshRemote Object | WshRemoteError Object | Status Property | Execute Method | Terminate Method | Start Event | End Event | Error Event


Execute Method

Starts execution of a remote script object.

object.Execute

Parameters

object
WshRemote Object

Remarks

The Start event of the WshRemote object is fired when the script starts executing. Do not confuse the Execute method with the Exec method (of the WScript object).

Example

The following example demonstrates how the Execute method is used to create a WshRemote object (start an instance of a remote script).

[VBScript]
Dim Controller, RemoteScript
Set Controller = WScript.CreateObject("WSHController")
Set RemoteScript = Controller.CreateScript("remote1.js")
RemoteScript.Execute

Do While RemoteScript.Status <> 2
    WScript.Sleep 100
Loop
[JScript]
var Controller = WScript.CreateObject("WSHController");
var RemoteScript = Controller.CreateScript("remote1.js");
RemoteScript.Execute();

while (RemoteScript.Status != 2) {
    WScript.Sleep(100);
}

See Also

WshController Object | WshRemote Object | Status Property | Error Property | Terminate Method | Start Event | End Event


Terminate Method

Terminate Method (WshScriptExec)

Instructs the script engine to end the process started by the Exec method.

object.Terminate

Arguments

object
WshScriptExec object.

Remarks

The Terminate method does not return a value. Use the Terminate method only as a last resort since some applications do not clean up properly. As a general rule, let the process run its course and end on its own. The Terminate method attempts to end a process using the WM_CLOSE message. If that does not work, it kills the process immediately without going through the normal shutdown procedure.

Example

The following JScript example demonstrates how to use the Terminate method to stop a running script.

var aScript = WScript.Exec("%comspec% /c myScript.js");
aScript.Terminate();

See Also

WshScriptExec Object


Start Event

Event that is fired when the remote script begins executing.

Object_Start

Parameters

object
WshRemote object.

Remarks

The Start event is fired when the Execute method is called.

Example

var WshController = new ActiveXObject("WSHController");
var RemoteProc = WshController.CreateScript("foo.wsf", "remotemachine");
WScript.ConnectObject(RemoteProc, "RemoteProc_");
var Done = false;
RemoteProc.Execute();
while (!Done)
   WScript.Sleep(100);

function RemoteProc_End()
{
   WScript.Echo("The process has ended");
   Done = true;
}

function RemoteProc_Error()
{
   WScript.Echo("An error has occurred: " + RemoteProc.Error.Description);
   Done = true;
}

function RemoteProc_Start()
{
   WScript.Echo("The process has started");
}

See Also

WshController Object | WshRemote Object | Status Property | Error Property | Execute Method | Terminate Method | End Event | Error Event


End Event

Event that is fired when the remote script completes.

Object_end

Parameters

object
WshRemote object.

Remarks

The End event is fired when the remote script object has finished executing. This can be when the remote script object has terminated normally, timed out, or terminated due to an error.

Example

var WshController = new ActiveXObject("WSHController");
var RemoteProc = WshController.CreateScript("foo.wsf", "remotemachine");
WScript.ConnectObject(RemoteProc, "RemoteProc_");
var Done = false;
RemoteProc.Execute();
while (!Done)
   WScript.Sleep(100);

function RemoteProc_End()
{
   WScript.Echo("The process has ended");
   Done = true;
}

function RemoteProc_Error()
{
   WScript.Echo("An error has occurred: " + RemoteProc.Error.Description);
   Done = true;
}

function RemoteProc_Start()
{
   WScript.Echo("The process has started");
}

See Also

WshController Object | WshRemote Object | Status Property | Error Property | Execute Method | Terminate Method | Start Event | Error Event


Error Event

Event that is fired when an error occurs in the remote script.

Object_Error

Parameters

object
WshRemote object.

Remarks

The remote script object fires the Error event when the remote script terminates prematurely. The Error property contains the WshRemoteError object (which holds information about the error that caused the remote script to terminate prematurely).

Example

var WshController = new ActiveXObject("WSHController");
var RemoteProc = WshController.CreateScript("foo.wsf", "remotemachine");
WScript.ConnectObject(RemoteProc, "RemoteProc_");
var Done = false;
RemoteProc.Execute();
while (!Done)
   WScript.Sleep(100);

function RemoteProc_End()
{
   WScript.Echo("The process has ended");
   Done = true;
}

function RemoteProc_Error()
{
   WScript.Echo("An error has occurred: " + RemoteProc.Error.Description);
   Done = true;
}

function RemoteProc_Start()
{
   WScript.Echo("The process has started");
}

See Also

WshController Object | WshRemote Object | WshRemoteError Object | Status Property | Error Property | Execute Method | Terminate Method | Start Event | End Event


WshRemoteError Object

Error PropertyWshRemote Object

Provides access to the error information available when a remote script (a WshRemote object) terminates as a result of a script error.

Remarks

The WshRemoteError object is returned by the Error property of the WshRemote object.

Example

The following example demonstrates how the WshRemoteError object is used to show where the error occurred in the script along with a description of the error.

[VBScript]
Dim Controller, RemoteScript
Set Controller = WScript.CreateObject("WSHController")
Set RemoteScript = Controller.CreateScript("test.js", "remoteserver")
WScript.ConnectObject RemoteScript, "remote_"
RemoteScript.Execute

Do While RemoteScript.Status <> 2
    WScript.Sleep 100
Loop

WScript.DisconnectObject RemoteScript

Sub remote_Error
    Dim theError
    Set theError = RemoteScript.Error
    WScript.Echo "Error " & theError.Number & " - Line: " & theError.Line & ", Char: " & theError.Character & vbCrLf & "Description: " & theError.Description
    WScript.Quit -1
End Sub
[JScript]
var Controller = WScript.CreateObject("WSHController");
var RemoteScript = Controller.CreateScript("test.js", "remoteserver");
WScript.ConnectObject(RemoteScript, "remote_");
RemoteScript.Execute();

while (RemoteScript.Status != 2) {
    WScript.Sleep(100);
}

WScript.DisconnectObject(RemoteScript);

function remote_Error()
{
    var theError = RemoteScript.Error;
    WScript.Echo("Error " + theError.Number + " - Line: " + theError.Line + ", Char: " + theError.Character + "\nDescription: " + theError.Description);
    WScript.Quit(-1);
}

Properties

Description Property | Line Property | Character Property | SourceText Property | Source Property | Number Property

See Also

WshRemote Object


Description Property

Error Event

Event that is fired when an error occurs in the remote script.

Object_Error

Parameters

object
WshRemote object.

Remarks

The remote script object fires the Error event when the remote script terminates prematurely. The Error property contains the WshRemoteError object (which holds information about the error that caused the remote script to terminate prematurely).

Example

var WshController = new ActiveXObject("WSHController");
var RemoteProc = WshController.CreateScript("foo.wsf", "remotemachine");
WScript.ConnectObject(RemoteProc, "RemoteProc_");
var Done = false;
RemoteProc.Execute();
while (!Done)
   WScript.Sleep(100);

function RemoteProc_End()
{
   WScript.Echo("The process has ended");
   Done = true;
}

function RemoteProc_Error()
{
   WScript.Echo("An error has occurred: " + RemoteProc.Error.Description);
   Done = true;
}

function RemoteProc_Start()
{
   WScript.Echo("The process has started");
}

See Also

WshController Object | WshRemote Object | WshRemoteError Object | Status Property | Error Property | Execute Method | Terminate Method | Start Event | End Event


Line Property

Line Property (WshRemoteError)

Identifies the line in a script that contains an error.

Object.Line

Arguments

Object
WshRemoteError object.

Remarks

The Line property returns an unsigned long integer.

Notice that some errors do not occur on a particular line. For example, consider the error Expected End If. In this case, there is no line (a line of code is missing). In such a case, the Line property returns zero (0).

Example

The following JScript code demonstrates how the WshRemoteError object exposes the line in which the error occurred.

[VBScript]
Dim Controller, RemoteScript
Set Controller = WScript.CreateObject("WSHController")
Set RemoteScript = Controller.CreateScript("test.js", "remoteserver")
WScript.ConnectObject RemoteScript, "remote_"
RemoteScript.Execute

Do While RemoteScript.Status <> 2
    WScript.Sleep 100
Loop

Sub remote_Error
    Dim theError
    Set theError = RemoteScript.Error
    WScript.Echo "Error - Line: " & theError.Line & ", Char: " & theError.Character & vbCrLf & "Description: " & theError.Description
    WScript.Quit -1
End Sub
[JScript]
var Controller = WScript.CreateObject("WSHController");
var RemoteScript = Controller.CreateScript("test.js", "remoteserver");
WScript.ConnectObject(RemoteScript, "remote_");
RemoteScript.Execute();

while (RemoteScript.Status != 2) {
    WScript.Sleep(100);
}

function remote_Error()
{
    var theError = RemoteScript.Error;
    WScript.Echo("Error - Line: " + theError.Line + ", Char: " + theError.Character + "\nDescription: " + theError.Description);
    WScript.Quit(-1);
}

See Also

WshRemote Object | WshRemoteError Object | Character Property | Description Property | Line Property | SourceText Property | Number Property | Source Property


Character Property

Reports the specific character in a line of code that contains an error.

Object.Character

Arguments

Object
WshRemoteError object.

Remarks

The Character property returns a signed long integer.

Some errors are not associated with a particular character position. For example, consider the error Expected End If. In this case, there is no line (a line of code is missing). In such a case, the Character property returns zero (0).

The character position is based on an offset of one (1) (the first character in a line resides at position one).

Example

The following JScript code demonstrates how the WshRemoteError object exposes the character in the line of code that contained the error.

[VBScript]
Dim Controller, RemoteScript
Set Controller = WScript.CreateObject("WSHController")
Set RemoteScript = Controller.CreateScript("test.js", "remoteserver")
WScript.ConnectObject RemoteScript, "remote_"
RemoteScript.Execute

Do While RemoteScript.Status <> 2
    WScript.Sleep 100
Loop

Sub remote_Error
    Dim theError
    Set theError = RemoteScript.Error
    WScript.Echo "Error - Line: " & theError.Line & ", Char: " & theError.Character & vbCrLf & "Description: " & theError.Description
    WScript.Quit -1
End Sub
[JScript]
var Controller = WScript.CreateObject("WSHController");
var RemoteScript = Controller.CreateScript("test.js", "remoteserver");
WScript.ConnectObject(RemoteScript, "remote_");
RemoteScript.Execute();

while (RemoteScript.Status != 2) {
    WScript.Sleep(100);
}

function remote_Error()
{
    var theError = RemoteScript.Error;
    WScript.Echo("Error - Line: " + theError.Line + ", Char: " + theError.Character + "\nDescription: " + theError.Description);
    WScript.Quit(-1);
}

See Also

WshRemote Object | WshRemoteError Object | Line Property| Description Property | SourceText Property | Number Property | Source Property


SourceText Property

Contains the line of source code that caused an error.

Object.SourceText

Arguments

Object
WshRemoteError object.

Remarks

The SourceText property returns a string.

It is not always possible to obtain the source text. If that is the case, the SourceText property returns an empty string.

Example

The following JScript code demonstrates how the WshRemoteError object exposes the line of source code that caused an error.

[VBScript]
Dim Controller, RemoteScript
Set Controller = WScript.CreateObject("WSHController")
Set RemoteScript = Controller.CreateScript("test.js", "remoteserver")
WScript.ConnectObject RemoteScript, "remote_"
RemoteScript.Execute

Do While RemoteScript.Status <> 2
    WScript.Sleep 100
Loop

Sub remote_Error
    Dim theError
    Set theError = RemoteScript.Error
    WScript.Echo "Error - Line: " & theError.Line & ", Char: " & theError.Character & vbCrLf & "Description: " & theError.Description & vbCrLf & "Source Text: " & theError.SourceText
    WScript.Quit -1
End Sub
[JScript]
var Controller = WScript.CreateObject("WSHController");
var RemoteScript = Controller.CreateScript("test.js", "remoteserver");
WScript.ConnectObject(RemoteScript, "remote_");
RemoteScript.Execute();

while (RemoteScript.Status != 2) {
    WScript.Sleep(100);
}

function remote_Error()
{
    var theError = RemoteScript.Error;
    WScript.Echo("Error - Line: " + theError.Line + ", Char: " + theError.Character + "\nDescription: " + theError.Description + "\nSource Text: "_+ theError.SourceText);
    WScript.Quit(-1);
}

See Also

WshRemote Object | WshRemoteError Object | Description Property | Line Property | Character Property| Number Property | Source Property


Source Property

Identifies the COM object responsible for causing the script error.

Object.Source

Arguments

Object
WshRemoteError object.

Remarks

The Source property returns a string.

Example

The following JScript code demonstrates how the WshRemoteError object exposes the COM object responsible for causing the script error.

[VBScript]
Dim Controller, RemoteScript
Set Controller = WScript.CreateObject("WSHController")
Set RemoteScript = Controller.CreateScript("test.js", "remoteserver")
WScript.ConnectObject RemoteScript, "remote_"
RemoteScript.Execute

Do While RemoteScript.Status <> 2
    WScript.Sleep 100
Loop

Sub remote_Error
    Dim theError
    Set theError = RemoteScript.Error
    WScript.Echo "Error - Line: " & theError.Line & ", Char: " & theError.Character & vbCrLf & "Description: " & theError.Description & vbCrLf & "Source: " & theError.Source
    WScript.Quit -1
End Sub
[JScript]
var Controller = WScript.CreateObject("WSHController");
var RemoteScript = Controller.CreateScript("test.js", "remoteserver");
WScript.ConnectObject(RemoteScript, "remote_");
RemoteScript.Execute();

while (RemoteScript.Status != 2) {
    WScript.Sleep(100);
}

function remote_Error()
{
    var theError = RemoteScript.Error;
    WScript.Echo("Error - Line: " + theError.Line + ", Char: " + theError.Character + "\nDescription: " + theError.Description + "\nSource: " + theError.Source);
    WScript.Quit(-1);
}

See Also

WshRemote Object | WshRemoteError Object | Description Property | Line Property | Character Property| SourceText Property | Number Property


Number Property

Reports the error number representing a script error.

Object.Number

Arguments

Object
WshRemoteError object.

Remarks

That Number property returns an unsigned long integer.

Example

The following JScript code demonstrates how the WshRemoteError object exposes the error number.

[VBScript]
Dim Controller, RemoteScript
Set Controller = WScript.CreateObject("WSHController")
Set RemoteScript = Controller.CreateScript("test.js", "remoteserver")
WScript.ConnectObject RemoteScript, "remote_"
RemoteScript.Execute

Do While RemoteScript.Status <> 2
    WScript.Sleep 100
Loop

Sub remote_Error
    Dim theError
    Set theError = RemoteScript.Error
    WScript.Echo "Error " & theError.Number & " - Line: " & theError.Line & ", Char: " & theError.Character & vbCrLf & "Description: " & theError.Description
    WScript.Quit -1
End Sub
[JScript]
var Controller = WScript.CreateObject("WSHController");
var RemoteScript = Controller.CreateScript("test.js", "remoteserver");
WScript.ConnectObject(RemoteScript, "remote_");
RemoteScript.Execute();

while (RemoteScript.Status != 2) {
    WScript.Sleep(100);
}

function remote_Error()
{
    var theError = RemoteScript.Error;
    WScript.Echo("Error " + theError.Number + " - Line: " + theError.Line + ", Char: " + theError.Character + "\nDescription: " + theError.Description);
    WScript.Quit(-1);
}

See Also

WshRemote Object | WshRemoteError Object | Description Property | Line Property | Character Property| SourceText Property| Source Property


WshScriptExec Object

Exec MethodWshShell Object

Provides status information about a script run with Exec along with access to the StdIn, StdOut, and StdErr streams.

Remarks

The WshScriptExec object is returned by the Exec method of the WshShell object. The Exec method returns the WshScriptExec object either once the script or program has finished executing, or before the script or program begins executing.

Example

The following code runs calc.exe and echoes the final status to the screen.

[VBScript]
Dim WshShell, oExec
Set WshShell = CreateObject("WScript.Shell")

Set oExec = WshShell.Exec("calc")

Do While oExec.Status = 0
     WScript.Sleep 100
Loop

WScript.Echo oExec.Status
[JScript]
var WshShell = new ActiveXObject("WScript.Shell");
var oExec = WshShell.Exec("calc");

while (oExec.Status == 0)
{
     WScript.Sleep(100);
}

WScript.Echo(oExec.Status);

Properties

Status Property | StdOut Property | StdIn Property | StdErr Property

Methods

Terminate Method

See Also

WScript Object | Exec Method


StdIn Property

StdIn Property (WshScriptExec)

Exposes the stdin input stream of the Exec object.

Object.StdIn

Arguments

Object
WshScriptExec object.

Remarks

Use the StdIn property to pass data to a process started using Exec.

Example

The following code starts a batch file and waits for the user input prompt. After entering the needed data through the StdIn stream, the batch file will be able to complete.

[VBScript]
Dim WshShell, oExec, input
Set WshShell = CreateObject("WScript.Shell")
Set oExec    = WshShell.Exec("test.bat")
input = ""

Do While True

     If Not oExec.StdOut.AtEndOfStream Then
          input = input & oExec.StdOut.Read(1)
          If InStr(input, "Press any key") <> 0 Then Exit Do
     End If
     WScript.Sleep 100
Loop

oExec.StdIn.Write VbCrLf

Do While oExec.Status <> 1
     WScript.Sleep 100
Loop
[JScript]
var WshShell = new ActiveXObject("WScript.Shell");
var oExec    = WshShell.Exec("test.bat");
var input = "";

while (true)
{
     if (!oExec.StdOut.AtEndOfStream)
     {
          input += oExec.StdOut.Read(1);
          if (input.indexOf("Press any key") != -1)
               break;
     }
     WScript.Sleep(100);
}

oExec.StdIn.Write("\n");

while (oExec.Status != 1)
     WScript.Sleep(100);

See Also

WshScriptExec Object | StdIn Property | StdErr Property


StdOut Property

StdOut Property (WshScriptExec)

Exposes the write-only stdout output stream of the Exec object.

Object.StdOut

Arguments

Object
WshScriptExec object.

Remarks

The StdOut property contains a read-only copy of any information the script may have sent to the standard output.

Example

The following code starts a batch file and waits for the user input prompt. After entering the needed data through the StdIn stream, the batch file will be able to complete.

[VBScript]
Dim WshShell, oExec, input
Set WshShell = CreateObject("WScript.Shell")
Set oExec    = WshShell.Exec("test.bat")
input = ""

Do While True

     If Not oExec.StdOut.AtEndOfStream Then
          input = input & oExec.StdOut.Read(1)
          If InStr(input, "Press any key") <> 0 Then Exit Do
     End If
     WScript.Sleep 100
Loop

oExec.StdIn.Write VbCrLf

Do While oExec.Status <> 1
     WScript.Sleep 100
Loop
[JScript]
var WshShell = new ActiveXObject("WScript.Shell");
var oExec    = WshShell.Exec("test.bat");
var input = "";

while (true)
{
     if (!oExec.StdOut.AtEndOfStream)
     {
          input += oExec.StdOut.Read(1);
          if (input.indexOf("Press any key") != -1)
               break;
     }
     WScript.Sleep(100);
}

oExec.StdIn.Write("\n");

while (oExec.Status != 1)
     WScript.Sleep(100);

See Also

WshScriptExec Object | StdIn Property | StdErr Property


StdErr Property

StdErr Property (WshScriptExec)

Provides access to the stderr output stream of the Exec object.

Object.StdErr

Arguments

Object
WshScriptExec object.

Remarks

Use the StdErr property to retrieve data sent to the stderr stream from a process started with Exec.

Example

The following code demonstrates the StdErr object by attempting to execute a non-existent command and displaying the results.

[VBScript]
Dim WshShell, oExec
Set WshShell = CreateObject("WScript.Shell")
Set oExec    = WshShell.Exec("%comspec% /c dire")

Function ReadAllFromAny(oExec)

     If Not oExec.StdOut.AtEndOfStream Then
          ReadAllFromAny = oExec.StdOut.ReadAll
          Exit Function
     End If

     If Not oExec.StdErr.AtEndOfStream Then
          ReadAllFromAny = "STDERR: " + oExec.StdErr.ReadAll
          Exit Function
     End If

     ReadAllFromAny = -1
End Function

Dim allInput, tryCount

allInput = ""
tryCount = 0

Do While True

     Dim input
     input = ReadAllFromAny(oExec)

     If -1 = input Then
          If tryCount > 10 And oExec.Status = 1 Then
               Exit Do
          End If
          tryCount = tryCount + 1
          WScript.Sleep 100
     Else
          allInput = allInput & input
          tryCount = 0
     End If
Loop

WScript.Echo allInput
[JScript]
var WshShell = new ActiveXObject("WScript.Shell");
var oExec    = WshShell.Exec("%comspec% /c dire");

function ReadAllFromAny(oExec)
{
     if (!oExec.StdOut.AtEndOfStream)
          return oExec.StdOut.ReadAll();

     if (!oExec.StdErr.AtEndOfStream)
          return "STDERR: " + oExec.StdErr.ReadAll();

     return -1;
}

var allInput = "";
var tryCount = 0;

while (true)
{
     var input = ReadAllFromAny(oExec);
     if (-1 == input)
     {
          if (tryCount++ > 10 && oExec.Status == 1)
               break;
          WScript.Sleep(100);
     }
     else
     {
          allInput += input;
          tryCount = 0;
     }
}

WScript.Echo(allInput);

See Also

WshScriptExec Object | StdIn Property | StdOut Property


WshShortcut Object

WshShell Object

Allows you to create a shortcut programmatically.

Example

The following example demonstrates the creation of a shortcut to the script being run:

<package>
   <job id="vbs">
      <script language="VBScript">
         set WshShell = WScript.CreateObject("WScript.Shell")
         strDesktop = WshShell.SpecialFolders("Desktop")
         set oShellLink = WshShell.CreateShortcut(strDesktop & "\Shortcut Script.lnk")
         oShellLink.TargetPath = WScript.ScriptFullName
         oShellLink.WindowStyle = 1
         oShellLink.Hotkey = "CTRL+SHIFT+F"
         oShellLink.IconLocation = "notepad.exe, 0"
         oShellLink.Description = "Shortcut Script"
         oShellLink.WorkingDirectory = strDesktop
         oShellLink.Save
      </script>
   </job>

   <job id="js">
      <script language="JScript">
         var WshShell = WScript.CreateObject("WScript.Shell");
         strDesktop = WshShell.SpecialFolders("Desktop");
         var oShellLink = WshShell.CreateShortcut(strDesktop + "\\Shortcut Script.lnk");
         oShellLink.TargetPath = WScript.ScriptFullName;
         oShellLink.WindowStyle = 1;
         oShellLink.Hotkey = "CTRL+SHIFT+F";
         oShellLink.IconLocation = "notepad.exe, 0";
         oShellLink.Description = "Shortcut Script";
         oShellLink.WorkingDirectory = strDesktop;
         oShellLink.Save();
      </script>
   </job>
</package>

Properties

Arguments Property | Description Property | FullName Property (WshShortcut Object) | Hotkey Property | IconLocation Property | TargetPath Property | WindowStyle Property | WorkingDirectory Property

Methods

Save Method

See Also

Running Your Scripts | CreateShortcut Method


Description Property

Returns a shortcut's description.

object.Description

Arguments

object
WshShortcut object.

Remarks

The Description property contains a string value describing a shortcut.

Example

The following example demonstrates the use of the Description Property.

<package>
   <job id="vbs">
      <script language="VBScript">
         set WshShell = WScript.CreateObject("WScript.Shell")
         strDesktop = WshShell.SpecialFolders("Desktop")
         set oShellLink = WshShell.CreateShortcut(strDesktop & "\Shortcut Script.lnk")
         oShellLink.TargetPath = WScript.ScriptFullName
         oShellLink.WindowStyle = 1
         oShellLink.Hotkey = "Ctrl+Alt+e"
         oShellLink.IconLocation = "notepad.exe, 0"
         oShellLink.Description = "Shortcut Script"
         oShellLink.WorkingDirectory = strDesktop
         oShellLink.Save
         set oUrlLink = WshShell.CreateShortcut(strDesktop & "\Microsoft Web Site.url")
         oUrlLink.TargetPath = "http://www.microsoft.com"
         oUrlLink.Save
      </script>
   </job>

   <job id="js">
      <script language="JScript">
         var WshShell = WScript.CreateObject("WScript.Shell");
         strDesktop = WshShell.SpecialFolders("Desktop");
         var oShellLink = WshShell.CreateShortcut(strDesktop + "\\Shortcut Script.lnk");
         oShellLink.TargetPath = WScript.ScriptFullName;
         oShellLink.WindowStyle = 1;
         oShellLink.Hotkey = "Ctrl+Alt+e";
         oShellLink.IconLocation = "notepad.exe, 0";
         oShellLink.Description = "Shortcut Script";
         oShellLink.WorkingDirectory = strDesktop;
         oShellLink.Save();
         var oUrlLink = WshShell.CreateShortcut(strDesktop + "\\Microsoft Web Site.url");
         oUrlLink.TargetPath = "http://www.microsoft.com";
         oUrlLink.Save();
      </script>
   </job>
</package>

See Also

Running Your Scripts | WshShortcut Object


FullName Property

FullName Property (WshShortcut Object)

Returns the fully qualified path of the shortcut object's target.

object.FullName

Arguments

object
WshShortcut object.

Remarks

The FullName property contains a read-only string value indicating the fully qualified path to the shortcut's target.

Example

The following code retrieves the fully qualified path of a shortcut.

[VBScript]
set WshShell = WScript.CreateObject("WScript.Shell")
strDesktop = WshShell.SpecialFolders("Desktop")
set oShellLink = WshShell.CreateShortcut(strDesktop & "\Shortcut Script.lnk")
oShellLink.TargetPath = WScript.ScriptFullName
oShellLink.WindowStyle = 1
oShellLink.Hotkey = "CTRL+SHIFT+F"
oShellLink.IconLocation = "notepad.exe, 0"
oShellLink.Description = "Shortcut Script"
oShellLink.WorkingDirectory = strDesktop
oShellLink.Save
WScript.Echo oShellLink.FullName
[JScript]
var WshShell = new ActiveXObject("WScript.Shell");
strDesktop = WshShell.SpecialFolders("Desktop");
var oShellLink = WshShell.CreateShortcut(strDesktop + "\\Shortcut Script.lnk");
oShellLink.TargetPath = WScript.ScriptFullName;
oShellLink.WindowStyle = 1;
oShellLink.Hotkey = "CTRL+SHIFT+F";
oShellLink.IconLocation = "notepad.exe, 0";
oShellLink.Description = "Shortcut Script";
oShellLink.WorkingDirectory = strDesktop;
oShellLink.Save();
WScript.Echo(oShellLink.FullName);

See Also

Path Property | WScript Object | WshShortcut Object | WshUrlShortcut Object


Hotkey Property

Assigns a key-combination to a shortcut, or identifies the key-combination assigned to a shortcut.

object.Hotkey = strHotkey

Arguments

object
WshShortcut object.
strHotkey
A string representing the key-combination to assign to the shortcut.

Syntax

The syntax of strHotkey is:

[KeyModifier]KeyName
KeyModifier
Can be any one of the following: ALT+, CTRL+, SHIFT+, EXT+.

Note EXT+ means "Extended key." — it appears here in case a new type of SHIFT-key is added to the character set in the future.

KeyName
a ... z, 0 ... 9, F1 … F12, ...

The KeyName is not case-sensitive.

Remarks

A hotkey is a combination of keys that starts a shortcut when all associated keys are held down at the same time.

  • Hotkeys can be used to start shortcuts located on your system's desktop and in the Windows Start menu.
    Note Another name for a hotkey is a Keyboard Shortcut.

In Windows 2000, valid Hotkeys always begin with CTRL + ALT.

Example

The following example demonstrates the use of the HotKey property.

<package>
   <job id="vbs">
      <script language="VBScript">
         set WshShell = WScript.CreateObject("WScript.Shell")
         strDesktop = WshShell.SpecialFolders("Desktop")
         set oShellLink = WshShell.CreateShortcut(strDesktop & "\Shortcut Script.lnk")
         oShellLink.TargetPath = WScript.ScriptFullName
         oShellLink.WindowStyle = 1
         oShellLink.Hotkey = "Ctrl+Alt+e"
         oShellLink.IconLocation = "notepad.exe, 0"
         oShellLink.Description = "Shortcut Script"
         oShellLink.WorkingDirectory = strDesktop
         oShellLink.Save
      </script>
   </job>

   <job id="js">
      <script language="JScript">
         var WshShell = WScript.CreateObject("WScript.Shell");
         strDesktop = WshShell.SpecialFolders("Desktop");
         var oShellLink = WshShell.CreateShortcut(strDesktop + "\\Shortcut Script.lnk");
         oShellLink.TargetPath = WScript.ScriptFullName;
         oShellLink.WindowStyle = 1;
         oShellLink.Hotkey = "Ctrl+Alt+e";
         oShellLink.IconLocation = "notepad.exe, 0";
         oShellLink.Description = "Shortcut Script";
         oShellLink.WorkingDirectory = strDesktop;
         oShellLink.Save();
      </script>
   </job>
</package>

See Also

Running Your Scripts | Running Your Scripts | WshSpecialFolders Object | WshShortcut Object


IconLocation Property

Assigns an icon to a shortcut, or identifies the icon assigned to a shortcut.

object.IconLocation = strIconLocation

Arguments

object
WshShortcut object.
strIconLocation
A string that locates the icon. The string should contain a fully qualified path and an index associated with the icon. See example for more details.

Remarks

String.

Example

The following example demonstrates the use of the IconLocation property.

<package>
   <job id="vbs">
      <script language="VBScript">
         set WshShell = WScript.CreateObject("WScript.Shell")
         strDesktop = WshShell.SpecialFolders("Desktop")
         set oShellLink = WshShell.CreateShortcut(strDesktop & "\Shortcut Script.lnk")
         oShellLink.TargetPath = WScript.ScriptFullName
         oShellLink.WindowStyle = 1
         oShellLink.Hotkey = "Ctrl+Alt+e"
         oShellLink.IconLocation = "notepad.exe, 0"  'Zero is the index
         oShellLink.Description = "Shortcut Script"
         oShellLink.WorkingDirectory = strDesktop
         oShellLink.Save
      </script>
   </job>

   <job id="js">
      <script language="JScript">
         var WshShell = WScript.CreateObject("WScript.Shell");
         strDesktop = WshShell.SpecialFolders("Desktop");
         var oShellLink = WshShell.CreateShortcut(strDesktop + "\\Shortcut Script.lnk");
         oShellLink.TargetPath = WScript.ScriptFullName;
         oShellLink.WindowStyle = 1;
         oShellLink.Hotkey = "Ctrl+Alt+e";
         oShellLink.IconLocation = "notepad.exe, 0";  //Zero is the index
         oShellLink.Description = "Shortcut Script";
         oShellLink.WorkingDirectory = strDesktop;
         oShellLink.Save();
      </script>
   </job>
</package>

See Also

Running Your Scripts | WshShortcut Object


TargetPath Property

The path to the shortcut's executable.

object.TargetPath

Arguments

object
WshShortcut or WshUrlShortcut object.

Remarks

String.

This property is for the shortcut's target path only. Any arguments to the shortcut must be placed in the Argument's property.

Example

The following example demonstrates the use of the TargetPath property:

<package>
   <job id="vbs">
      <script language="VBScript">
         set WshShell = WScript.CreateObject("WScript.Shell")
         strDesktop = WshShell.SpecialFolders("Desktop")
         set oShellLink = WshShell.CreateShortcut(strDesktop & "\Shortcut Script.lnk")
         oShellLink.TargetPath = WScript.ScriptFullName
         oShellLink.WindowStyle = 1
         oShellLink.Hotkey = "Ctrl+Alt+e"
         oShellLink.IconLocation = "notepad.exe, 0"
         oShellLink.Description = "Shortcut Script"
         oShellLink.WorkingDirectory = strDesktop
         oShellLink.Save
         set oUrlLink = WshShell.CreateShortcut(strDesktop & "\Microsoft Web Site.url")
         oUrlLink.TargetPath = "http://www.microsoft.com"
         oUrlLink.Save
      </script>
   </job>

   <job id="js">
      <script language="JScript">
         var WshShell = WScript.CreateObject("WScript.Shell");
         strDesktop = WshShell.SpecialFolders("Desktop");
         var oShellLink = WshShell.CreateShortcut(strDesktop + "\\Shortcut Script.lnk");
         oShellLink.TargetPath = WScript.ScriptFullName;
         oShellLink.WindowStyle = 1;
         oShellLink.Hotkey = "Ctrl+Alt+e";
         oShellLink.IconLocation = "notepad.exe, 0";
         oShellLink.Description = "Shortcut Script";
         oShellLink.WorkingDirectory = strDesktop;
         oShellLink.Save();
         var oUrlLink = WshShell.CreateShortcut(strDesktop + "\\Microsoft Web Site.url");
         oUrlLink.TargetPath = "http://www.microsoft.com";
         oUrlLink.Save();
      </script>
   </job>
</package>

See Also

Running Your Scripts | WshShortcut Object | WshUrlShortcut Object


WindowStyle Property

Assigns a window style to a shortcut, or identifies the type of window style used by a shortcut.

object.WindowStyle = intWindowStyle

Arguments

object
WshShortcut object.
intWindowStyle
Sets the window style for the program being run.

Remarks

The WindowStyle property returns an integer.

The following table lists the available settings for intWindowStyle.

intWindowStyle | Description
1 | Activates and displays a window. If the window is minimized or maximized, the system restores it to its original size and position.
3 | Activates the window and displays it as a maximized window.
7 | Minimizes the window and activates the next top-level window.

Example

The following example demonstrates the use of the WindowStyle property:

<package>
   <job id="vbs">
      <script language="VBScript">
         set WshShell = WScript.CreateObject("WScript.Shell")
         strDesktop = WshShell.SpecialFolders("Desktop")
         set oShellLink = WshShell.CreateShortcut(strDesktop & "\Shortcut Script.lnk")
         oShellLink.TargetPath = WScript.ScriptFullName
         oShellLink.WindowStyle = 1
         oShellLink.Hotkey = "Ctrl+Alt+e"
         oShellLink.IconLocation = "notepad.exe, 0"
         oShellLink.Description = "Shortcut Script"
         oShellLink.WorkingDirectory = strDesktop
         oShellLink.Save
         set oUrlLink = WshShell.CreateShortcut(strDesktop & "\Microsoft Web Site.url")
         oUrlLink.TargetPath = "http://www.microsoft.com"
         oUrlLink.Save
      </script>
   </job>

   <job id="js">
      <script language="JScript">
         var WshShell = WScript.CreateObject("WScript.Shell");
         strDesktop = WshShell.SpecialFolders("Desktop");
         var oShellLink = WshShell.CreateShortcut(strDesktop + "\\Shortcut Script.lnk");
         oShellLink.TargetPath = WScript.ScriptFullName;
         oShellLink.WindowStyle = 1;
         oShellLink.Hotkey = "Ctrl+Alt+e";
         oShellLink.IconLocation = "notepad.exe, 0";
         oShellLink.Description = "Shortcut Script";
         oShellLink.WorkingDirectory = strDesktop;
         oShellLink.Save();
         var oUrlLink = WshShell.CreateShortcut(strDesktop + "\\Microsoft Web Site.url");
         oUrlLink.TargetPath = "http://www.microsoft.com";
         oUrlLink.Save();
      </script>
   </job>
</package>

See Also

Running Your Scripts | WshShortcut Object


WorkingDirectory Property

Assign a working directory to a shortcut, or identifies the working directory used by a shortcut.

object.WorkingDirectory = strWorkingDirectory

Arguments

object
WshShortcut object.
strWorkingDirectory
String. Directory in which the shortcut starts.

Remarks

String.

Example

The following example demonstrates the use of the WorkingDirectory property:

<package>
   <job id="vbs">
      <script language="VBScript">
         set WshShell = WScript.CreateObject("WScript.Shell")
         strDesktop = WshShell.SpecialFolders("Desktop")
         set oShellLink = WshShell.CreateShortcut(strDesktop & "\Shortcut Script.lnk")
         oShellLink.TargetPath = WScript.ScriptFullName
         oShellLink.WindowStyle = 1
         oShellLink.Hotkey = "Ctrl+Alt+e"
         oShellLink.IconLocation = "notepad.exe, 0"
         oShellLink.Description = "Shortcut Script"
         oShellLink.WorkingDirectory = strDesktop
         oShellLink.Save
         set oUrlLink = WshShell.CreateShortcut(strDesktop & "\Microsoft Web Site.url")
         oUrlLink.TargetPath = "http://www.microsoft.com"
         oUrlLink.Save
      </script>
   </job>

   <job id="js">
      <script language="JScript">
         var WshShell = WScript.CreateObject("WScript.Shell");
         strDesktop = WshShell.SpecialFolders("Desktop");
         var oShellLink = WshShell.CreateShortcut(strDesktop + "\\Shortcut Script.lnk");
         oShellLink.TargetPath = WScript.ScriptFullName;
         oShellLink.WindowStyle = 1;
         oShellLink.Hotkey = "Ctrl+Alt+e";
         oShellLink.IconLocation = "notepad.exe, 0";
         oShellLink.Description = "Shortcut Script";
         oShellLink.WorkingDirectory = strDesktop;
         oShellLink.Save();
         var oUrlLink = WshShell.CreateShortcut(strDesktop + "\\Microsoft Web Site.url");
         oUrlLink.TargetPath = "http://www.microsoft.com";
         oUrlLink.Save();
      </script>
   </job>
</package>

See Also

Running Your Scripts


Save Method

Saves a shortcut object to disk.

object.Save

Arguments

object
WshShortcut or WshUrlShortcut object.

Remarks

After using the CreateShortcut method to create a shortcut object and set the shortcut object's properties, the Save method must be used to save the shortcut object to disk. The Save method uses the information in the shortcut object's FullName property to determine where to save the shortcut object on a disk. You can only create shortcuts to system objects. This includes files, directories, and drives (but does not include printer links or scheduled tasks).

Example

The following example demonstrates the use of a single .wsf file for two jobs in different script languages (VBScript and JScript). Each job creates a shortcut to the script being run and a URLshortcut to www.microsoft.com.

<package>
   <job id="vbs">
      <script language="VBScript">
         set WshShell = WScript.CreateObject("WScript.Shell")
         strDesktop = WshShell.SpecialFolders("Desktop")
         set oShellLink = WshShell.CreateShortcut(strDesktop & "\Shortcut Script.lnk")
         oShellLink.TargetPath = WScript.ScriptFullName
         oShellLink.WindowStyle = 1
         oShellLink.Hotkey = "CTRL+SHIFT+F"
         oShellLink.IconLocation = "notepad.exe, 0"
         oShellLink.Description = "Shortcut Script"
         oShellLink.WorkingDirectory = strDesktop
         oShellLink.Save
         set oUrlLink = WshShell.CreateShortcut(strDesktop & "\Microsoft Web Site.url")
         oUrlLink.TargetPath = "http://www.microsoft.com"
         oUrlLink.Save
      </script>
   </job>

   <job id="js">
      <script language="JScript">
         var WshShell = WScript.CreateObject("WScript.Shell");
         strDesktop = WshShell.SpecialFolders("Desktop");
         var oShellLink = WshShell.CreateShortcut(strDesktop + "\\Shortcut Script.lnk");
         oShellLink.TargetPath = WScript.ScriptFullName;
         oShellLink.WindowStyle = 1;
         oShellLink.Hotkey = "CTRL+SHIFT+F";
         oShellLink.IconLocation = "notepad.exe, 0";
         oShellLink.Description = "Shortcut Script";
         oShellLink.WorkingDirectory = strDesktop;
         oShellLink.Save();
         var oUrlLink = WshShell.CreateShortcut(strDesktop + "\\Microsoft Web Site.url");
         oUrlLink.TargetPath = "http://www.microsoft.com";
         oUrlLink.Save();
      </script>
   </job>
</package>

See Also

Running Your Scripts | WshShortcut Object | WshUrlShortcut Object | FullName Property | TargetPath Property | WindowStyle Property | Hotkey Property | IconLocation Property | Description Property | WorkingDirectory Property


WshSpecialFolders Object

SpecialFolders PropertyWshShell Object

Provides access to the collection of Windows special folders.

Remarks

The WshShell object's SpecialFolders property returns the WshSpecialFolders object, which is a collection of special folders. This collection contains references to Windows special folders (for example, the Desktop folder, Start Menu folder, and Personal Documents folder). This collection retrieves paths to special folders using the special folder name as the index. A special folder's path depends on the user environment. The information stored in a special folder is unique to the user logged onto the computer system. If several different users have accounts on the same computer system, several different sets of special folders are stored on the hard disk.

The following special folders are available:

  • AllUsersDesktop
  • AllUsersStartMenu
  • AllUsersPrograms
  • AllUsersStartup
  • Desktop
  • Favorites
  • Fonts
  • MyDocuments
  • NetHood
  • PrintHood
  • Programs
  • Recent
  • SendTo
  • StartMenu
  • Startup
  • Templates

Example

The following script demonstrates the use of the WshSpecialFolders Object:

<package>
   <job id="vbs">
      <script language="VBScript">
         set WshShell = WScript.CreateObject("WScript.Shell")
         strDesktop = WshShell.SpecialFolders("Desktop")
         set oShellLink = WshShell.CreateShortcut(strDesktop & "\Shortcut Script.lnk")
         oShellLink.TargetPath = WScript.ScriptFullName
         oShellLink.WindowStyle = 1
         oShellLink.Hotkey = "CTRL+SHIFT+F"
         oShellLink.IconLocation = "notepad.exe, 0"
         oShellLink.Description = "Shortcut Script"
         oShellLink.WorkingDirectory = strDesktop
         oShellLink.Save
      </script>
   </job>

   <job id="js">
      <script language="JScript">
         var WshShell = WScript.CreateObject("WScript.Shell");
         strDesktop = WshShell.SpecialFolders("Desktop");
         var oShellLink = WshShell.CreateShortcut(strDesktop + "\\Shortcut Script.lnk");
         oShellLink.TargetPath = WScript.ScriptFullName;
         oShellLink.WindowStyle = 1;
         oShellLink.Hotkey = "CTRL+SHIFT+F";
         oShellLink.IconLocation = "notepad.exe, 0";
         oShellLink.Description = "Shortcut Script";
         oShellLink.WorkingDirectory = strDesktop;
         oShellLink.Save();
      </script>
   </job>
</package>

Properties

Item Property

Methods

Count Method

See Also

Running Your Scripts | SpecialFolders Property


Unnamed Object

WshUnnamed Object

Unnamed PropertyWshArguments Object

Provides access to the unnamed arguments from the command line.

Remarks

The WshUnnamed object is a read-only collection that is returned by the Unnamed property of the WshArguments object. Individual argument values are retrieved from this collection using zero-based indexes. Two of the WshArguments object's properties are filtered arguments collections — one contains the named arguments (the WshNamed object), the other contains the unnamed arguments (the WshUnnamed object). In total, this gives you three ways to access sets of command-line arguments.

  • You can access the entire set of arguments (those with and without names) with the WshArguments object.
  • You can access the arguments that have names with the WshNamed object.
  • You can access the arguments that have no names with the WshUnnamed object.

Example

The following code displays the number of named and unnamed command-line arguments.

<package>
<job id="JS">
<script language="JScript">

var argsNamed = WScript.Arguments.Named;
var argsUnnamed = WScript.Arguments.Unnamed;

WScript.Echo("There are " + argsNamed.length + " named arguments.");
WScript.Echo("There are " + argsUnnamed.length + " unnamed arguments.");

</script>
</job>

<job id="VBS">
<script language="VBScript">

Dim argsNamed, argsUnnamed
Set argsNamed = WScript.Arguments.Named
Set argsUnnamed = WScript.Arguments.Unnamed

WScript.Echo "There are " & argsNamed.Count & " named arguments."
WScript.Echo "There are " & argsUnnamed.Count & " unnamed arguments."

</script>
</job>
</package>

Properties

Item Property | Length Property (WshArguments object)

Methods

Count Method

See Also

WshArguments Object | WshNamed Object


WshUrlShortcut Object

WshShell Object

Allows you to create a shortcut to an Internet resource programmatically.

Remarks

The WshUrlShortcut object is a child object of the WshShell object — you must use the WshShell method CreateShortcut to create a WshUrlShortcut object (e.g., WshShell.CreateShortcut(strDesktop & "\Shortcut Script.lnk")).

Example

The following example demonstrates the creation of a URL shortcut to www.microsoft.com.

<package>
   <job id="vbs">
      <script language="VBScript">
         set WshShell = WScript.CreateObject("WScript.Shell")
         set oUrlLink = WshShell.CreateShortcut(strDesktop & "\Microsoft Web Site.url")
         oUrlLink.TargetPath = "http://www.microsoft.com"
         oUrlLink.Save
      </script>
   </job>

   <job id="js">
      <script language="JScript">
         var WshShell = WScript.CreateObject("WScript.Shell");
         var oUrlLink = WshShell.CreateShortcut(strDesktop + "\\Microsoft Web Site.url");
         oUrlLink.TargetPath = "http://www.microsoft.com";
         oUrlLink.Save();
      </script>
   </job>
</package>

Properties

FullName Property (WshUrlShortcut Object) | TargetPath Property

Methods

Save Method

See Also

Running Your Scripts | CreateShortcut Method


FullName Property

FullName Property (WshUrlShortcut Object)

Returns the fully qualified path of the shortcut object's target.

object.FullName

Arguments

object
WshUrlShortcut object.

Remarks

String. Read-only.

The FullName property is a read-only string representing the fully qualified path to the shortcut's target.

Example

The following code retrieves the fully qualified path of a URL shortcut.

[VBScript]
set oUrlLink = WshShell.CreateShortcut(strDesktop & "\Microsoft Web Site.url")
oUrlLink.TargetPath = "http://www.microsoft.com"
oUrlLink.Save
WScript.Echo oUrlLink.FullName
[JScript]
var oUrlLink = WshShell.CreateShortcut(strDesktop + "\\Microsoft Web Site.url");
oUrlLink.TargetPath = "http://www.microsoft.com";
oUrlLink.Save();
WScript.Echo (oUrlLink.FullName);

See Also

Path Property | WScript Object | WshShortcut Object | WshUrlShortcut Object


Scripting.Signer Object

The Scripting.Signer object enables an author to sign a script with a digital signature and a recipient to verify the signature's authenticity and trustworthiness.

Remarks

The Scripting.Signer object requires a valid certificate.

Example

The following JScript code shows the Scripting.Signer object digitally signing a script.

<job>
<runtime>
   <named name="file" helpstring="the file to sign" required="true" type="string"/>
   <named name="cert" helpstring="the name of the signing certificate" required="true" type="string"/>
   <named name="store" helpstring="the name of the certificate store" required="false" type="string"/>
</runtime>
<script language="JScript">
   var Signer, File, Cert, Store = "my";
   if (!(WScript.Arguments.Named.Exists("cert") && WScript.Arguments.Named.Exists("file")))
   {
      WScript.Arguments.ShowUsage();
      WScript.Quit();
   }
   Signer = new ActiveXObject("Scripting.Signer");
   File  = WScript.Arguments.Named("file");
   Cert  = WScript.Arguments.Named("cert");
   if (WScript.Arguments.Named.Exists("store"))
   {
      Store = WScript.Arguments.Named("store");
   }

    Signer.SignFile(File, Cert, Store);
</script>
</job>

See Also

Signing a Script | Sign Method | SignFile Method | Verify Method | VerifyFile Method


Signing a Script

The following scripts demonstrate the creation of a signature, which is used in a verification process. The script uses the Signer Object and the SignFile method to create a digital signature.

// JScript.
<job>
<runtime>
   <named name="file" helpstring="the file to sign" required="true" type="string"/>
   <named name="cert" helpstring="the name of the signing certificate" required="true" type="string"/>
   <named name="store" helpstring="the name of the certificate store" required="false" type="string"/>
</runtime>
<script language="JScript">
   var Signer, File, Cert, Store;
   if (!(WScript.Arguments.Named.Exists("cert") && WScript.Arguments.Named.Exists("file")))
   {
      WScript.Arguments.ShowUsage();
      WScript.Quit();
   }
   Signer = new ActiveXObject("Scripting.Signer");
   File  = WScript.Arguments.Named("file");
   Cert  = WScript.Arguments.Named("cert");
   Store = WScript.Arguments.Named("store");
    Signer.SignFile(File, Cert, Store);
</script>
</job>

'VBScript
<job>
<runtime>
   <named name="file" helpstring="the file to sign" required="true" type="string"/>
   <named name="cert" helpstring="the name of the signing certificate" required="true" type="string"/>
   <named name="store" helpstring="the name of the certificate store" required="false" type="string"/>
</runtime>
<script language="VBScript">
   Dim Signer, File, Cert, Store
   If Not (WScript.Arguments.Named.Exists("cert")) And WScript.Arguments.Named.Exists("file")) Then
      WScript.Arguments.ShowUsage
      WScript.Quit
   End If
   Set Signer = CreateObject("Scripting.Signer")
   File  = WScript.Arguments.Named("file")
   Cert  = WScript.Arguments.Named("cert")
   Store = WScript.Arguments.Named("store")
    Signer.SignFile File, Cert, Store
</script>
</job>

See Also

WSH Samples | Verifying a Script | Signing a Script


Sign Method

Signs a script stored in a string.

Object.Sign (FileExtension, Text, Certificate, Store)

Arguments

object
Scripting.Signer
FileExtension
A string designating the script extension type (.vbs, .js, or .wsf). This provides a mechanism by which the operating system can determine the type of script file being verified.
Text
A string containing the script to be signed.
Certificate
A string designating the author's certificate name.
Store
Optional. A string designating the name of the certificate store. Typically certificates that contain private keys — i.e., certificates you can use for code signing — are in a certificate store called "my". The default value is "my".

Remarks

The Sign method is used to digitally sign a script stored in a string. In order to create a digital signature, the caller must have a valid certificate.

Example

Dim Signer, UnsignedText, SignedText
Set Signer = CreateObject("Scripting.Signer")
UnsignedText = _
     "Dim X " & vbCrLf & _
     "X = 123" & vbCrLf & _
     "WScript.Echo X" & vbCrLf
SignedText = Signer.Sign(".VBS", UnsignedText, "Your Certificate Name Here")

See Also

Scripting.Signer Object | SignFile Method | Verify Method | VerifyFileMethod | Signing a Script


SignFile Method

Signs a script using a digital signature.

Object.SignFile (FileName, Certificate, Store)

Arguments

object
Scripting.Signer
FileName
A string containing the name of the script file.
Certificate
A string designating the author's certificate name.
Store
An optional string designating the name of the certificate store. Typically certificates that contain private keys — i.e., certificates you can use for code signing — are in a certificate store called "my". The default value is "my".

Remarks

In order to sign a digital signature, the author must have a valid certificate.

Example

The following example demonstrates not only signature checking but also the command-line argument.

<job>
<runtime>
<named name="file" helpstring="the file to sign" required="true" type="string"/>
<named name="cert" helpstring="the name of the signing certificate" required="true" type="string"/>
<named name="store" helpstring="the name of the certificate store" required="false" type="string"/>
</runtime>
<script language="vbscript">
Dim Signer, File, Cert, Store
If Not (WScript.Arguments.Named.Exists("cert") And WScript.Arguments.Named.Exists("file")) Then
     WScript.Arguments.ShowUsage
     WScript.Quit
End If
Set Signer = CreateObject("Scripting.Signer")
File  = WScript.Arguments.Named("file")
Cert  = WScript.Arguments.Named("cert")
If WScript.Arguments.Named.Exists("store") Then
     Store = WScript.Arguments.Named("store")
Else
     Store = "my"
End If
Signer.SignFile File, Cert, Store
</script>
</job>

See Also

Scripting.Signer Object | Sign Method | Verify Method | VerifyFile Method | Signing a Script


Verify Method

Verifies a digital signature retrieved as a string.

object.Verify (FileExtension, Text, ShowUI)

Arguments

object
Scripting.Signer
FileExtension
A string designating the script extension type (.vbs, .js, or .wsf). This provides a mechanism by which the operating system can determine the type of script file being verified.
Text
The text to verify.
ShowUI
A Boolean value. If the ShowUI argument is false, then the Scripting.Signer object determines whether a trusted source provided the signature without prompting the user. If it is true then the Scripting.Signer object may create dialog boxes to prompt the user if there is not sufficient information to determine trust.
Note On some operating systems, the operating system also creates a dialog box if the flag is on, the file is trusted, and you have not already checked the "Always trust …" option.

Remarks

The Verify method is used to verify a digital signed script stored in a string.

Example

In this example the Verify method determines whether the script in the UnsignedText variable is trusted. (In this example there is no digital signature, so the Scripting.Signer object asks the user whether to extend trust.)

Dim Signer, UnsignedText, Trusted
Set Signer = CreateObject("Scripting.Signer")
UnsignedText = _
     "Dim X " & vbCrLf & _
     "X = 123" & vbCrLf & _
     "WScript.Echo X" & vbCrLf
Trusted = Signer.Verify(".VBS", UnsignedText, True)

See Also

Scripting.Signer Object | VerifyFile Method | Sign Method | SignFile Method | Verifying a Script


VerifyFile Method

Verifies the digital signature encapsulated in a script.

Object.VerifyFile (FileName, ShowUI)

Arguments

object
Scripting.Signer
FileName
A string containing the name of the script file.
ShowUI
A Boolean value. If the ShowUI argument is false, then the Scripting.Signer object determines whether a trusted source provided the signature without prompting the user. If it is true then the Scripting.Signer object may create dialog boxes to prompt the user if there is not sufficient information to determine trust.
Note On some operating systems, the operating system also creates a dialog box if the flag is on, the file is trusted, and you have not already checked the "Always trust …" option.

Example

The following example demonstrates signature checking using the command-line argument processing features.

<job>
<runtime>
<named name="file" helpstring="the file to sign" required="true" type="string"/>
<named name="UI" helpstring="produce user interface for untrusted scripts" required="false"/>
</runtime>
<script language="vbscript">
Dim Signer, File, UI, OK
If Not WScript.Arguments.Named.Exists("file") Then
     WScript.Arguments.ShowUsage
     WScript.Quit
End If
Set Signer = CreateObject("Scripting.Signer")
File = WScript.Arguments.Named("file")
UI   = WScript.Arguments.Named.Exists("ui")
OK = Signer.VerifyFile(File, UI)
If OK Then
     WScript.Echo File & " is trusted."
Else
     WScript.Echo File & " is NOT trusted."
End If
</script>
</job>

See Also

Scripting.Signer Object | Verify Method | Sign Method | SignFile Method | Verifying a Script


Windows Script Components

Script Components

Microsoft® Windows® Script Components provide you with an easy way to create COM components using scripting languages such as Microsoft® Visual Basic® Scripting Edition (VBScript) and Microsoft® JScript®. Use script components as COM components in applications such as Microsoft® Internet Information Services (IIS), Microsoft® Windows® Script Host, and any other application that can support COM components. The areas discussed in this tutorial are shown in the following list.

  • Script Components Overview Learn what script components are and how to use them.
  • Creating Script Components Create a script component.
  • Using Script Components Use a script component in your applications.
  • Implementing ASP Script Components Create a script component that incorporates the functionality of Active Server Pages (ASP), allowing you to isolate and reuse ASP logic.
  • Implementing DHTML Behavior Script Components Create a script component that can be used in Microsoft® Internet Explorer 5.0 to define behaviors.


letovervw

Script Components Overview

Windows® Script Components are an exciting new technology that allows you to create powerful, reusable COM components with easy-to-use scripting languages such as Microsoft® Visual Basic® Scripting Edition (VBScript) and Microsoft® JScript®. The following topics provide an overview of script component technology, and explain how to create and use script components.

  • Introducing Script Components Learn what script components are, and the advantages to using them.
  • How Script Components Work Understand what script component technology consists of, and how to create script components.


Introduction

Introducing Windows Script Components

Windows® Script Components provide you with an easy way to create powerful, reusable COM components in script. You create script components using any scripting language that supports the Microsoft® ActiveX® Scripting interfaces. Script languages that support these interfaces include JScript, Microsoft® Visual Basic® Scripting Edition (VBScript), PERLScript, PScript, and Python.

Note For more information about ActiveX Scripting interfaces, see the Microsoft Scripting Technologies Web site at www.microsoft.com.

This new script component technology supports common types of COM components, such as Automation, and is extensible with add-ons such as DHTML behaviors.

Script Components:

  • Are small and efficient.
  • Are easy to create, maintain, and deploy.
  • Provide the ability to create COM components.
  • Provide access to a broad range of system services.

Using script components, you can create COM components for a variety of tasks, such as performing middle-tier business logic, accessing and manipulating database data, adding transaction processing to applications, and adding interactive effects to a Web page using DHTML Behaviors.

See Also

How Script Components Work | Creating Script Components


How Script Components Work

Windows® Script Component technology consists of three pieces:

  • The script component run-time (Scrobj.dll), which helps dispatch COM requests to your scripts. In COM terms, Scrobj.dll functions as the inproc server for script components.
  • Interface handlers, which are compiled components that implement specific COM interfaces. Different interface handlers come ready to work as specific types of COM components.

    The most commonly used interface handlers, including the COM Automation interface handler, an ASP interface handler, and a handler for DHTML Behaviors, are already built into the script component run-time. Others are available as add-on components, or embedded into specific applications.

  • Your script component file (an .wsc file). Script component files are XML (Extensible Markup Language) files that contain information about what type of COM component you want to create (that is, what interface handlers you want to use). Then, depending on what functionality the handler makes available, you write script in your script component to implement those interfaces.

The script component run-time serves as an entry point for the host application. The complexities of COM, including the implementation of such COM-standard interfaces as IUnknown, are embedded in the various interface handlers. Your script component contains only the script required to implement the functionality of the COM component.

For example, one of the most common types of COM components is an Automation component, which is a component with properties and methods that can be called from other applications. The low-level COM interfaces required to implement this functionality — such as dispatching to the correct function when a method is called — are built into an Automation interface handler. In your script component file, you define the properties, methods, and events you want to expose, and the Automation handler makes sure they are called correctly when the host application needs them.

See Also

Introducing Script Components | Creating Script Components


letcreates

Creating Script Components

Creating a Windows® Script Component (.wsc) file is much like creating any file containing scripts, including HTML files. The following topics provide information about the basic layout of a script component file, as well as information about creating registration information and type libraries.

  • Script Component File Contents Learn about the XML (Extensible Markup Language) elements required for a script component.
  • Using The Script Component Wizard Use the Script Component Wizard to create a script component file.
  • Creating Registration Information Create information in the script component file that is used to register it as a COM component.
  • Exposing Methods Add methods to your script component.
  • Exposing Properties Add properties to your script component.
  • Exposing Events Define and fire custom events in your script component.
  • Creating a Script Component Type Library Create a type library for your script component so it can be used more easily in the host application.
  • Referencing Other Components Include global references to objects you need in your scripts, to external type libraries that provide constants for use in your scripts, or to resources that point to strings or values not hard-coded into your scripts.
  • Referencing Another Script Component in the Same Package When including multiple script components in the same package, embed the functionality of one script component inside another.
  • Checking For Errors in Script Component Files Add compile-time error checking to your script component.
  • Script Component Files and XML Conformance Learn about XML conformance.


.htm

Windows® Script Component files are XML (Extensible Markup Language) that are much like HTML files, but contain special elements that define the script component and its behavior. The elements used for defining script components are not HTML tags, but are XML elements specifically used for script component definitions.

A basic script component file contains these elements:

  • <component> and <package> elements The <component> element encloses one entire script component definition. Multiple <component> elements can appear in the same .wsc file, and are contained within a master <package> element.
  • <registration> element Includes information used to register your script component as a COM component. This element might not be required if the host application (such as Microsoft® Internet Explorer 5.0) does not directly use the Windows registry when creating an instance of the script component.
  • <public> element Encloses definitions for properties, methods, and events that your script component exposes. The definitions point to variables or functions defined in a separate <script> block.
  • <implements> element Specifies the COM interface handler for the script component, which determines what type of COM component the script component will be. For example, by specifying <implements type=ASP>, you implement the ASP interface handler and therefore get access to the ASP object model in your script component.

    The <public> element is used to specify that a script component implements the COM Automation interface handler. Therefore, you don't need to create an <implements> element for the Automation handler.

    Note The script component run-time includes interface handlers for Automation (exposed using the <public> element), for ASP, and for Internet Explorer 5.0 DHTML Behaviors. Other interface handlers are available as external DLLs. For more information about additional interface handlers and script components, see the Microsoft Scripting Technologies Web site.
  • <script> element Contains the script used to implement the logic of your script component, depending on what type of COM component you are creating. For example, if you are creating a COM Automation component, you declare properties, methods, and events in a <public> element, and then write the script to define them in one or more <script> elements.
  • <object> element Contains information about an object that you use in your script, such as another COM component.
  • <resource> elements Contain values that should not be hard-coded into script component code. Resource elements can include information that might change between versions, strings that might be translated, and other values.
  • <reference> element References a type library you want to use in script.
  • <comment> elements Contain text that is ignored when the script component is parsed and executed.
    Note If you are concerned that the .wsc files you create contain XML that conforms to XML standards, you can specify that the script component's XML parser check the XML syntax. For example, this is useful if you think you might someday use an XML editor to work with your files. Otherwise, however, it is not usually a concern. For more details, see Script Component Files and XML Conformance.

Skeleton Script Component File

The following example illustrates how to construct a script component file.

<?XML version="1.0"?>
<package>
<?component error="true" debug="true"?>

   <comment>
      This skeleton shows how script component elements are
      assembled into a .wsc file.
   </comment>

<component id="MyScriptlet">
   <registration
      progid="progID"
      description="description"
      version="version"
      clsid="{00000000-0000-0000-000000000000}"/>

   <reference object="progID">

   <public>
      <property name="propertyname"/>
      <method name="methodname"/>
      <event name="eventname"/>
   </public>

   <implements type=COMhandlerName id=internalName>
      (interface-specific definitions here)
   </implements>

   <script language="VBScript">
      <![CDATA[
      dim propertyname
      Function methodname()
      ' Script here.
      End Function
      ]]>
   </script>

   <script language="JScript">
      <![CDATA[
      function get_propertyname()
      { // Script here.
      }
      function put_propertyname(newValue)
      { // Script here.
         fireEvent(eventname)
      }
      ]]>
   </script>

   <object id="objID" classid="clsid:00000000-0000-0000-000000000000">
   <resource ID="resourceID1">string or number here</resource>
   <resource ID="resourceID2">string or number here</resource>
</component>
</package>
Note In XML, you can specify elements without content (attributes only), such as the <property> and <method> elements in the previous example, by closing the element with />.

Note that:

  • The <?XML ?> declaration at the top indicates that this is an XML file and that it conforms to XML protocol. This declaration is optional; if you leave it out, you can use slightly looser syntax when creating the script component's elements. For details, see Script Component Files and XML Conformance.
  • The <package> element is optional in this example, because the file contains only one <component> element.
  • The <?component?> processing instruction includes attributes for specifying the error checking options. For details, see Checking For Errors in Script Component Files. If you do not include this element, the default options are all false.
  • A <comment> element can appear anywhere in the script component.
  • A <registration> element is not required in all cases. For example, a script component that implements the DHTML Behaviors interface handler in Internet Explorer 5.0 does not need to be registered, because Internet Explorer directly instantiates the behaviors as they are detected on the page. For details about registration requirements, see the documentation for the interface handler you are implementing, and note also which host the script component will be used in.
  • A <reference> element allows you to include a type library in the script component so you can use the library's constants in your script.
  • The <public> element encloses <property>, <method>, and <event> elements. The script that defines these appears later in the script component file.
  • The <implements> element is used to make available non-default COM interfaces. For example, you can expose the ASP interface with an <implements> type such as the following:
    <implements type="ASP" id="iASP">

    The exact elements that appear inside an <implements> element depend on what interface you are implementing.

    Note The <implements> element is shown here with an id attribute. However, this attribute is optional, except in cases where you must disambiguate objects or variables. For details, see the <implements> element.
  • In this skeleton, there are two script elements, one for VBScript and one for JScript. If you are using only one scripting language, you do not need more than one <script> element. Because the <?XML ?> declaration appears at the top of the file, a CDATA section is required to make the script in the <script> element opaque. For details, see Script Component Files and XML Conformance.
  • The <object> element creates a reference to an object you want to use in script within the script component.

After creating the skeleton, fill in the elements to define the script component's functionality, depending on which interface handler you are implementing.

See Also

Checking For Errors in Script Component Files | Creating a Script Component Type Library | Creating Registration Information | Exposing Events | Exposing Methods | Exposing Properties | Implementing ASP Script Components | Implementing DHTML Behavior Script Components | Script Component Files and XML Conformance | Using the Script Component Wizard


Using the Script Components Wizard

Using the Script Component Wizard

The Windows® Script Component package includes a Script Component Wizard that automates the process of creating a script component (.wsc) file. The wizard performs the following functions:

  • Creates the .wsc file and adds basic XML elements.
  • Prompts for and creates registration information.
  • Prompts for the type of interface handler you want the script component to use.
  • Prompts for properties you want to expose and creates the necessary elements in the scripting language you specify.
  • Prompts for methods you want to expose and creates the necessary elements in the scripting language you specify.
  • Prompts for events that the script component can fire and creates the skeleton event elements.
    Note You can download and install the Script Component Wizard from the Microsoft Scripting Technologies Web site on www.microsoft.com.

The wizard creates a skeleton script component with information you provide, and writes it out as an .wsc file. Edit the .wsc file and add your script to create the script component's functionality.

Note The wizard creates a script component file containing the <?XML ?> declaration at the top, meaning that the contents of the file must be XML-conformant. For more details, see Script Component Files and XML Conformance.

See Also

Script Component File Contents | Creating Registration Information | Creating Script Components | Script Component Files and XML Conformance


Creating Registration Information

If the host application requires it, you can register a Windows® Script Component as a COM component using a program such as Regsvr32.exe. Registration places information about the COM component in a public location (in Windows, registration information is stored in the Windows registry). By reading the registration information, applications can find and load the COM component.

Note Registration is not required in every case. For example, a script component that implements the DHTML Behaviors interface handler in Internet Explorer 5.0 does not need to be registered, because Internet Explorer registers the behaviors as they are detected on the page. For more details about using Behaviors, see the "Using DHTML Behaviors" topic on the Microsoft Site Builder Network (SBN) Web site. If the host application supports monikers, you can also create an instance of a script component without registering it.

When you specify registration, the most important information is:

  • A program ID (prog ID), which is the name used in the host application when creating an instance of the script component. For example, if your script component's program ID is Component.MyComponent, you can create an instance of it in Microsoft® Visual Basic® using a statement such as the following:
    Set Component = CreateObject("Component.MyComponent")
  • A class ID, which is a GUID (globally unique ID) that uniquely identifies your script component. You can generate a GUID with a program such as Uuidgen.exe.
    Note If you create a script component using the Script Component Wizard, the wizard automatically creates a program ID and class ID for you. For details, see Using The Script Component Wizard.

Registration information also includes a description and a version number.

The registration program can create a class ID for your script component when it is registered. However, it is highly recommended that you provide a class ID for the script component yourself, to ensure that your script component has the same class ID on all computers on which it is registered. Allowing the registration program to create a class ID can also cause problems if you use the script component with development tools that store class IDs. If the registration creates a new class ID each time, it will not match the ID stored by the application.

To create registration information for the script component

  • Create an <registration> element that includes at least a program ID, and optionally, a class ID, description, and version, as shown in the following example:
    <registration
description="My Test Component"
progid="Component.TestScript"
version="1"
classid="{2154c700-9253-11d1-a3ac-0aa0044eb5f}"/>
    Note The registration attributes can appear in any order in the <registration> element.

Running Script During Registration

The script component <registration> element also allows you to include script that will be executed when the script component is registered and unregistered. For example, you can post a message that the script component has been registered.

To run script during registration and unregistration

  • In the <registration> element, include an <script> element. To run script during registration, write a register( ) function. To run script when the script component has been unregistered, include an unregister( ) function.

    The following example shows how to post messages when the script component is registered or unregistered.

    Note A CDATA section is required to make the script in the <script> element opaque. For details, see Script Component Files and XML Conformance.
    <registration
   description="My Test Component"
   progid="Component.TestScript"
   version="1"
   classid="{2154c700-9253-11d1-a3ac-0aa0044eb5f}">

   <script language="VBScript">
   <![CDATA[
      Function register()
         MsgBox "Component 'My Test Component' registered."
      End Function
      Function unregister()
         MsgBox "Component 'My Test Component' unregistered."
      End Function
   ]]>
   </script>
</registration>

Registering for Remote Access

If you are deploying your script component in a distributed environment, you can specify that the script component can be instantiated remotely. For example, you might be creating a script component designed to run on a server, but which will be called from code on a client. This scenario is possible if the client and server machines are properly configured with DCOM, which provides the mechanism for passing object pointers to the client from the server.

To register a script component for remote access

  • Include the remotable attribute in the <registration> element, as shown in the following example:
    <registration
   description="My Test Component"
   progid="Component.TestScript"
   version="1"
   classid="{2154c700-9253-11d1-a3ac-0aa0044eb5f}"
   remotable=true/>

For more details about creating instances of a script component remotely, see Using a Script Component in an Application.

See Also

Script Component File Contents | Using The Script Component Wizard | Creating a Script Component Type Library | Checking For Errors in Script Component Files | Script Component Files and XML Conformance


Exposing Methods

Methods are implemented as functions or subroutines in your Windows® Script Component file.

To expose a method

  1. Create a <public> element as a child of the <component> element.
  2. In the <public> element, include a <method> element. The method element can optionally include one or more <parameter> elements to define the method's parameters.
  3. Write a procedure in any scripting language to implement the function. Place the procedure in a <script> element outside the <implements> element but within the <component> element. Be sure the function name matches the functionName, or if you did not specify a functionName, the methodName name you specified in the <method> element.

    For example, the following example shows a fragment from a script component file with two methods, factorial and getRandomNumber.

    Note A CDATA section is required to make the script in the <script> element opaque. For details, see Script Component Files and XML Conformance.
    <public>
   <method name="factorial"/>
   <method name="random" internalName="getRandomNumber">
      <parameter name="upperBound"/>
      <parameter name="seed"/>
   </method>
</public>

<script language="VBScript">
Function factorial(n)
   <![CDATA[
   If isNumeric(n) Then
      If n <= 1 Then
         factorial = 1
      Else
         factorial = n*factorial(n-1)
      End If
   Else
      factorial = -2   ' Error code.
   End If
End Function

Function getRandomNumber(upperBound, seed)
   getRandomNumber = Cint(upperBound * Rnd(seed) + 1)
End Function
]]>
</script>

You can specify a default method for a script component so the host application can invoke the method without explicitly calling it. For example, if you have exposed a method called factorial and marked it as the default, you can call it in the followoing ways in Visual Basic:

Set component = CreateObject("component.MyComponent")
n = component.factorial(4)   ' Calls factorial method explicitly.
n = component(4)   ' Calls factorial method as default.

To specify a default method, include an attribute assigning a special dispatch identifier (a dispid) to the method. For more information about dispids, see Exposing Events.

To specify a default method

  • In the <method> element, include the attribute dispid="0", as shown in the following example:
    <public>
   <method name="factorial" dispid="0"/>
</public>
    Note This technique can be used to assign either a default method or a default property, but not both. There can be only one element in the script component with the dispid of zero.

See Also

Exposing Events | Exposing Properties | Script Component File Contents


Exposing Properties

You can expose properties in two ways:

  • As simple values The property is simply a global variable that can be read and written by the script component's user. Because the value is stored in a global value, you can manipulate it in your Windows® Script Component file's scripts.
  • As functions The property is defined using a function. This allows you to calculate a property value, and to control whether a property is read-only, read-write, or write-only.

You can also mark a property as the default value for a script component.

To expose a property as a simple value

  1. Create a <public> element as a child of the <component> element.
  2. In the <public> element, include a <property> element that specifies the variable used to store property value.
  3. To initialize the value of a simple property, create a global variable in the <script> element with a name matching propertyName (or propertyVariable, if you specified that) and assign it a value.
  4. The following script component fragment illustrates two properties (name and tag) exposed as simple values. The properties are initialized using global variables in the <script> element.
    Note A CDATA section is required to make the script in the <script> element opaque. For details, see Script Component Files and XML Conformance.
    <public>
   <property name="name"/>
   <property name="tag" internalName="tagVar"/>
</public>

<script language="VBScript">
   <![CDATA[
   Dim name
   name = "script component"   ' Initializes the value of name property.
   Dim tagVar
   tagVar = "10"   ' Initializes the value of tag property.
   ]]>
</script>

Exposing a property using functions is similar to exposing a method.

To expose a property using functions

  1. In the script component file's <public> element, include a <property> element that contains a <get> element to define the read function and a <put> element to define the write function. If you do not include the <put> element, the property will be read-only. If you do not include the <get> element, the property will be write-only.
  2. Write procedures in a <script> element outside the <public> element to implement the functions. The function for setting the property's value — the put function — must accept a single parameter, the value to set the property to.

    The names of the procedures must match the internal names you specified in the <property> element. If you did not specify an internalName attribute, the names of the functions must be the name of the function with the get_ prefix for a read function, and with a put_ prefix for the write function.

  3. For example, the following script component fragment is an example of a script component file that exposes three properties: sname, dateOfBirth, and age. The dateOfBirth property is defined by functions so it can include error checking. The age property is calculated, and is therefore defined as read-only.
    Note A CDATA section is required to make the script in the <script> element opaque. For details, see Script Component Files and XML Conformance.
    <public>
   <property name="sname"/>
   <property name="age">
      <get internalName="readAge"/>
   </property>
   <property name="dateOfBirth">
      <get internalName="readDOB"/>
      <put internalName="writeDOB"/>
   </property>
</public>

<script language="VBScript">
<![CDATA[
Dim sname   ' Read-write sname property (no functions).
Dim gDOB   ' Global variable used to store date of birth.

Function readDOB()
   ' Gets value of dateOfBirth property.
   readDOB = gDOB
End Function

Function writeDOB(newDOB)
   ' Sets value of dateOfBirth property.
   If isDate(gDOB) Then
      'Error checking
      gDOB = newDOB
   End If
End Function

Function readAge()
   ' Calculates read-only age property.
   If isDate(gDOB) Then
      dobM = DatePart("m", gDOB)
      dobD = DatePart("d", gDOB)
      dobY = DatePart("yyyy", gDOB)
      todayY = DatePart("yyyy", Date)
      age = todayY - dobY

      ' Adjust if birthday has not yet occurred this year.
      bday = DateValue(dobM & "/" & dobD & "/" & todayY)
      If DateDiff("d", bday, DateValue(Date)) < 0 Then
         age = age - 1
      End If
      readAge = age
   End If
End Function
]]>
</script>

You can specify a default property for a script component so the host application can get or set the property's value without explicitly naming the property. For example, if you have exposed a property called sname and marked it as the default, you can work with it in either of these ways in Visual Basic:

Set component = CreateObject("Component.MyComponent")
n = component.sname   ' Gets property explicitly.
n = component   ' Gets value of sname as default.

To specify a default property, include an attribute assigning a special dispatch identifier (a dispid) to the method. For more information about dispids, see Exposing Events.

To specify a default property

  • In the <property> element, include the attribute dispid="0", as in the following example:
    <property name="sname" dispid="0"/>
    Note This technique can be used to assign either a default property or a default method, but not both. There can be only one element in the script component with the dispid of zero.

See Also

Exposing Events | Exposing Methods | Script Component File Contents | Script Component Files and XML Conformance


Exposing Events

To add event capability to a Windows® Script Component:

  • Declare each event that you want to be able to fire.
  • Call a function to fire the event as required in the script component.

Some host environments also require that you generate a type library which they use to bind to events. For details, see Creating a Script Component Type Library.

Note The Behavior handler exposes events in a slightly different way. For details, see Exposing Custom Events in Behavior Script Components.

Declaring Events

Each event you want to be able to fire must be individually declared.

To declare an event

  1. Create a <public> element as a child of the <component> element.
  2. In the <public> element, include an <event> element for each event you want to declare.
  3. For example, the following script component fragment shows how to expose two events:
    <public>
   <property name="sname"/>
   <method name="factorial"/>
   <event name="namechanged"/>
   <event name="querydone"/>
</public>

Specifying Dispatch Identifiers

COM programming provides event notification via dispatch identifiers (each referred to as a dispid), which are integer values that identify a component's events. The dispid is compiled into the component's type library and then used by the host application to bind to events.

The process of creating a type library for script components automatically generates dispids for your script component's events. However, if you prefer, you can specify your own dispids. Doing so allows you to:

  • Guarantee that events in your script component will always have the same dispid. If the type library generator assigns dispids, they can change each time the library is generated.
  • Map events in your script component to dispids with specific numbers. For example, if you want to fire a standard COM event such as an error notification, you can map your event to the values used by convention in COM.

To specify a dispid for an event, include the dispid attribute in the <event> element, as in the following example:

<public>
   <event name="namechanged" dispid="22">
</public>

Dispids must be unique within the script component. You can specify a negative value for a dispid to map to conventional events, but must use only specified ranges, such as -999 to -500 for controls. For details about reserved dispid ranges, refer to documentation for DISPID in the MSDN library.

Note The dispid number zero is used to identify a default method or property. For more details, see Exposing Methods and Exposing Properties.

Firing an Event

You can fire an event by calling the fireEvent method, specifying the name of the event to fire. You cannot fire events that you did not expose in the <implements> element. You can fire an event in any script in your script component file. For example, the following illustrates how you can fire an event when a property value changes.

<script language="VBScript">
<![CDATA[
Sub put_lowercaseName(newLCName)
   name = newLCName
   fireEvent("namechanged")
End Sub
]]>
</script>

See Also

Exposing Custom Events in Behavior Script Components | Exposing Methods | Exposing Properties | Handling Script Component Events in the Host Application | Script Component File Contents


Creating a Script Component Type Library

You can generate a type library for your Windows® Script Component containing information about its interfaces and members. In some host applications (such as Visual Basic), type libraries are necessary to enable events for the script component, while in other host applications, type libraries are optional. However, even if a type library is not required, generating one can make working with a script component easier and less error-prone in the host application.

For example, if you are using Visual Basic as your host application, use the References dialog box to select a script component's type library. This allows you to bind events to the script component and make them visible in Visual Basic. In addition, when you are writing Visual Basic code that references the script component, Visual Basic uses the type library information in statement completion and in the Object Browser so you can easily see and use properties, methods, and events that the script component exposes.

Note For information about using a type library in the host application, refer to the application's documentation.

To create a script component type library

  • In Windows Explorer, right-click the script component .wsc file, and then choose Generate Type Library.

    A .tlb file is generated for the script component with the same name as the script component file, written to the folder where the .wsc file is, and registered in the Windows registry.

For more precise control over generating type libraries, you can generate the type library dynamically from script inside the script component file, or you can use a command-line interface.

Generating Type Libraries Dynamically

The script component run-time includes an Automation interface implemented by the Component.GenerateTypeLib object. You can use this object in script to generate a type library from within the script component file. This is particularly useful for creating a type library automatically when the script component is registered.

To create a script component type library dynamically

  1. In script inside the script component file, create an instance of the Component.GenerateTypeLib object by using syntax such as the following:
    set oTL = CreateObject("Scriptlet.GenerateTypeLib")
  2. Set the following properties of the Component.GenerateTypeLib object:
    Property/Method | Description
    AddURL | (Method) Adds the URL of the script component file from which to generate the type library. You can call this method property multiple times to include multiple script components in the type library.
    Path | (Property) The path and file where the type library will be written. The default path is the current directory and the default name is the name of the script component file with a .tlb extension. If the object is unable to create the specified library, it defaults to creating a type library called component.tlb.
    Doc | (Property) A string containing any information that is stored in the registry with the type library information.
    GUID (Property) A GUID for the type library. (This is not the GUID for the script component.) If you do not provide one, the GenerateTypeLib object will create one, but then the type library will have a different GUID on each machine. The GUID must be exactly in this format, where x represents a hex value:
    {xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx}
    Name | (Property) The internal name for the type library. This name is displayed in some applications, such as the Visual Basic Object Browser.
    MajorVersion | (Property) An integer value you assign.
    MinorVersion | (Property) An integer value you assign.
  3. Call the type library object's Write method to create the .tlb file, then register it.
  4. If you want to create an additional type library, call the GenerateTypeLib object's Reset method to clear the list of script component files in the AddURL property, reset the URLs and any other properties you want, and then call the Write method again.

For example, the following script in a <registration> element creates a type library dynamically.

Note A CDATA section is required to make the script in the <script> element opaque. For details, see Script Component Files and XML Conformance.
<registration
   description="My Test Component"
   progid="Component.TestScript"
   version="1"
   classid="{2154c700-9253-11d1-a3ac-0aa0044eb5f}">
   <script language="VBScript">
   <![CDATA[
   Function Register()
      Set oTL = CreateObject("Scriptlet.GenerateTypeLib")
         oTL.AddURL "d:\components\MyComponent.wsc"   ' Script component URL.
         oTL.AddURL "d:\components\YourComponent.wsc"
         oTL.Path = "d:\components\MyComponent.tlb"   ' .tlb path.
         oTL.Doc = "Sample component typelib"   ' Documentation string.
         oTL.GUID = "{a1e1e3e0-a252-11d1-9fa1-00a0c90fffc0}"
         oTL.Name = "MyComponentTLib" ' Internal name for tlb.
         oTL.MajorVersion = 1
         oTL.MinorVersion = 0
         oTL.Write ' Write tlib to disk.
         oTL.Reset ' Clear list of URLs in AddURL/.
      End Function
   ]]>
   </script>
</registration>

Command-line Interface

If you are comfortable using the Command Prompt window, you can call the Rundll32.exe program to create type libraries.

To create a type library from the command prompt

  • Call Rundll32.exe using this syntax:
    rundll32.exe path\scrobj.dll,GenerateTypeLib options

    Where:

    • path The path where Scrobj.dll is located on your computer.
    • options A set of flags and values you can use to specify type library information in the form -flag:value. You can specify the options in any order. The following flags are supported, with values as described under the previous section, To create a script component type library dynamically.
      -name:Name
      -file:Path
      -doc:\"Doc\"
      -guid:GUID
      -major:MajorVersion
      -minor:MinorVersion
      -URL:AddURL

For example, the following command creates a type library called MyComponent.tlb from the script component MyComponent.wsc (the command is wrapped for clarity):

rundll32.exe c:\winnt\system32\scrobj.dll,GenerateTypeLib
   -name:MyComponentTLib -file:d:\components\MyComponent.tlb
   -doc:\"Sample component typelib\"
   -guid:{a1e1e3e0-a252-11d1-9fa1-00a0c90fffc0} -major:1 -minor:0
   -URL:d:\components\MyComponent.wsc

Troubleshooting Type Libraries

The process of generating a type library can fail for various reasons. The error you see might not be clear enough in all cases to make it obvious where the problem lies. If you are unable to generate a type library, review the following list of likely causes for the failure.

  • If a property is defined by functions, the get and put functions must have the same number of arguments with the same names. For details, see Exposing Properties.
    Note It is possible to define a script component in which the get and put property functions have different numbers of arguments, but you cannot create a type library for that script component.
  • If you are exposing events, you cannot use the same dispatch identifiers (dispid) more than once in a script component. Additionally, you cannot use a negative value for the dispid unless it is within a specified range. For details, see Exposing Methods.
  • The ID attributes of elements in the script component must be unique. If you are generating a type library from more than one script component, then the IDs must be unique in the type library as a whole.

See Also

Script Component File Contents | Creating Registration Information | Checking For Errors in Script Component Files | Script Component Files and XML Conformance


Referencing Other Components

Your Windows® Script Component can include references to external components that you need to create the script component, such as:

  • Additional COM objects
  • Type libraries
  • Resources, such as numbers and text, that you do not want to hard-code into your script component's scripts.

Referencing Additional COM Components

In your script component, it might be necessary to create instances of other COM components as needed. You can do so in two ways:

  • In script Create instances of other objects directly in your script. For example, you can use the CreateObject function in Microsoft® Visual Basic® Scripting Edition (VBScript) or the new ActiveXObject Object in JScript.
  • Using an OBJECT element Use an <object> element similar to the <OBJECT> tag you use in HTML pages. Using an <object> element makes objects globally available to any script and allows scripting tools to provide statement completion. It also provides a convenient way to summarize and document the objects you use in your script component.
    Note Although <object> elements in script components are similar to <OBJECT> tags in HTML pages, the list of attributes for an <object> element in a script component is shorter, because script components do not present a user interface.

To create an OBJECT element

  • Create an <object> element. This element should be inside the <component> element, but outside of any other element such as a <script> element.

The following example shows an object definition in a script component.

<object id="cnn" progid="ADODB.Connection"/>

Referencing an External Type Library

Many components that you might work with support type libraries, which provide a complete listing of the component's classes and their members. By referencing the component's type libraries, you can use constants defined in the type library.

To include a reference to a type library

  • Include a <reference> element in your script component that specifies the location and name of the type library to include. For example:
    <reference object="ADODB.Connection.2.0"/>

Referencing Resources

Resource elements can include information that might change between versions, strings that might be translated, and other values.

To reference resources

  1. In the script component, but outside of the <public> and <script> elements (and <implements> element, if any), create one <resource> element for each resource you want to define, giving each element a unique ID. The following example shows two <resource> elements:
    Note A CDATA section is required to make the contents of the <resource> element opaque to the parser. For details, see Script Component Files and XML Conformance.
    <component id="MyScriptlet">
<public>
   <method name="random" internalName="getRandomNumber"/>
</public>
<resource id="errNonNumeric"><![CDATA[Non-numeric value passed]]>
</resource>
<resource id="errOutOfRange"><![CDATA[Passed value is out of range ]]>
</resource>
  2. In your script, include the resource text or number by calling the getResourcefunction, as shown in the following example.
    Note A CDATA section is required to make the script in the <script> element opaque to the parser. For details, see Script Component Files and XML Conformance.
    <script language="VBScript">
<![CDATA[
Function getRandomNumber(upperBound)
   If IsNumeric(upperBound) Then
      getRandomNumber = Cint(upperBound * Rnd + 1)
   Else
      getRandomNumber=getResource("errNonNumeric")
   End If
End Function
]]>
</script>

See Also

Script Component File Contents | Referencing Another Script Component in the Same Package


Referencing Another Script Component in the Same Package

You can create a package that contains multiple Windows® Script Components, so you can also instantiate and use one of the script components from the other without having to register the second script component.

For example, you might create one script component that implements the Automation interface and exposes a series of properties and methods. A second script component in the same package might implement the ASP interface, which provides access to the server object model for Microsoft® Internet Information Services (IIS). You can then create a method or property in the Automation script component that exposes the ASP script component and makes its members available.

To reference one script component from another, create a skeleton member — a property or method — in one method that exposes the second script component.

To reference another script component in the same script component file

  1. Declare a property or method in the first script component.
  2. As part of the definition for the new property or method, call the createComponentfunction.

    For example, the following shows two script components in the same package. In the first script component, the math method simply references the second script component, which exposes the add method and the multiply method.

    Note A CDATA section is required to make the script in the <script> element opaque. For details, see Script Component Files and XML Conformance.
    <?XML version="1.0"?>
<package>
<component id="component1">
<registration progid="Component.FrontEnd"/>
<public>
   <property name="math"/>
</public>
<script language="JScript">
<![CDATA[
var math = createComponent("component2")
   ]]>
</script>
</component>

<component id="component2">
<registration progid="Component.Math"/>
<public>
   <method name="add"/>
   <method name="multiply"/>
</public>
<script language="JScript">
<![CDATA[
function add(n1, n2){
   return n1+n2;
}
function multiply(n1, n2){
   return n1*n2;
}
]]>
</script>
</component>
</package>

To invoke the referenced script component, call the full member hierarchy to get to its methods or properties. The following example illustrates a few ways to do this:

' Creates instance of first script component.
set o1 = CreateObject("Component.FrontEnd")

' Invokes the second script component's functions directly.
msgbox(o1.math.add(3,5))
msgbox(o1.math.multiply(3,5))

' Creates a second object that references the math method directly.
Set o2 = o1.math()
msgbox(o2.add(4,5))
msgbox(o2.multiply(4,5))

Each time you call the createComponent() function, it creates a new instance of the referenced script component. If you need to preserve instance information between calls, store the pointer to the second script component in a global variable, as in the following example.

Note A CDATA section is required to make the script in the <script> element opaque. For details, see Script Component Files and XML Conformance.
<component id="component1">
<registration progid="Component.FrontEnd"/>
<public>
   <property name="math">
      <get/>
   </property>
</public>
<script language="JScript">
<![CDATA[
var m = createComponent("component2")
function get_math(){
   return m
}
   ]]>
</script>
</component>

(Component2 as in previous example)

See Also

Script Component File Contents | <package> | <component>


Checking for Errors in Script Componets

Checking For Errors in Script Component Files

Because Windows® Script Components are used as COM components, they normally run silently. However, while you are developing your script component file, you might find it useful to know about errors in the file. You can specify three types of error checking:

  • Check for XML validity. For details, see Script Component Files and XML Conformance.
  • Allow notification for syntax and run-time errors. By default, if an error occurs in a script component file, a generic error message is displayed. By specifying error notification, you can have the script component parser display details about the error.
  • Allow debugging. By default, you cannot use the script debugger for script components. If you enable debugging, you can launch the script debugger in response to an error, by setting a breakpoint, or with a Stop (Microsoft® Visual Basic® Scripting Edition (VBScript)) or debugger (JScript) statement.

Setting Error Options

Specify error options as attributes of the XML <?component?> processing instruction.

To specify error checking

  • Include the <?component?> processing instruction at the top of the script component file (but after the optional <?XML ?> declaration) with one or more of the following attributes:
    • error Set this to true to display detailed error messages for syntax or run-time errors in the script component.
    • debug Set this to true to enable debugging. If this debugging is not enabled, you cannot launch the script debugger for a script component in any way.

For example, the following enables all three error reporting options:

<?component error="true" debug="true"?>
Tip Turn error reporting off before deploying your script component to a production environment.

See Also

Script Component File Contents | Using The Script Component Wizard | Creating Registration Information | Creating a Script Component Type Library | Script Component Files and XML Conformance


Script Component Files and XML Conformance

Windows® Script Components are XML files and should follow the XML version 1.0 conventions for how elements are defined in the file. Although XML elements superficially resemble HTML tags, XML is a more strictly defined protocol. For example, element names are case-sensitive.

To make it easier to create script components, the script component run-time (Scrobj.dll) allows you to specify how strictly you want the XML in your file to be interpreted. Script component XML can be interpreted fairly loosely, allowing the same sorts of variations in tags that HTML does.

However, you can also specify XML validation in your script component file, which causes the script component run-time to check that your script component file's XML conforms closely to the XML standard. If you will ever be using an XML editing tool to work with your script component, you should set XML validation.

When you specify XML validation, you must make sure that your script component file conforms to the following rules.

  • Element types and attribute names are case-sensitive. Element types and attributes names are usually all lowercase, except multipart names such as internalName. In XML files that conform closely to XML standards, all names must follow naming conventions exactly.
  • Attribute values require quotation marks. Values for attributes must be in single or double quotation marks. For example, without XML validation, you can specify language=JScript in a <script> element. But to follow XML rules, the same attribute would be language="JScript".
  • Reserved characters in script elements must be made opaque. Script elements frequently include greater than (<) and less than (>) symbols, the ampersand symbol (&), and other characters that are reserved in XML. If you are creating a closely conformant XML file, you must make sure that these reserved characters do not confuse the XML parser. You can individually mark characters with escape sequences (for example, specify "<" as "&lt;"), or you can make an entire script element opaque by enclosing it in a <![CDATA[ ...]]> section. Without XML validation, the script component XML parser treats <script> elements as opaque by default.
    Note Do not include a CDATA section in script if you have not specified closely conformant XML parsing. If you do, the script component will report errors when you try to register, instantiate, or call it.

For more details about XML standards, see the XML specification Web site and the Microsoft® XML Web site.

To specify XML conformance

  • Include the <?XML ?> declaration as the first element in your file:
    <?XML version="1.0" ?>
    Note If you create a script component using the Script Component Wizard, the <?XML ?> declaration is added to the file, and the script component's XML is parsed strictly.

If this element is missing, the script component run-time assumes that you do not want XML validation. However, you will probably not be able to work with the file using an XML editor.

See Also

Script Component File Contents | Using The Script Component Wizard | Checking For Errors in Script Component Files


Using Script Components

After you have created a Windows® Script Component, you can use it in your applications. Using script components is similar to using other COM components, however, each host application uses a slightly different way to instantiate COM components.

  • Registering a Script Component Register and unregister a script component.
  • Using a Script Component in an Application Create an instance of a script component in a host application.
  • Handling Script Component Events in the Host Application Detect and respond to custom script component events.


Registering a Script Component

To register a Windows® Script Component, you must have the script component run-time Scrobj.dll available, and it must be registered on your computer. When you install the script component package from the Microsoft® Scripting Technologies Web site, Scrobj.dll is automatically loaded and registered on your computer.

Note Registration is not required if you are creating a script component to be called via DHTML Behaviors, because Microsoft®Internet Explorer 5.0 can use this type of script component without prior registration.

This topic provides information about:

  • Registering a Script Component
  • Registering a Script Component for Remote Instantiation
  • Unregistering a Script Component

Registering a Script Component

You can register a script component on a local computer using a variety of methods.

To register a script component

  • In Windows Explorer, right-click the script component (.wsc) file, and then choose Register.

    –or–

  • Use the new version of Regsvr32.exe that ships with the script component package, and use this command:
    regsvr32 URL/component_name.wsc

    For example, to register a script component called MyComponent.wsc, use syntax such as this:

    regsvr32 file:\\myserver\MyComponent.wsc

    -or–

  • If you do not have the version of Regsvr32.exe that ships with the script component package, use the existing version and register the script component run-time DLL using syntax such as the following:
    regsvr32 scrobj.dll /n /i:URL/component_name.ext

    For example, to register a script component called MyComponent.wsc, use syntax such as this:

    regsvr32 scrobj.dll /n /i:http://myserver/MyComponent.wsc

Registering a Script Component for Remote Instantiation

If you intend to create a remote instance of a script component, the script component must be registered on the remote computer where it resides. You must also register it on each local computer from which you intend to instantiate the script component, so that DCOM can have a starting point in the registry from which to find and instantiate the remote script component.

To register a script component for remote instantiation

  1. Determine the program ID and class ID of the script component to be instantiated remotely.
    Note The script component must have the same class ID on both the local and remote computers, so you must provide a class ID in the script component's <registration> element.
  2. On each local computer, create the following registry entry:
    HKEY_CLASSES_ROOT\componentProgID

    where componentProgID is the program ID of the script component to instantiate.

  3. Under the new entry, create the CLSID key and set its value to the class ID of the script component, enclosing the class ID in brackets.
    Tip An easy way to create the proper registry information is to register the script component on the server where it will be instantiated. Then using Regedit.exe, locate the HKEY_CLASSES_ROOT\componentProgID entry. From the Registry menu, choose Export Registry File, which creates a .reg file. This file can be distributed to local computers, and users can simply run the file to create the appropriate registry entries.

Unregistering a Script Component

If you no longer need to have a script component registered on your computer, you can unregister it using one of these methods:

  • Right-click the script component file name in Windows Explorer, and then choose Unregister.
  • Run Regsvr32.exe with the -u flag.

See Also

Creating Registration Information | Script Component File Contents | Using a Script Component in an Application


Using a Script Component in an Application

After creating a Windows® Script Component, you can use it as you would any COM component, by calling it from a host application such as Microsoft® Visual Basic®, C++, Microsoft® Internet Explorer, or other applications.

Note Script components written for DHTML Behaviors are instantiated differently than traditional COM objects. For details, see Using DHTML Behaviors on the Microsoft Site Builder Network (SBN) Web site.

There are a variety of options for creating an instance of the script component, depending on the host application, the type of script component you are using, and where the script component is deployed. The primary difference, however, is whether you want to create an instance of the script component locally (on the same computer as the application) or remotely (on another computer).

In either case, there are a few points to bear in mind. If you create an instance of the script component and change the .wsc file while using that instance, your instance of the component is not updated. To update it, create a new instance of the script component.

The exact properties and methods you can use are defined by the <public> element and by scripts in the script component file. If you are working in an environment that supports statement completion, such as Visual Basic, you can see a script component's properties and methods if you generate and use a type library. For details, see Creating a Script Component Type Library.

If your attempt to create an instance of the script component fails, a likely cause is a syntax or run-time error in the script component file. A parsing error in any XML element (including the <registration> element) can cause the instantiation to fail. While you are developing your script component file, set error checking options in the <?component?> processing instruction as described in Checking For Errors in Script Component Files.

Tip To make it easier for the host application to know about the COM interfaces exposed by a script component, the script component run-time can generate a type library, which contains information about the properties, methods, and events available in the script component. For details, see Creating a Script Component Type Library.

Creating Local Instances of Script Components

If the script component is installed on the same computer as the host application, you can register the script component as its own component as described in Registering a Script Component. You can then use the host application's normal means for creating an object instance, such as the CreateObject function. For example, to create an instance of the script component that was registered with the program ID Component.MyComponent in Visual Basic, use a statement such as this:

Set oComponent = CreateObject("Component.MyComponent")
Note If your host application is Visual Basic and you want to handle events fired by the script component, you must bind the object early with a Dim statement that includes the WithEvents keyword, such as the following:
Dim WithEvents scMyComponent As MyComponent
Private Sub Command1_Click()
Set scMyComponent=CreateObject("MyComponent")
End Sub
Note For details, see Handling Script Component Events in the Host Application. This is not necessary if you do not intend to write handlers for script component events.

On a Web page, you can use the <OBJECT> tag to create an instance of the script component. You must know the class ID of the script component and include it in the <OBJECT> tag, as in the following example:

<OBJECT
   ID="oComponent"
   CLASSID="clsid:855c8606-49ba-11d2-a428-00c04f8ec80b">
</OBJECT>

If the script component is not registered on the local computer, you can use the script component moniker to create an instance of it. The moniker is supported in functions such as GetObject. The script component run-time, Scrobj.dll, must be registered on the local computer.

Note The GetObject function is not supported for script components in Microsoft® Internet Explorer for security reasons.

For example, the following illustrates how to call the Visual Basic GetObject function to create an instance of an unregistered script component:

Set oComponent = GetObject("script:c:\COM\MyComponent.wsc")

If the .wsc file referenced by the moniker contains more than one script component, you can specify the script component to instantiate by adding its name to the file name with a hash mark (#) as a delimiter. The following creates an instance of the script component whose ID is "math" contained in the file MyComponent.wsc:

Set oComponent = GetObject("script:c:\COM\MyComponent.wsc#math")

Using a URL moniker allows you to create an instance of a script component that resides on another computer, such as a Web server. Use a complete URL (with HTTP protocol) as the location for the script component, as in the following example:

Set oComponent = GetObject("script:http://myserver/MyComponent.wsc")

Internet Explorer 5.0 supports DHTML Behavior syntax for creating instances of script components, which works somewhat differently than the traditional syntax for instantiating objects and will ensure that the script component cannot access potential unsafe system objects. For an example, see Using DHTML Behaviors on the Microsoft Site Builder Network (SBN) Web site.

Creating Remote Instances of Script Components

If the remotable attribute of a script component's <registration> element has been set to "true," the script component can be instantiated remotely from another computer using Distributed COM (DCOM).

Both computers must have basic DCOM installed. A computer is correctly configured with DCOM if it is running any of the following:

  • Windows NT 4.0
  • Windows 95 running Internet Explorer 4.0
  • Windows 95 with the OEM Service Release 2 (OSR2) or later. For details, see the Windows 95 OSR2 page on the Microsoft® Web site.
  • Windows 95 with DCOM for Windows 95, version 1.2. For details, see the DCOM for Windows 95 page on the Microsoft® Web site.

The script component itself must be deployed as follows:

  • On the local computer, you do not require either the script component itself (.wsc file) or the script component run-time (Scrobj.dll) at the time you instantiate the script component. However, you must have a reference to the remote script component in the local Windows registry for DCOM. For details, see Registering a Script Component.
  • On the remote computer, you require the script component and the script component runtime. Both must be registered.

When you create an instance of a remote script component, it works within your application as if it were a local object; you call its methods and get and set its properties normally. However, the remote script component's script runs on the remote machine and has access to that machine's resources (within any limitations imposed by security, and so forth). Communication between the host application on the local machine and the script component on the remote machine is handled automatically and invisibly by DCOM.

To create a remote instance of a script component, call the CreateObject method, passing it the name of the remote computer as a parameter.

Note The ability to use CreateObject for instantiating remote script components requires Visual Basic 6.0 or later or VBScript 5.0 or later.

The following Visual Basic example shows how to do this on a computer named "myserver":

Set newS = CreateObject("Component.MyComponent", "myserver")
Note There can be a slight delay when you first instantiate a remote script component while DCOM establishes communication between the computers.

See Also

Creating Registration Information | Creating Script Components | How Script Components Work | Introducing Script Components | Registering a Script Component


Handling Script Component Events in the Host Application

Most host applications can receive Windows® Script Component events as they do any other events. However, some host applications require some setup before they can receive script component events.

Note If you are creating a Behavior script component, events are exposed using the DHTML object model. For details, see Exposing Custom Events in Behavior Script Components.

In Visual Basic, for example, you must use early (compile-time) binding to the component in order to receive events. Early binding requires a type library, so you must have generated a type library for the script component. For details, see Creating a Script Component Type Library. In addition, when you declare the object variable for the component, you must specify the WithEvents keyword. (The class name used in the Dim statement is the ID that you assigned in the script component's <component> element.)

An example in Visual Basic might look like this:

Dim WithEvents Scriptlet1 as MyScriptlet
Set Scriptlet1 = CreateObject("MyScriptlet")
Sub Scriptlet1_namechanged
   MsgBox("Value of name property changed")
End Sub

See Also

Exposing Events


Implementing a Script Component

Implementing ASP Script Components

Using a Windows® Script Component, you can include the functionality of Active Server Pages (ASP). Doing so allows you to isolate server script into a component that can be easily called from ASP pages and which makes it easy to reuse ASP code. For example, you might have several ASP pages that process forms. Rather than implement all the form-processing logic directly in each ASP page, the ASP pages could all call a script component with form-handling logic that you create.

To create an ASP script component, create a script component normally, as described in Script Component File Contents. Use the <implements> element to implement the ASP interface handler, setting the type attribute of the <implements> element to "ASP." Doing so provides the means for accessing ASP objects: Response, Request, Server, Session, and Application. In an ASP script component, you can use these objects as you would directly in an ASP page. The ASP interface handler is built into the script component run-time (Scrobj.dll), so no external interface handler is required.

When the script component runs, it uses the same namespace as the ASP page that called it. The script component can access the Request and Server objects as if it were in the ASP page that called it. The script component also has access to the same Session and Application variables that the calling ASP page does. Similarly, if the ASP script component calls a method on the Response object, the result of these calls is available in the calling page. For example, if you call Response.Write, the output is directed to the calling ASP page.

The following shows a simple ASP script component that exposes a property and a method. The applicationVar1 property makes available the hypothetical Application variable called Var1. The AddDate method outputs the current date into the calling ASP page.

Note A CDATA section is required to make the script in the <script> element opaque. For details, see Script Component Files and XML Conformance.
<component id="ASPScriptlet">
<registration progid="ASPScriptlet"/>

<public>
   <property name="applicationVar1"/>
   <method name="AddDate"/>
</public>

<implements type="ASP"/>
<script language="VBScript">
<![CDATA[
dim applicationVar1
applicationVar1 = Application("Var1")
Sub AddDate()
   Response.Write(Date)
End Sub
]]>
</script>
</component>

The calling ASP page might look like this:

<HTML>
<HEAD>
<TITLE>Testing the Script Components ASP Handler</TITLE>
</HEAD>
<BODY BGCOLOR="#FFFFFF">
<H1>Testing the ASP Handler</H1>
<%Set wscASP = CreateObject("ASPScriptlet")%>
<P>The current date is <%= wscASP.AddDate()%></P>

<P>The value of the Application(Var1) variable is <%= wscASP.applicationVar1%></P>

</BODY>
</HTML>


Implementing DHTML Behavior Script Components

Windows® Script Components provide a lightweight, easily maintainable way to create components for implementing DHTML Behaviors available in Microsoft® Internet Explorer 5.0. Using a script component allows script developers to implement behaviors using Microsoft® Visual Basic® Scripting Edition (VBScript), Microsoft® JScript® (ECMAScript), or any third party scripting language that supports the Microsoft® ActiveX® Scripting interfaces.

For general information about DHTML Behaviors, see http://msdn.microsoft.com/workshop.

By creating Behavior script components, you can:

  • Expose behaviors by binding functions in the script component to events raised in the containing document, either for specific elements or for the DHTML document or DHTML window objects.
  • Define layouts, which contain HTML text that is inserted into the containing document when the behavior is called.
  • Expose custom properties and methods that extend the set of members for an element in the containing page.
  • Expose custom events which the script component can fire at any time. For example, a script component can fire a custom event after changing the contents of a DHTML element on the page.
  • Bind a script component function to certain standard events such as when the document is loaded or when the content of the element changes.

In this section you will find information about the following:

  • Creating a Behavior Script Component See what elements to put into a Behavior script component file, how to share information with the containing document, what DHTML features apply to Behavior script components, and what to watch for when scripting.
  • Exposing Properties and Methods in Behavior Script Components Create properties and methods that extend those already available in DHTML elements.
  • Exposing Custom Events in Behavior Script Components Expose and fire events from the script component to the containing document.
  • Behavior Handler Reference A list of XML elements, properties, and methods used in Behavior script components.

See Also

The "DHTML Behaviors" and "Using DHTML Behaviors" topics on the Site Builder Network (SBN) Workshop on the Microsoft Web site provide general


Creating a Behavior Script Component

Creating a Behavior script component is similar to creating any other kind of script component, except that you are linking Microsoft® Internet Explorer events to script that is run in response to those events.

This topic is divided into the following sections:

  • Creating a Behavior Script Component File
  • Behavior-Related Enhancements to the DHTML Object Model
  • Getting Event Parameters in the Script Component
  • Scope Rules
  • Timing Considerations

Creating a Behavior Script Component File

A Behavior script component includes an <implements> element that specifies the Behavior interface handler. Within the <implements> element, you use:

  • <attach>elements to bind events from the containing document to functions created in a separate <script> element in the script component.
  • <layout>elements to define HTML text to be inserted into the containing document.
  • <event>elements to define custom events that will be fired by the script component.

Behavior script components can also include custom properties and methods that extend those already available for the element in the containing document. For details, see Exposing Properties and Methods in Behavior Script Components.

The following example shows a Behavior script component that changes the color of an element in the containing page whenever the mouse is passed over the element. To do this, the sample binds the DHTML onmouseover and onmouseout events to functions in the script component that set the element's DHTML style attribute. The sample also sets the document's link color when the document is initialized by binding to the DHTML window object's onload event.

In addition to binding events to script, the script component also inserts text into any <H1> elements in the containing document that are linked to this script component. Finally, it exposes and fires an event called onchange, which extends the DHTML window object's event object with a custom property called newvalue.

Note A CDATA section is required to make the script in the <script> element opaque. For details, see Script Component Files and XML Conformance.
<?XML version="1.0"?>
<component>
<implements type="Behavior">
   <comment>The following will cause the do_nmousedown and
   do_mouseout functions to be called when the mouse is
   passed over the element in the containing document.</comment>

   <attach event="onmouseover" handler="do_onmouseover"/>
   <attach event="onmouseout" handler="do_onmouseout"/>

   <comment> This will call the init function when the onload
   event of window is fired.</comment>

   <attach for="window" event="onload" handler="docinit"/>

   <comment>The following defines HTML text that will appear in
   the containing document.</comment>

   <layout>
      <h1>This is the HTML to show in the element</h1>
   </layout>

   <comment>The following defines a custom event that is fired
   from within the script component by the fireEvent method.</comment>

   <public>
      <event name="onchange"/>
   </public>

</implements>
<script language="JScript">
<![CDATA[
var normalColor, normalSpacing;
function do_onmouseover(){
   // Save original values.
   normalColor = style.color;
   normalSpacing= style.letterSpacing;
   style.color = "red";
   style.letterSpacing = 2;
   oEvent = createEventObject();
   oEvent.newcolor = "red";
   fireEvent("onchange",oEvent);
}
function do_onmouseout(){
   // Reset to original values.
   style.color = normalColor;
   style.letterSpacing = normalSpacing;
}

function docinit(){
   document.linkColor = "red";
}
]]>
</script>
</component>

There are a few things to point out in the preceding code:

  • From a script component procedure, the implied this pointer in an event handler refers to the containing function, not to the element on which the event is being fired.
  • Just as in an HTML page, it is possible to place inline script within a <script> in a script component. In this instance, the global variables normalColor and normalSpacing are defined in inline script.
    Note Inline script is executed even before the behavior is applied to the element, which limits what statements can be executed in inline script. For example, if the same behavior in the example exposed a property called hiliteColor, the inline script could refer to hiliteColor directly (in other words, it resolves against the script component's namespace). It is illegal, however, to refer to hiliteColor as Behavior.element.hiliteColor from an inline script, because at that point, the behavior has not yet been applied to the element. For more information, see Scope Rules and Timing Considerations later in this topic.

Behavior-Related Enhancements to the DHTML Object Model

The following enhancements were made to the DHTML object model for Microsoft® Internet Explorer 5 in order to add support for behaviors.

  • The cascading style sheet (CSS) behavior attribute specifies the location of the behavior.
  • The DHTML attachEvent and detachEvent methods enable a Behavior script component to receive event notifications from the containing page, by specifying a function that gets called whenever the event fires on the object.
  • The DHTML uniqueID property enables a behavior script component to assign an ID to the element. This can be useful in cases where a script component injects code into the containing page and needs to specify the ID of the element to which the behavior is being applied.

Getting Event Parameters in the Script Component

In DHTML, the DHTML event object provides information about the event. Although in DHTML the event object is accessible to event handlers through the DHTML window object, in a behavior script component the event object is passed in as a parameter to the event handler.

The following code from a hypothetical calculator script component demonstrates keyboard and mouse events bound to a script component function called doCalc. The doCalc function uses the event object to get information about the conditions under which the event was fired.

Note A CDATA section is required to make the script in the <script> element opaque. For details, see Script Component Files and XML Conformance.
<implements type="Behavior">
   <attach event="onclick" handler="doCalc"/>
   <attach event="onkeydown" handler="doCalc"/>
</implements>

<script language="jscript">
<![CDATA[
function doCalc(oEventParam){
   oElement = oEventParam.srcElement;
   if(oEventParam.type == "keydown"){
      sVal = KeyCodeToChar(oEventParam.keyCode);
   }
   else{
      if (oEventParam.srcElement.type != "button"){
         return;}
      sVal = stripBlanks(oEventParam.srcElement.value);
   }
}
// other script here
]]>
</script>

Scope Rules

When working with script components, you actually work with three namespaces: the behavior, the element, and the containing document. Scope rules define the order in which name conflicts are resolved in a behavior script component. A name will be resolved in this order:

The name is resolved to one defined by the behavior anywhere in the script component, whether a variable, a behavior-defined property, a method, or an event.

If the name is not resolved successfully, it is resolved to a property, method, or event that applies to the element.

Finally, the name is resolved to the name of a property, method, or event that applies to the window object in the containing page.

In the following example, note how the names have been resolved, using the scope rules defined above:

  • normalColor Resolves to the variable defined by the behavior at the top of the script.
  • style Resolves to the style property of the element in the containing document.
    <implements type="Behavior">
   <attach event="onmouseover" handler="do_onmouseover"/>
   <attach event="onmouseout "handler="do_onmouseout"/>
</implements>

<script language="JScript">
<![CDATA[
var normalColor, normalSpacing;
function event_onmouseover()
{
   // Save original values.
   normalColor = style.color;
   normalSpacing = style.letterSpacing;

   style.color = "red";
   style.letterSpacing = 2;
}
function event_onmouseout()
{
   // Reset to original values.
   style.color = normalColor;
   style.letterSpacing = normalSpacing;
}
]]>
</script>

Timing Considerations

When creating behaviors, it is important to know when the behavior is applied to the element. Until the behavior has been applied, scripts cannot have access to the values of behavior-defined properties that might be set in the document.

Because the behavior is encapsulated in a separate file from the HTML document, it is downloaded separately from the rest of the document. As the document and behavior are parsed and loaded, the behavior receives notifications of progress through the function specified with the attachNotification method. Currently, the behavior is notified with a "contentChange" or a "documentReady" notification. The "contentChange" notification is sent when the content of the element to which the behavior has been attached has been parsed, and any time thereafter that the content of the element is changed. The "documentReady" notification is sent when the document has been downloaded and parsed.

Because inline script in the script component file is executed as soon as the behavior is instantiated, the values of behavior-defined attributes and properties that are being set in the document may not be accessible from an inline script. However, these properties will be available as soon as the first "contentChange" notification is sent.

See Also

Exposing Properties and Methods in Behavior Script Components | Exposing Custom Events in Behavior Script Components | Behavior Handler Reference


Exposing Properties and Methods in Behavior Script Components

Behavior script components can expose custom properties and methods in a manner similar to Automation script components. Behavior script component properties and methods extend the properties and methods available to elements in the containing page. For example, you might create a behavior script component that changes the color of an element when the mouse is passed over it. By defining a property in the script component, you can make available a custom property in the document, perhaps called hiliteColor, that allows the Web page author to set the color with which text gets highlighted.

A behavior can override an element's default behavior by exposing a property or method of the same name as that which is already defined for the element.

Properties and methods are defined in a <public> element separate from the <implements> element used to specify the Behavior handler. For details, see Exposing Properties and Exposing Methods.

Exposing a Property

Properties are exposed in a <public> element, as in any script component. The following script component fragment shows a Behavior script component that exposes the custom property hiliteColor. If the containing page does not specifically set the property's value, the default is set to "red."

Note A CDATA section is required to make the script in the <script> element opaque. For details, see Script Component Files and XML Conformance.
<public>
   <property name="hiliteColor"/>
</public>

<implements type="Behavior">
   <attach for="window" event="onload" handler="event_onload">
</implements>

<script language="JScript">
<![CDATA[
   var hiliteColor;
   function event_onload(){
      // Initialize the properties.
      if (hiliteColor == null){
         hiliteColor = "red";}
   }
   // Further script here.
]]>
</script>

Exposing a Method

Exposing a method in a Behavior script component is identical to doing so in an Automation script component. For details, see Exposing Methods. In a Behavior script component, methods exposed in the script component extend those already available for the element in the containing document.

See Also

Exposing Custom Events in Behavior Script Components


Exposing Custom Events in Behavior Script Components

Behavior script components, like Automation script components, can expose custom events that are fired inside the script component and can be handled in the containing document. An event is declared in the <public> element as in the following:

<public>
   <event name="onResultChange" />
</public>

The event can then be fired by calling the fireEvent method in script:

<script language="JScript">
   // Other code here.
   fireEvent("onResultChange");
   // Other code here.
</script>

A behavior can override an element's default behavior by exposing an event of the same name as one that is already defined for the element. For example, a behavior that exposes an onclick event can override the element's default onclick event.

Getting and Setting Custom Event Information

Your custom script component event can get access to the DHTML event object, which maintains event-specific information. You can use this object to:

  • Change existing event object properties, such as keyCode, that have been set by in the calling event.
  • Create new (expando) properties of the event object in order to pass information about your event back to the containing event.

In your script component code, call the createEventObject method to create a new instance of an event object, and then set one or more properties on the new event object. When you call the fireEvent method, you can pass the new event object with the event name.

To create a new expando property, simply name it when assigning its value in your script. The following shows how you can create a new property called myprop for the event object:

oEvent = createEventObject();
oEvent.myprop = "a new value"
Note You can create expando properties only if you are using Microsoft® JScript® (or JavaScript). This feature is not supported in Microsoft® Visual Basic® Scripting Edition (VBScript).

Example

The following script component fragment is derived from a calculator script component sample. The sample defines a custom onResultChange event that is fired to the containing document whenever the result changes. Event-specific information (the actual calculation result) is passed via the expando property called result.

Note A CDATA section is required to make the script in the <script> element opaque. For details, see Script Component Files and XML Conformance.
<public>
   <event name="onResultChange" />
</public>

<implements type="Behavior">
   <attach event="onclick" handler="doCalc"/>
</implements>

<script language="JScript">
<![CDATA[
function doCalc()
{
   // Code here to perform calculation. Results are placed into
   // the variable sResult.
   oEvent = createEventObject();
   oEvent.result = sResult;
   fireEvent("onResultChange",oEvent);
}
]]>
</script>

The following shows what the containing page looks like. When the onResultChange event fires, the results of the calculation are extracted from expando property result of the DHTML window.event object and displayed in the resultWindow <DIV> element.

<HTML>
<HEAD>
<xml:namespace prefix="LK" />
<style>
   LK\:CALC {behavior:url(calc.wsc)}
</style>
<script language="JScript">
function showResults(){
   resultWindow.innerText=window.event.result;
}
</script>
</HEAD>

<LK:CALC id="myCalc" onResultChange="showResults()">
<TABLE>
<TR>
   <DIV ID=resultWindow
      STYLE="border: '.025cm solid gray'"
      ALIGN=RIGHT>0.</DIV>
</TR>
<TR>
   <TD><INPUT TYPE=BUTTON VALUE=" 0 "></TD>
   <TD><INPUT TYPE=BUTTON VALUE="+/-"></TD>
   <TD><INPUT TYPE=BUTTON VALUE=" . "></TD>
   <TD><INPUT TYPE=BUTTON VALUE=" + "></TD>
   <TD><INPUT TYPE=BUTTON VALUE=" = "></TD>
<TR>
</TABLE>
</LK:CALC>
</HTML>

See Also

Exposing Properties and Methods in Behavior Script Components


Script Component Reference

When creating Windows® Script Component files, use XML elements to define different parts of your script component, such as the registration information, scripts, and objects that you intend to reference in your script component's code. You can also call methods to perform tasks in the script component. The following table lists the available XML elements and methods.

Note Specific handlers, such as the Behavior handler, expose additional XML elements, methods, and other members. For more information, refer to the documentation for specific handlers.

XML Elements

  • <?component?>
  • <?XML ?>
  • <comment>
  • <component>
  • <event>
  • <implements>
  • <method>
  • <object>
  • <package>
  • <property>
  • <public>
  • <reference>
  • <registration>
  • <resource>
  • <script>

Methods and Functions

  • createComponent
  • fireEvent
  • getResource


<?component?>

Specifies attributes for error handling.

<?component error="flag" debug="flag" ?>

Values

flag
A Boolean value: "true" or "false," 1 or 0, or "yes" or "no." The default value for all attributes is false.

Remarks

Because script components are used as COM components, they normally run silently. However, while you are developing your script component file, you might find it useful to be notified about errors in the file. You can specify these types of error notification:

  • error Set this to true to allow error messages for syntax or run-time errors in the script component file.
  • debug Set this to true to enable debugging. If this debugging is not enabled, you cannot launch the script debugger for a script component in any way.

Example

<?component error="true" debug="true" ?>

See Also

Checking For Errors in Script Component Files | Script Component File Contents


<?XML ?>

Indicates that the file should be parsed as XML.

<?XML version="version" standalone="DTDflag" encoding="encname" ?>

Values

version
A string in the form n.n specifying the XML level of the file. Use the value 1.0.
DTDflag
(Optional) A Boolean value indicating whether the XML file includes a reference to an external Document Type Definition (DTD). Script component XML files do not include such a reference, so the value for this attribute is always "yes."
encname
(Optional) A string that describes the character set encoding used by the XML document. The string may include any of the character sets supported by Microsoft® Internet Explorer.

Remarks

This declaration must be the first element (including white space) in the file.

The existence of this declaration puts the script component compiler into strict XML mode where element types and attribute names are case-sensitive, attribute values must be in single or double quotes, and all elements are parsed. If the declaration is not included, the compiler allows looser syntax.

In general, you should include this declaration and follow XML conventions if your script component file will ever be edited in an XML-conformant editor.

Example

<?XML version="1.0" standalone="yes" encoding="UTF-16" ?>

See Also

Script Component Files and XML Conformance


<comment>

<comment> Element

Marks text in a script component file that should be ignored.

<comment>
   text here
</comment>

Remarks

Use the <comment> element inside other XML elements to enclose text that is not markup and not data, but that you want to include for other purposes, such as documentation.

Example

The following script component fragment shows a <comment> element inside a <public> element.

<public>
   <comment>
      This implements an Automation component with the
      method "random" and the property "uppercaseName"
   </comment>
   <method name="random" internalName="getRandomNumber"/>
   <property name="uppercaseName">
      <get internalName="get_ucname"/>
      <put internalName="put_ucname"/>
   </property>
</public>

See Also

Script Component File Contents


createComponent Function

Returns a reference to another script component in the same package (.wsc file).

value = createComponent(componentID)

Values

componentID
The unique identifier for the script component to create an instance of.

Remarks

By calling the createComponent method, you can include the functionality of another script component in the same file. For more details, see Referencing Another Script Component in the Same Package.

Example

The following example shows two script components in the same package. The first script component calls the second script component when its math method is called.

Note A CDATA section is required to make the script in the <script> element opaque. For details, see Script Component Files and XML Conformance.
<package>
<component id="component1">
<registration progid="component.FrontEnd"/>
<public>
   <method name="math"/>
</public>
<script language="JScript">
<![CDATA[
function math(){
   return createComponent("component2")
}
]]>
</script>
</component>

<component id="component2">
<registration progid="component.Math"/>
<public>
   <method name="add"/>
</public>
<script language="JScript">
<![CDATA[
function add(n1, n2){
   return n1+n2;
}
]]>
</script>
</component>
</package>

After registering this package, you can use it as illustrated in the following commands:

set o1 = CreateObject("component.FrontEnd")
Set o2 = o1.math()
msgbox(o2.add(4,5))

See Also

Referencing Another Script Component in the Same Package


<event>

<event> Element

Declares the name of a custom event that can be fired from within the script component.

<event name="name" dispid="dispid"/>

Values

name
The name of an event being exposed.
dispid
(Optional) A numeric value specifying the dispatch ID for the event, which is compiled into the component's type library and then used by the host application to bind to events. If you do not specify a dispatch ID, it is assigned automatically to the event when the type library is created. Specifying your own dispatch ID allows you to make sure the dispatch ID for an event is always the same, even if you recreate the type library. It also allows you to map your event to a specific dispatch ID, such as those used by convention in COM. For more details, see Exposing Events.

Remarks

To fire an event, use the fireEventmethod.

Example

The following script component fragment defines two events (namechanged and querydone) and shows how to fire one of them (namechanged).

Note A CDATA section is required to make the script in the <script> element opaque. For details, see Script Component Files and XML Conformance.
<public>
   <property name="name">
      <get/>
      <put/>
   </property>
   <event name="namechanged"/>
   <event name="querydone" dispid="22"/>
<public>

<script language="VBScript">
<![CDATA[
var gName
Sub get_lowercaseName()
   get_lowercaseName = name
End Sub

Sub put_lowercaseName(newLCName)
   gName = newLCName
   fireEvent("namechanged")
End Sub
   ]]>
</script>

See Also

<method> Element | <property> Element | Exposing Events | Exposing Methods | Exposing Properties | fireEvent Method


fireEvent Method

Sends notification of a custom event from the script component to the host application.

fireEvent(eventName[,...])

Values

eventName
The name of the event as defined in the <event> element.

Remarks

You can only fire events if they have been declared in the <public> element.

Note The Behavior handler exposes a fireEvent method that is similar to the Automation handler version, but which includes support for event objects. For details, see Exposing Custom Events in Behavior Script Components.

Example

The following shows a fragment of a script component that defines the event namechanged and shows how to fire it.

Note A CDATA section is required to make the script in the <script> element opaque. For details, see Script Component Files and XML Conformance.
<public>
   <property name="name">
      <get/>
      <put/>
   </property>
   <event name="namechanged">
</public>

<script language="VBScript">
<![CDATA[
var name
Sub get_lowercaseName()
   get_lowercaseName = name
End Sub

Sub put_lowercaseName(newLCName)
   name = newLCName
   fireEvent("namechanged")
End Sub
]]>
</script>

See Also

<event> Element | Exposing Events | fireEvent (Behavior)


getResource Function

Gets the value of a resource defined with the <resource> element.

value = getResource(resourceID)

Values

resourceID
A unique identifier for the resource within the script component.

Remarks

The <resource> element allows you to isolate strings or numbers in your script component that you want to intermingle with script in your script component. For example, resource elements are typically used to maintain strings that might be localized into another language. You can use the getResource function in the script component's script to extract the contents of a <resource> element.

Example

The following script component fragment defines a resource (called errNonNumeric) and how to use it in script.

Note A CDATA section is required to make the script in the <script> element opaque. For details, see Script Component Files and XML Conformance.
<public>
   <method name="random" internalName="getRandomNumber"/>
</public>
<resource id="errNonNumeric">Non-numeric value passed</resource>

<script language="VBScript">
<![CDATA[
Function getRandomNumber(upperBound)
   If IsNumeric(upperBound) Then
      getRandomNumber = Cint(upperBound * Rnd + 1)
   Else
      getRandomNumber=getResource("errNonNumeric")
   End If
End Function
]]>
</script>

See Also

Referencing Other Components


<implements>

<implements> Element

Specifies additional COM interface handlers for a script component.

<implements type="COMHandlerName" [id="internalName"] [default=fAssumed]>
   handler-specific information here
</implements>

Values

COMHandlerName
The name of the interface handler to reference. Interface handlers are usually implemented as DLLs, which you must be sure are available and registered in the production environment for your script component. Some handlers, such as the Automation and ASP handlers, are built into the script component run-time (Scrobj.dll). Examples of available interface handlers include:
Interface handler | Description | How implemented
ASP | Allows a script component to get access to the Microsoft Internet Information Services (IIS) Active Server Pages (ASP) object model. | Built into Scrobj.dll
DHTML Behaviors | Allows a behavior script component to communicate with the containing page so it can fire events and access the DHTML object model. | Built into Scrobj.dll
internalName
(Optional) A name you can use to reference the handler in your script. By default, properties, methods, events, and other members of a script component are available in the global namespace. However, if there is a naming conflict between <implements> elements, the names can be disambiguated by prefixing them with the ID of the <implements> element to which they belong, as in the following:
<implements type="Behavior" id="sctBehavior">
   [...]
</implements>

[...]

<script language="JScript">
   // [...]
   sctBehavior.fireEvent("onResultChange",oEvent);
</script>
fAssumed
(Optional) A Boolean flag indicating that the internalName is assumed in scripts. The default value for this attribute is true, and members of the object model exposed by the handler are added to the global script namespace and can be accessed unqualified. You only need to include this attribute if you want to set it to false and therefore hide members of a specific <implements> element.

Remarks

Interface handlers extend the script component run-time. An interface handler is a compiled component (generally written in C++) that implements specific COM interfaces.

Script components by default implement the COM Automation interface (specifically, the IDispatchEx COM interface). The Automation object's properties, methods, and events are defined in the script component's <public> element. Because the Automation handler is implemented by default, you do not need to implement it with the <implements> element.

Script components can also implement additional COM interfaces by including an <implements> element. Inside the <implements> element, you specify information specific to the interfaces you are implementing. Each interface handler requires different information. For example, a Behavior script component can include <attach> and <layout> elements that are specific to the DHTML Behavior interface.

Example

<implements type="Behavior">
   <event name="onResultChange" />
</implements>

See Also

How Script Components Work | Script Component File Contents


<method>

<method> Element

Declares a method.

<method name="methodName" internalName="functionName" dispid=dispID>
   [<parameter name="parameterID"/>]
</method>

Values

methodName
The name of the method to expose.
functionName
(Optional) The name of the procedure (function or subroutine) in the script component file that implements the method. If you do not specify an internal name, methodName is used.
Tip In XML, you can implement elements that have no content (such as the <method> element) by closing the element with />.
dispID
(Optional) COM dispatch ID for the method. If no dispid is specified, the dispid is automatically generated. If the dispid is set to 0 (zero), the method becomes the script component's default method. For more information about dispids, see Exposing Events.
parameterID
If a parameter is explicitly declared for the method, identifies the parameter's name.

Remarks

A method is implemented as a procedure (function or subroutine) in a separate <script> element. The <method> element maps the name of the method to the procedure used to implement it.

You can optionally declare the parameters for your method. Doing so is not required, but exposes parameter information if you generate a type library for your script component (see Creating a Script Component Type Library).

Example

The following script component fragment defines two methods (factorial and random). The random method includes definitions for its parameters, and binds to a function called getRandomNumber.

Note A CDATA section is required to make the script in the <script> element opaque. For details, see Script Component Files and XML Conformance.
<public>
   <method name="factorial"/>
   <method name="random" internalName="getRandomNumber">
      <parameter name="upperBound">
      <parameter name="seed">
   </method>
</public>

<script language="VBScript">
<![CDATA[
   Function factorial(n)
      If isNumeric(n) Then
         If n <= 1 Then
            factorial = 1
         Else
            factorial = n*factorial(n-1)
         End If
      Else
         factorial = -2    ' Error code.
      End If
   End Function

   Function getRandomNumber(upperBound, seed)
      upperBound = CInt(upperBound)
      Randomize
      getRandomNumber = Cint(upperBound * Rnd(seed) + 1)
   End Function
]]>
</script>

See Also

<event> Element | <property> Element | Exposing Events | Exposing Methods | Exposing Properties


<object>

<object> Element

Defines objects that can be referenced by script.

<object id="objID" [classid="clsid:GUID" | progid="progID"] events="true|false"/>

Values

objID
A name by which the object can be referenced in your script. Object ID values must begin with a letter and can include letters, digits, and underscores (_). The object ID must be unique throughout the scope of the script component. For example, if you specify the name CObj, you can reference the object in your script this way:
x = CObj.Prop1
GUID
(Optional) A reference to the class ID (GUID) under which the object has been registered. Use "clsid:" followed by the class ID (without curly brackets). Either a classid or a progid attribute must be specified. For example:
classid="clsid:2154c700-9253-11d1-a3ac-0aa0044eb5f"
progID
(Optional) The program ID of the object, which can be specified as an alternative to the class ID. Either a classid or a progid attribute must be specified.
events
(Optional) An attribute that allows you to hook events from the object. By default, events is false. If the attribute is true, you can connect to any events the object may fire. You must add an event handler for each event that is to be handled.

Remarks

The <object> element provides a way to expose objects globally for use in scripting within the script component without having to use a function such as CreateObject(). Using an <object> element makes the object available with global scope, and allows scripting tools to provide statement completion for the object's members.

Example

The following script component fragment includes an <object> element to create an object reference to the ADODB.Connection object.

Note A CDATA section is required to make the script in the <script> element opaque. For details, see Script Component Files and XML Conformance.
<registration progid="ADOScriptlet"/>
<object id="cnn" progid="ADODB.Connection"/>
<public>
   <property name="cnnState"/>
   <method name="openconnection"/>
</public>

<script language="VBScript">
<![CDATA[
Dim cnnState
Function openconnection()
   cnn.ConnectionString =
      "driver={SQL Server};server=myserver;uid=sa;database=pubs"
   cnn.Open
   If cnn.State = 1 Then
      cnnState = "open"
      cnn.Close
   Else
      cnnState = "closed"
   End If
End Function
]]>
</script>

See Also

Script Component File Contents


<package>

<package> Element

Encloses multiple script component definitions.

<package>
   one or more script components here
</package>

Remarks

The <package> element is optional when a .wsc file contains only one script component definition.

Example

<package>
<component id="MyScriptlet">
   (script component information here)
</component>

<component id="MyOtherScriptlet">
   (script component information here)
</component>
</package>

See Also

Script Component File Contents


<property>

<property> Element

Declares a property.

<property name="propertyName" [internalName="propertyVariable"] />

–or–

<property name="propertyName">
   <get [internalName="getFunctionName"] />
   <put [internalName="putFunctionName"] />
</property>

Values

propertyName
The name of the property to expose. Unless you specify an internalName attribute, this name must match the name of a global variable that will be used to hold the property's value.
propertyVariable
(Optional) The name of the global variable in the scriptlet file's <script> element that will hold the value for propertyName. If you do not include the internalName attribute, the property value is maintained in a variable named the same as propertyName. Specifying the internalName attribute allows you to use different names for the property and its corresponding global variable.
getFunctionName
(Optional) The name of a procedure that is used to read the value of the property. If you include <get> element but no <put> element, the property will be read-only. If you include a <get> element but do not specify an internalName attribute, the method used to read the property value must have the name of the property plus the get_ prefix (for example, get_lastname).
putFunctionName
(Optional) The name of a procedure that is used to write the value of the property. If you include a <put> element but no <get> element, the property will be write-only. If you include a <put> element but do not specify an internalName attribute, the method used to read the property value must have the name of the property plus the put_ prefix (for example, put_lastname).
Tip In XML, you can implement elements that have no content (such as the <property> element) by closing the element with />.

Remarks

Properties can be exposed as simple values. In that case, the property is treated as a global variable inside the script component file.

You can also implement properties as procedures (functions or subroutines), which allows you to calculate a property value and to control whether a property is read-only, read-write, or write-only. In this technique, properties are implemented as a procedure (function or subroutine) in a separate <script> element. The <property> element maps the name of the property to the procedures used to implement it. The names of the procedures must match the internal names you specified in the <property> element.

When putFunctionName is called, it is passed one argument that contains the value to which to set the property.

In addition to the standard syntax shown above, you can use a shorthand notation to specify information what would otherwise be added using child tags. For example, if you want to declare a property with a "get" and "put" accessor of the same name as the property, you can use the following syntax:

<property name="myproperty" get put/>

which is functionally equivalent to:

<property name="myproperty">
   <get/>
   <put/>
</property>

If you wanted to explicitly name those accessors differently from the default, you can use the following syntax:

<property name="myproperty" get="testget" put="testput"/>

To specify a default property, include the attribute dispid="0" in the <property> element. For details, see Exposing Properties.

Example

The following script component fragment shows the definition for four properties (sname, age, dateOfBirth, and mstatus). The sname property is a simple value. The age property is read-only, and is implemented with the function readAge. The dateOfBirth property is read-write, and is implemented wih the functions readDOB and writeDOB. Finally, the mstatus property is implemented with the default functions get_mstatus and put_mstatus.

Note A CDATA section is required to make the script in the <script> element opaque. For details, see Script Component Files and XML Conformance.
<public>
   <property name="sname"/>
   <property name="age">
      <get internalName="readAge"/>
   </property>
   <property name="dateOfBirth">
      <get internalName="readDOB"/>
      <put internalName="writeDOB"/>
   </property>
   <property name="mstatus">
      <get/>
      <put/>
   </property>
</public>

<script language="VBScript">
<![CDATA[
Dim sname   ' Read-write sname property (no functions).
Dim gDOB   ' Global variable used to store date of birth.
Dim gMStatus   ' global variable used to store marital status.

Function readDOB()
   ' Gets value of dateOfBirth property.
   readDOB = gDOB
End Function

Function writeDOB(newDOB)
   ' Sets value of dateOfBirth property.
   If isDate(gDOB) Then
      ' Error checking.
      gDOB = newDOB
   End If
End Function

Function readAge()
   ' Calculates read-only age property.
   If isDate(gDOB) Then
      dobM = DatePart("m", gDOB)
      dobD = DatePart("d", gDOB)
      dobY = DatePart("yyyy", gDOB)
      todayY = DatePart("yyyy", Date)
      age = todayY - dobY

      ' Adjust if birthday has not yet occurred this year.
      bday = DateValue(dobM & "/" & dobD & "/" & todayY)
      If DateDiff("d", bday, DateValue(Date)) < 0 Then
         age = age - 1
      End If
      readAge = age
   End If
End Function

Function get_mstatus()
   ' Reads value of mstatus property.
   get_mstatus = gMStatus
End Function

Function put_mstatus(s)
   ' Writes value of mstatus property.
   If s = "M" Or s = "S" Then
      gMStatus = s
   Else
      gMStatus = "?"
   End If
End Function
]]>
</script>

See Also

<event> Element | <method> Element | Exposing Events | Exposing Methods | Exposing Properties


<public>

<public> Element

Encloses the script component's property, method, and event declarations.

<public>
   <property name="pname"/>
   <method name="mname"/>
   <event name="ename"/>
</public>

See Also

<event> Element | <method> Element | <property> Element | Exposing Events | Exposing Methods | Exposing Properties


<reference>

<reference> Element

Includes a reference to an external type library.

<reference [object="progID" |guid="typelibGUID"] [version="version"]>

Values

progID
The program ID from which the type library can be derived, which can include a version number (for example, ADO.Recordset.2.0). This can include the explicit program ID of a type library, or the program ID of the executable (such as a .DLL) that incorporates the type library. If you use the object attribute, you do not need to specify a version attribute, because the version can be inferred from the program ID.

If the object attribute is specified, you cannot also specify a guid attribute.

typelibGUID
The GUID of the type library to reference. If the guid attribute is specified, you cannot also specify an object attribute.
version
(Optional) The version number of the type library to use. It must be in the form <major version>[.<minor version>]. If a version is not specified, the default version is 1.0. If the object attribute is used to specify the type library and the version is not specified, the version is derived from the Registry key for the specified program ID. If none can be found, the default is 1.0.

Remarks

Referencing a type library in your script component allows you to use constants defined in the type library in scripts. The <reference> element looks up and makes available the type library associated with a specific program ID or type library name. Type library information can be available in .tlb, .olb, or .dll files.

The <reference> element should appear inside the <component> element. If there is more than one script component in the package, the type library applies to only the script component in whose <component> element it is declared.

Example

In the following script component fragment, referencing the type library for ADO (contained in the file MSAD015.DLL) allows you to use ADO constants such as adStateOpen in your scripts.

Note A CDATA section is required to make the script in the <script> element opaque. For details, see Script Component Files and XML Conformance.
<reference object="ADODB.Connection.2.0"/>
<registration progid="ADOScriptlet"/>
<public>
   <property name="cnnstate"/>
   <method name="openConnection"/>
   <method name="closeConnection"/>
</public>

<script language="VBScript">
<![CDATA[
Dim cnn
Dim cnnState
Function openConnection()
   Set cnn = CreateObject("ADODB.Connection")
   cnn.ConnectionString =
      "driver={SQL Server};server=myserver;uid=sa;database=pubs"
   cnn.Open
   If cnn.State = adStateOpen Then
      cnnState = "open"
   Else
      cnnState = "closed"
   End If
End Function

Function closeConnection()
   cnn.Close
   cnnState = "closed"
End Function
]]>
</script>

See Also

Referencing Other Components


<registration>

<registration> Element

Defines information used to register the script component as a COM component.

<registration progid="progID" classid="GUID" description="description"
   version="version" [remotable=remoteFlag]/>

–or–

<registration progid="progID" classid="GUID" description="description"
      version="version" [remotable=remoteFlag]>
   <script>
      (registration and unregistration script)
   </script>
</registration>

Values

progID
(Optional) A text name that programmers use to reference your script component when creating an instance of it. For example, if your script component's program ID is Component.MyComponent, you can create an instance of it in Microsoft® Visual Basic using a statement such as the following:

Set Component = CreateObject("Component.MyComponent")

Note Although a progid attribute is optional, you must include either a progid or a classid attribute (you can include both). If only the progid attribute is specified, the class ID is generated automatically. If only the class ID is created, then no progid is registered and the object can be created only by referencing the class ID directly.
GUID
(Optional) A GUID that you have generated using a class ID generation program (such as Uuidgen.exe). If you do not include a class ID, the registration program assigns a class ID to your script component.
description
(Optional) A text description of the script component that is stored in the registry and that is used in certain tools such as the Visual Basic object browser.
version
(Optional) A numeric version number that you assign. The version is appended to the program ID with a period (for example, MyComponent.1) when applications request a version-specific name. Use only numbers (decimal points are not allowed).
Note The registration attributes can appear in any order in the <registration> element.
remoteFlag
(Optional) A Boolean value indicating whether the script component can be instantiated remotely using DCOM. For details, see Creating Remote Instances of Script Components in the topic "Using a Script Component in an Application."

Remarks

After a script component is created, it can be registered using a program such as Regsvr32.exe, which reads the information in the <registration> element and writes it into the computer's Windows Registry. For example, a script component can be registered this way:

regsvr32 file:\\myserver\MyComponent.wsc
Note A <registration> element is not required in all cases. For example, a script component that implements the DHTML Behaviors interface handler in Microsoft® Internet Explorer 5.0 does not need to be registered, because Internet Explorer registers the behaviors as they are detected on the page. For details about registration requirements, see the documentation for the interface handler you are implementing and note also which host the script component will be used in.

If you do not include class ID information, the registration program assigns a class ID to your script component at the time it is registered. However, the script component will have a different class ID everywhere it is registered. It is highly recommended that you provide a class ID for the script component yourself, to ensure that your script component has the same class ID on all computers on which it is registered.

Allowing the registration program to create a class ID can cause problems if you use the script component with development tools that store class IDs. If the registration creates a new class ID each time, it will not match the the ID stored by the application.

You can optionally run scripts when a script component is registered and unregistered. To do so, include a <script> element within the <registration> element. To run script during registration, write a register( ) function. To run script when the script component has been unregistered, include an unregister( ) function.

Example

The following shows a typical <registration> element that includes both a prog ID and a class ID.

<registration
   progid="Component.TestScript"
   classid="{2154c700-9253-11d1-a3ac-0aa0044eb5f}"
   description="My Test Component"
   version="1"/>

The following registration element allows the script component to be instantiated via DCOM:

<registration>
   progid="Component.TestScript"
   classid="{2154c700-9253-11d1-a3ac-0aa0044eb5f}"
   version="1"
   description="My Test Component"
   remotable=true/>

The following example shows a <registration> element that includes script to be run when the script component is registered and unregistered.

Note A CDATA section is required to make the script in the <script> element opaque. For details, see Script Component Files and XML Conformance.
<registration
   progid="Component.TestScript"
   classid="{2154c700-9253-11d1-a3ac-0aa0044eb5f}">
   version="1"
   description="My Test Component">

   <script language="VBScript">
      Function register()
         MsgBox "Component 'My Test Component' registered."
      End Function
      Function unregister()
         MsgBox "Component 'My Test Component' unregistered."
      End Function
   </script>
   ]]>
</registration>

See Also

Creating Registration Information | Registering a Script Component


<resource>

<resource> Element

Isolates textual or numeric data that should not be hard-coded into the script component's scripts.

<resource id="resourceID">
   text or number here
</resource>

Values

ResourceID
A unique identifier for the resource within the script component.

Remarks

The <resource> element allows you to isolate strings or numbers in your script component that you want to intermingle with script in your script component. For example, resource elements are typically used to maintain strings that might be localized into another language.

To get the value of a resource, call the getResource function, passing it the ID of the resource you want to use.

Example

The following script component fragment defines a resource (called errNonNumeric) and demonstrates how to use it in script.

Note A CDATA section is required to make the script in the <script> element opaque. For details, see Script Component Files and XML Conformance.
<public>
   <method name="random" internalName="getRandomNumber"/>
</public>
<resource id="errNonNumeric">
   Non-numeric value passed
</resource>

<script language="VBScript">
<![CDATA[
Function getRandomNumber(upperBound)
   If IsNumeric(upperBound) Then
      getRandomNumber = Cint(upperBound * Rnd + 1)
   Else
      getRandomNumber=getResource("errNonNumeric")
   End If
End Function
]]>
</script>

See Also

Referencing Other Components


<script>

<script> Element

Defines the script component's behavior.

<script language="language">
   script here
</script>

Values

language
The name of the scripting language used in the script component file, such as Microsoft® Visual Basic® Scripting Edition (VBScript) or JScript.

Remarks

If XML validation is not enabled, the XML parser ignores all lines inside the <script> element. However, if XML validation is enabled by including the <?XML ?> declaration at the top of the script component file, the XML parser can misinterpret greater than (<), less than (>), and other symbols used in script as XML delimiters.

If you are creating a file that conforms closely to XML syntax, you must make sure that characters in your script element are not treated as XML reserved characters. To do so, enclose the actual script in a <![CDATA[ ... ]]> section. For details about XML validation, see Script Component Files and XML Conformance.

Note Do not include a CDATA section unless you also include the <?XML ?> declaration.

Example

<?XML version="1.0"?>
<component id="ScriptletFactorial">
<registration progid="Component.Factorial"/>
<public>
   <method name="factorial"/>
</public>

<script language="VBScript">
<![CDATA[
Function factorial(n)
   If isNumeric(n) Then
      If n <= 1 Then
         factorial = 1
      Else
         factorial = n * factorial(n-1)
      End If
   Else
      factorial = -2   ' Error code.
   End If
End Function
]]>
</script>
</component>

See Also

Script Component File Contents


<component>

<component> Element

Encloses an entire Windows Script Component definition.

<component id=componentid>
   script component information here
</component>

Values

componentid
A string that uniquely identifies the script component. This value is useful if a document contains multiple script components or when you are generating one type library for several script components. Identifiers must begin with a letter and can contain no spaces. The identifier must be unique within a script component package.

If specified, this value functions as the class name for the script component in the host application. For example, if you specify the component ID "MyComponent" in the <component> element, the script component is identified as the class MyComponent in the Visual Basic object browser. If no component ID is specified, the default value is ComponentCoClass.

Remarks

In script component files, an entire script component definition — including<registration>, <public> and <implements> elements — must appear inside a <component> element. If the file contains multiple script components, they must in turn be enclosed within a <package> element.

Example

The following shows a simple but complete script component that includes a factorial method and a name property.

Note A CDATA section is required to make the script in the <script> element opaque. For details, see Script Component Files and XML Conformance.
<?XML version="1.0"?>
<component>
<registration>
   description="My Test Component"
   progid="Component.TestScript"
   version="1"
   classid="{2154c700-9253-11d1-a3ac-0aa0044eb5f}"
</registration>

<public>
   <property name="name"/>
   <method name="factorial"/>
</public>

<script language="VBScript">
   <![CDATA[
   Function factorial(n)
      If isNumeric(n) Then
         If n <= 1 Then
            factorial = 1
         Else
            factorial = n*factorial(n-1)
         End If
      Else
         factorial = -2   ' Error code.
      End If
   End Function
   ]]>
</script>
</component>

See Also

Script Component File Contents


<attach>

<attach> Element

Binds an event from the containing document to a function in the script component.

<attach event="eventName" handler="functionName" [for="elementName"]/>

Values

eventName
The event being bound, such as onmouseclick.
functionName
The name of the procedure (function or subroutine) in the script component file that is executed in response to the event. If this attribute is omitted, it is generated.

If the for attribute is not specified, the default value of the handler attribute is the value of the event attribute. If the for attribute is specified, the default handler attribute value is the string generated by concatenating the for attribute value, "_", and the event attribute value.

elementName
The element associated with the event, used for containing elements to which DHTML Behaviors are not explicitly attached. The only possible values for the for attribute are "document," "window," and "element." If the for attribute is not included, "element" is the default and the event is assumed to be fired on the element to which the behavior is attached.

Example

In the following example, the <attach> element binds three events to functions. For example, the DHTML onmouseover element is bound to the script component's do_onmouseover function. The functions bound to the DHTML onmouseover and onmouseout events are executed only if they are fired on the element in the containing document to which the behavior is attached. The docinit function is explicitly bound to the DHTML document object's onload event.

Note A CDATA section is required to make the script in the <script> element opaque. For details, see Script Component Files and XML Conformance.
<?XML version="1.0"?>
<component id="bvrscript component1">
<registration progID="Behaviorscript component"/>
<implements type="Behavior">
   <attach event="onmouseover" handler="do_onmouseover"/>
   <attach event="onmouseout "handler="do_onmouseout"/>
   <attach for="window" event="onload" handler="docinit"/>
</implements>
<script language="JScript">
<![CDATA[
var normalColor, normalSpacing;
function do_onmouseover(){
   // Save original values.
   normalColor = style.color;
   normalSpacing= style.letterSpacing;
   style.color = "red";
   style.letterSpacing = 2;
}
function do_onmouseout(){
   // Reset to original values.
   style.color = normalColor;
   style.letterSpacing = normalSpacing;
}
function docinit(){
   document.linkColor = "red";
}
]]>
</script>
</component>

See Also

Creating a Behavior Script Component


attachNotifiaction Method

attachNotification Method

Binds a function in the script component to a notification message sent from the host.

behavior.attachNotification (fpNotify)

Values

behavior
The ID of the <implements> element used to implement the Behavior interface.
Note By default, the properties and methods exposed by the Behavior handler are automatically added to the global script namespace and can be accessed without referencing the Behavior handler ID. In this case, instead of using Behavior.attachNotification as shown in the syntax, the method can be used in script simply as attachNotification. For more details, see the <implements> element.
fpNotify
The name of the function to bind to the notification.

Remarks

Currently, the host can call the specified function with the following notifications:

  • "contentReady" There has been a change to the content of the element to which the behavior is attached. This is fired as soon as the closing tag of the element is parsed, as well as when a script sets the DHTML innerHTML property of the element. A behavior can use this notification to retrieve the content of the element it is applied to.
  • "documentReady" The browser has finished parsing the document. Any modifications or initializations that need to be made to the content can take place at this point.
    Note The attachNotification method does not notify the script component of standard events that occur in the document, window, or any element on the page. The recommended way to receive notifications on this type of event is by using the DHTML achEvent method.

When dealing with changes to an element's DHTML style property, such as setting its visibility, changing colors, or changing fonts, it is recommended that the changes be made inline in the script component's <script> element, as shown in the following script component fragment. Making the change in the documentReady notification clause can cause slight flashing.

Note A CDATA section is required to make the script in the <script> element opaque. For details, see Script Component Files and XML Conformance.
<implements type="Behavior"/>
<script language="JScript">
<![CDATA[
   style.color = "green";
   style.letterSpacing = 5;
]]>
</script>

Example

The example below demonstrates how a function could be set up to trap notifications and process them as appropriate.

Note A CDATA section is required to make the script in the <script> element opaque. For details, see Script Component Files and XML Conformance.
<?XML version="1.0"?>
<component>
<implements type="Behavior">
   <event name="onResultChange"/>
</implements>

<script language="JScript">
<![CDATA[
   attachNotification (onNotification);
   function onNotification (sNotification){
      if (sNotification == "contentReady"){
         // Contents of element have changed.
      }
      else if (sNotification == "documentReady"){
         // Host has finished parsing element.
      }
      window.status = sNotification;
   }
]]>
</script>
</component>

See Also

<event> Element


createEventObject Method

Creates a DHTML event object to be used in passing event context information to the containing document when the fireEventmethod is called.

oEvent = behavior.createEventObject()

Values

behavior
The ID of the <implements> element used to implement the Behavior interface.
Note By default, the createEventObject method has global scope and can be accessed without referencing the Behavior handler ID. For example, instead of using Behavior.createEventObject as shown in the syntax, you can simply call the function as createEventObject. For more details, see the <implements> element.
oEvent
An event object created by the method.

Remarks

The same event object cannot be reused in multiple fireEvent calls.

Example

The following partial script component is derived from a hypothetical calculator script component. Whenever the result changes, the script component fires a custom onResultChange event back to the page, passing the result as an expando property of the event object.

Note A CDATA section is required to make the script in the <script> element opaque. For details, see Script Component Files and XML Conformance.
<component>
<implements type="Behavior">
   <event name="onResultChange"/>
</implements>

<script language="JScript">
<![CDATA[
attachEvent("onclick", doCalc);

function doCalc()
{
   // Code here to perform calculation. Results are placed into
   // the variable sResult.
   oEvent = createEventObject();
   oEvent.result = sResult;
   fireEvent("onResultChange",oEvent);
}
]]>
</script>
</component>

The following shows what the containing DHTML page might look like. When the onResultChange event fires, the results of the calculation are extracted from expando property result of the DHTML window.event object and displayed in the resultWindow <DIV> element.

<HTML>
<HEAD>
<xml:namespace prefix="LK" />
<style>
   LK\:CALC {behavior:url(engine.wsc)}
</style>
<script language="JScript">
function showResults(){
   resultWindow.innerText=window.event.result;
}
</script>
</HEAD>

<LK:CALC id="myCalc" onResultChange="showResults()">
<TABLE>
<TR>
   <DIV ID=resultWindow
      STYLE="border: '.025cm solid gray'"
         ALIGN=RIGHT>0.</DIV>
</TR>
<TR>
   <TD><INPUT TYPE=BUTTON VALUE=" 0 "></TD>
   <TD><INPUT TYPE=BUTTON VALUE="+/-"></TD>
   <TD><INPUT TYPE=BUTTON VALUE=" . "></TD>
   <TD><INPUT TYPE=BUTTON VALUE=" + "></TD>
   <TD><INPUT TYPE=BUTTON VALUE=" = "></TD>
<TR>
</TABLE>
</LK:CALC>
</HTML>

See Also

Exposing Custom Events in Behavior Script Components


element Property

Returns the element to which the behavior is being applied.

[oElement = ] Behavior.element

Values

oElement
Element to which the behavior is being applied.
Behavior
The ID of the <implements> element used to implement the Behavior interface.
Note By default, the properties and methods exposed by the Behavior handler are automatically added to the global script namespace and can be accessed without referencing the Behavior handler ID. In this case, instead of using Behavior.element as shown in the syntax, the property can be used in script simply as element. For more details, see the <implements> element.

Remarks

The property is read-only.

With this property, a behavior is able to communicate with the containing document. All properties, methods, and events exposed by the DHTML object model are accessible through this property.

Example

The following script component fragment implements an expanding and collapsing table of contents using a script component. The script component attaches to the element's DHTML onmouseover event. It sets the DHTML cursor property of the element to "hand" to signal the user that the element can be clicked in order to toggle visibility of its children.

Note A CDATA section is required to make the script in the <script> element opaque. For details, seeScript Component Files and XML Conformance.
<public>
   <attach event="onmouseover" handler="event_onmouseover");
</public>

<implements type="Behavior"/>
<script language="JScript">
<![CDATA[
   function event_onmouseover()
   {
      oElement = window.event.srcElement;
      if (oElement == element)
         oElement.style.cursor = "hand";
   }
]]>
</script>

See Also

For general information about applying behaviors to DHTML elements, see the "Using DHTML Behaviors" topic on the Site Builder Network (SBN)


<layout>

<layout> Element

Defines HTML text inserted into the containing document.

<layout>
   <HTMLtag>Inserted text</HTMLtag>
</layout>

Values

HTMLTag
The name of HTML tag for which the element's text is a replacement.

Remarks

When the behavior is called, the text in the <layout> element is read into the corresponding element in the containing document. This behavior is equivalent to setting the element's DHTML innerHTML property.

If the script component is not defined to be XML-conformant, the contents of the <layout> element are opaque. However, if the script component is XML-conformant, the contents of the <layout> element must explicitly be made opaque by including them in a CDATA. For more details, see Script Component Files and XML Conformance.

Example

The following shows an example of a script component with a <layout> element. Because the script component contains the <?XML ?> declaration at the top, the <layout> element contains a CDATA section to make the contents of the <layout> element opaque to the XML parser.

<?XML version="1.0" ?>
<component id="bvrScriptlet1">
<registration progID="BehaviorScriptlet"/>
<implements type="Behavior">
   <layout>
   <![CDATA[
      <h1>This is the HTML to show in the element</h1>
   ]]>
   </layout>
</implements>
</component>

See Also

For general information about applying behaviors to DHTML elements, see the "Using DHTML Behaviors" topic on the Site Builder Network (SBN).


fireEvent method

Fires a custom event.

Behavior.fireEvent(sEvent[, oEvent])

Values

.htm
Behavior
The ID of the <implements> element used to implement the Behavior interface.
Note By default, the properties and methods exposed by the Behavior handler are automatically added to the global script namespace and can be accessed without referencing the Behavior handler ID. In this case, instead of using Behavior.fireEvent as shown in the syntax, the property can be used in script simply as fireEvent. For more details, see the <implements> element.
sEvent
The name of the custom event as declared in the <implements> element.
oEvent
(Optional) Specifies an event object containing context information. The event object is created using the createEventObject method.

Remarks

The same event object cannot be reused in multiple calls to the fireEvent method.

Example

The following partial script component is derived from a calculator script component sample. Whenever the result changes, the script component fires a custom onResultChange event back to the page, passing the result as an expando property of the event object.

Note A CDATA section is required to make the script in the <script> element opaque. For details, see Script Component Files and XML Conformance.
<component>
<public>
   <event name="onResultChange" />
</public>

<implements type="Behavior">
   <attach event="onclick" handler="doCalc");
</implements>

<script language="JScript">
<![CDATA[
function doCalc(){
   // Code here to perform calculation. Results are placed into
   // the variable sResult.

   oEvent = createObjectEvent();
   oEvent.result = sResult;
   fireEvent("onResultChange",oEvent);
}
]]>
</script>
</component>

The following shows what the containing DHTML page might look like. When the onResultChange event fires, the results of the calculation are extracted from expando property result of the window.event object and displayed in the resultWindow <DIV> element.

<HTML>
<HEAD>
<xml:namespace prefix="LK" />
<style>
   LK\:CALC {behavior:url(engine.wsc)}
</style>
<script language="JScript">
function showResults(){
   resultWindow.innerText=window.event.result;
}
</script>
</HEAD>

<LK:CALC id="myCalc" onResultChange="showResults()">
<TABLE>
<TR>
   <DIV ID=resultWindow
      STYLE="border: '.025cm solid gray'"
      ALIGN=RIGHT>0.</DIV>
</TR>
<TR>
   <TD><INPUT TYPE=BUTTON VALUE=" 0 "></TD>
   <TD><INPUT TYPE=BUTTON VALUE="+/-"></TD>
   <TD><INPUT TYPE=BUTTON VALUE=" . "></TD>
   <TD><INPUT TYPE=BUTTON VALUE=" + "></TD>
   <TD><INPUT TYPE=BUTTON VALUE=" = "></TD>
<TR>
</TABLE>
</LK:CALC>
</HTML>

See Also

Exposing Custom Events in Behavior Script Components | fireEvent


XML Elements

In this Section

<?job?> Element
XML processing instruction that specifies attributes for error handling.
<?XML?> Element
Indicates that a file should be parsed as XML.
<description> Element
Marks the descriptive text that appears when the user runs ShowUsage() or runs the script with the /? command line switch.
<example> Element
Makes your script self documenting.
<job> Element
Marks the beginning and the end of a job within a Windows Script file (*.wsf).
<named> Element
Marks a particular named argument to the script.
<object> Element
XML element that is used in Windows Script component files and that defines objects that can be referenced by script.
<package> Element
Encloses multiple job definitions in a Windows Script Host control (.wsf) file.
<reference> Element
XML element that includes a reference to an external type library.
<resource> Element
XML element that isolates textual or numeric data that should not be hard-coded into a script.
<runtime> Element
Groups together the set of run-time arguments for a script.
<script> Element
XML element that contains script to define the behavior of a Windows Script component.

Related Sections

WSH Reference
List of elements that make up WSH Reference.
WSH Basics
Learn the basics of WSH.


<?job?>

<?job?> Element

Specifies attributes for error handling.

<?job error="flag" debug="flag" ?>

Arguments

error
A Boolean value. False is the default value for all attributes. Set to true to allow error messages for syntax or run-time errors in the Windows Script (.wsf) file.
Debug
A Boolean value. False is the default value for all attributes. Set to true to enable debugging. If debugging is not enabled, you will be unable to launch the script debugger for a Windows Script file.

Remarks

Although most Windows Script files normally run silently during production, you might find it useful to be notified of errors in the Windows Script (.wsf) file as you are developing it.

Example

The following example incorporates two jobs into one .wsf file that uses two different scripting languages.

<package>
   <job id="DoneInVBS">
      <?job debug="true"?>
      <script language="VBScript">
         WScript.Echo "This is VBScript"
      </script>
   </job>

   <job id="DoneInJS">
      <?job debug="true"?>
      <script language="JScript">
         WScript.Echo("This is JScript");
      </script>
   </job>
</package>

See Also

<runtime> Element | <named> Element | <description> Element | <example> Element | <object> Element | <package> Element | <resource> Element | <?XML?> Element


<?XML>?> element

Indicates that a file should be parsed as XML.

<?XML version="version" [standalone="DTDflag"] ?>

Arguments

version
A string in the form n.n specifying the XML level of the file. Use the value 1.0.
DTDflag
Optional. Boolean value indicating whether the XML file includes a reference to an external Document Type Definition (DTD). Script component XML files do not include such a reference, so the value for this attribute is always "yes."

Remarks

This declaration must be the first element in the file and cannot be preceded by any blank lines.

The existence of this declaration puts the script component compiler into strict XML mode, where element types and attribute names are case-sensitive, attribute values are enclosed in single or double quotation marks, and all elements are parsed. If the declaration is not included, the compiler allows syntax that is less strict.

You should include this declaration and follow XML conventions if your script component file will be edited in an editor that supports XML.

Example

The following example demonstrates the use of the <?XML?> Element:

<?XML version="1.0" standalone="yes" ?>

See Also

<runtime> Element | <named> Element | <description> Element | <example> Element | <object> Element | <package> Element | <resource> Element | <?job?> Element


<description> Element

Marks the descriptive text that is displayed when the ShowUsage method is executed or when the script is run with the /? command line switch.

<description>
    This section describes the script
</description>

Remarks

Your description can be more than one line long.

Do not include quotes in your description if you do not want them to appear in the usage. All text between the description tags appears in the usage listing. This includes, among others, tabs, new lines, and special characters.

The <description> element is similar to the <example> element, except it appears at the start of the usage, whereas the <example> element appears at the end.

Example

The following script demonstrates the use of the <description> Element:

<runtime>
    <description>
        This script reboots a server
    </description>
    <!--...etc...-->
</runtime>

See Also

ShowUsage Method | <runtime> Element | <named> Element | <unnamed> Element | <example> Element


<example> Element

Provides an example of usage for the job.

<example>
   Example text
</example>

Remarks

The <example> element is enclosed within the <runtime> element.

Example

The following script demonstrates the use of the <example> Element:

<job>
    <runtime>
        <description>This script reboots a server</description>
        <named
            name = "Server"
            helpstring = "Server to run the script on"
            type = "string"
            required = "true"
        />
        <example>Example: reboot.wsf /Server:scripting</example>
    </runtime>
</job>

Everything between <example> and </example> tags gets picked up, including new lines and extra white space. Calling the ShowUsage method from this script results in the following output:

This script reboots a server

Usage: reboot.wsf /server:value

Options:

server : Server to run the script on

Example:

reboot.wsf /server:scripting

See Also

ShowUsage Method


<job> Element

Marks the beginning and the end of a job within a Windows Script file (*.wsf).

<job [id=JobID]>
    job code
</job>

Arguments

JobID
Optional. Uniquely identifies the job within the scope of the Windows Script file.

Remarks

Each jobID within a Windows Script file must be unique.

Each script within a set of job tags is executed in sequence, from top to bottom.

A job contains one or more script blocks. A script block is any script code between a set of <script> tags. A script block can contain several scripts, and each script can be in a different scripting language.

To run a specific job or to run multiple jobs, use the //Job switch. If you specify more than one job, the jobs are executed in sequential order. (This is shown in the example below.). If you do not specify a job, only the first job is run. If you have two or more jobs in your Windows Script file, they must be enclosed in a <package> tag.

Example

The following script example is a Windows Script file called myScript.wsf. This file contains two separate jobs, each written in a different scripting language. The first job, written in VBScript, is given the identifier DoneInVBS. The second job, written in JScript, is given the identifier DoneInJS.

<package>
    <job id="DoneInVBS">
    <?job debug="true"?>
        <script language="VBScript">
           WScript.Echo "This is VBScript"
        </script>
    </job>
    <job id="DoneInJS">
    <?job debug="true"?>
        <script language="JScript">
           WScript.Echo("This is JScript");
        </script>
    </job>
</package>

To run the second job in the Windows Script file, myScript.wsf, type the following at the command prompt.

cscript myScript.wsf //job:DoneInJS

To run both jobs in myScript.wsf, type the following at the command prompt.

cscript myScript.wsf //job:DoneInVBS //job:DoneInJS

See Also

ShowUsage Method | <runtime> Element | <named> Element | <unnamed> Element | <description> Element | <example> Element


<named> Element

Describes a named argument for the script.

<named
   name = namedname
   helpstring = helpstring
   type = "string|boolean|simple"
   required = boolean
/>

Arguments

name
String that represents the name of the argument you are describing. Defines the argument at the command line and in the script.
helpstring
String that represents the help description for the argument. The WSH runtime provides the help description using the ShowUsage method or the /? argument.
type
Optional. Describes the type of argument, which defines how the argument will be parsed from the command line. The default value is simple.
required
Optional. A Boolean value that indicates whether an argument is required or not. Affects the display of the usage only.

Remarks

The <named> element is contained by (enclosed within) a set of runtime tags.

An argument with the name server would provide a /server argument at the command line as well as an argument named server in the WSHNamed arguments collection.

If the type is string, the argument is a string. The argument is passed to the script as /named:stringvalue.

If the type is Boolean, the argument is Boolean. The argument is passed to the script as /named+ to turn it on, or /named- to turn it off.

If the type is simple, the argument takes no additional value and is passed as just the name, /named.

Example

The following script demonstrates the use of the <named> Element:

<job>
<runtime>
  <named
    name="server"
    helpstring="Server to access"
    type="string"
    required="true"
  />
  <named
    name="user"
    helpstring="User account to use on server. Default is current account."
    type="string"
    required="false"
  />
  <named
    name="enable"
    helpstring="If true (+), enables the action. A minus(-) disables."
    type="boolean"
    required="true"
  />
  <named
    name="verbose"
    helpstring="If specified, output will be verbose."
    type="boolean"
    required="false"
  />
</runtime>
<script language="JScript">
  WScript.Arguments.ShowUsage();
</script>
</job>

This will produce the following output when usage is shown:

Usage: example.wsf /server:value [/user:value] /enable[+|-] [/verbose]

Options:

server    : Server to access
user      : User account to use on server. Default is current account.
enable    : If true (+), enables the action. A minus(-) disables.
verbose   : If specified, output will be verbose.

See also

ShowUsage Method | <runtime> Element | <unnamed> Element | <description> Element | <example> Element


<object> Element

Defines objects in Windows Script (.wsf) files that can be referenced by a script.

<object id="objID" [classid="clsid:GUID" | progid="progID"] />

Arguments

objID
Required. A name that references the object in your script. Object ID values must begin with a letter and can include letters, digits, and underscores (_). The object ID must be unique throughout the scope of the Windows Script file.
GUID
Optional. The class ID (GUID) of the object.
progID
Optional. Program ID of the object, which can be specified as an alternative to the class ID.

Remarks

The <object> element provides a way to expose objects globally for use in scripting within the Windows Script file without using functions such as CreateObject(). Using an <object> element makes the object available with global scope and enables scripting tools to provide statement completion for the object's members.

You must specify either a classid or a progid.

Example

<job>
<obect id="fso" progid="Scripting.FileSystemObject"/>
<script language="Jscript">

var a = fso.CreateTextFile("c:\\testfile.txt", true);
a.WriteLine("This is a test.");
a.Close();

</script>
</job>

See Also

<runtime> Element | <named> Element | <description> Element | <example> Element | <package> Element


>package< Element

<package> Element

Encloses multiple job definitions in a Windows Script (.wsf) file.

<package>
   code for one or more jobs
</package>

Remarks

The <package> element is optional when a .wsf file contains only one job.

Example

The following example incorporates two jobs into one .wsf file that uses two different scripting languages:

<package>
   <job id="DoneInVBS">
   <?job debug="true"?>
      <script language="VBScript">
         WScript.Echo "This is VBScript"
      </script>
   </job>

   <job id="DoneInJS">
   <?job debug="true"?>
      <script language="JScript">
         WScript.Echo("This is JScript");
      </script>
   </job>
</package>

See Also

<runtime> Element | <named> Element | <description> Element | <example> Element | <object> Element


<reference> Element

Includes a reference to an external type library.

<reference [object="progID"|guid="typelibGUID"] [version="version"] />

Arguments

progID
Program ID from which the type library can be derived. It can include either a version number (for example, ADO.Recordset.2.0), the explicit program ID of a type library, or the program ID of the executable (such as a .DLL) that incorporates the type library. If you use the object attribute, you do not need to specify a version attribute because the version can be inferred from the program ID. If the object attribute is specified, you cannot also specify a GUID attribute.
typelibGUID
The GUID of the type library to reference. If the GUID attribute is specified, you cannot also specify an object attribute.
version
Optional. Version number of the type library to use. It must be in the form <major version>[.<minor version>]. If a version is not specified, the default version is 1.0. If the object attribute is used to specify the type library and the version is not specified, the version is derived from the registry key for the specified program ID. If none can be found, the default is 1.0.

Remarks

Referencing a type library in your Windows Script (.wsf) file enables you to use constants defined in the type library in your scripts. The <reference> element looks up and makes available the type library associated with a specific program ID or type library name. Type library information can be available in .tlb, .olb, or .dll files.

See Also

<runtime> Element | <named> Element | <description> Element | <example> Element | <object> Element | <package> Element


<resource> Element

Isolates textual or numeric data that should not be hard-coded into a script.

<resource id="resourceID">
   text or number
</resource>

Arguments

resourceID
Unique identifier for the resource within the script.

Remarks

The <resource> element allows you to isolate strings or numbers in your Windows Script (.wsf) file that you want to reference in your scripts. For example, resource elements are typically used to maintain strings that may be localized into other languages.

To get the value of a resource, call the getResource method, passing it the ID of the resource you want to use.

Everything within the elements gets used including white space (tabs, new lines, etc.).

Example

The following code defines a resource (errNonNumeric) and returns its value if the variable upperBound is not numeric.

<resource id="errNonNumeric">
   Non-numeric value passed
</resource>

<script language="VBScript">
   <![CDATA[
      Function getRandomNumber(upperBound)
         If IsNumeric(upperBound) Then
            getRandomNumber = CInt(upperBound * Rnd + 1)
         Else
            getRandomNumber=getResource("errNonNumeric")
         End If
      End Function
   ]]>
</script>

See Also

<runtime> Element | <named> Element | <description> Element | <example> Element | <object> Element | <package> Element | getResource Method


<runtime> Element

Groups together the set of run-time arguments for a script.

<runtime>
    <named attributes etc. />
    <unnamed attributes etc. />
    <example>Example Text</example>
    …
</runtime>

Remarks

The ShowUsage method uses the information enclosed by the <runtime> element to display the runtime parameters for a script.

Since the <runtime> element is enclosed within a set of job tags, the defined run-time arguments apply to that job only.

Note With version 5.6, the data enclosed by the <runtime> element is used only for self-documentation and to format the data displayed by ShowUsage. The <runtime> element does not enforce the values set for the arguments it contains (i.e. a "required" argument that is missing from the command line does not cause an error). If the <runtime> element is included in a .wsf file, then running the script with the "/?" argument will show the usage and quit.

Example

The following script demonstrates the use of the <runtime> Element:

<job>
    <runtime>
        <named
            name="server"
            helpstring="The server to run the script on"
            type="string"
            required="true"
        />
    </runtime>
<script language="JScript">
  if (!WScript.Arguments.Named.Exists("server"))
  {
    WScript.Arguments.ShowUsage();
  }
// ... some script here
</script>
</job>

See Also

ShowUsage Method | <named> Element | <unnamed> Element | <description> Element | <example> Element


<unnamed> Element

Describes an unnamed argument for the script.

<unnamed
   name       = unnamedname
   helpstring = helpstring
   many       = boolean
   required   = boolean or integer
/>

Arguments

name
The string that is used in the usage to represent this argument. This value is not used elsewhere.
helpstring
String that represents the help description for the argument. The WSH runtime provides the help description using the ShowUsage method or the /? argument.
many
Optional. Boolean value. If true, then this argument may be repeated more times than specified by the required attribute. Otherwise, the required attribute represents the exact number of the argument that is required. See the example below for more details.
required
Optional. An integer value indicating how many times this argument should appear in the command line.

Remarks

The <unnamed> element is contained by (enclosed within) a set of runtime tags.

An argument with the name server would provide a /server argument at the command line and an argument named server in the WSHNamed arguments collection.

Note The name attribute of the unnamed element is just for display purposes.

When setting the "required" attribute, a Boolean value will be converted to an integer; "true" becomes 1 and "false" becomes 0.

Example

Here are a couple of examples of how the various attributes affect the usage with unnamed elements. First, a simple case:

<runtime>
<unnamed
  name="filename"
  helpstring="The file to process"
  many="false"
  required="true"
</>
</runtime>

This would produce the following:

Usage: example.wsf filename

Options:

filename : The file to process

Change it to:

<runtime>
<unnamed
  name="filename"
  helpstring="The files to process"
  many="false"
  required="3"
</ >
</runtime>

and the output changes to:

Usage: example.wsf filename1 filename2 filename3

Options:

filename : The files to process

The many switch will display ellipses to indicate you can enter more files than indicated. If the example changes to:

<runtime>
<unnamed
  name="filename"
  helpstring="The file(s) to process"
  many="true"
  required="1"
</>
</runtime>

then the output changes to:

Usage: example.wsf filename1 [filename2...]

Options:

filename: The file to process.

See also

ShowUsage Method | <runtime> Element | <named> Element | <description> Element | <example> Element


<script> Element

Contains script that defines the behavior of a Windows Script (.wsf) file.

<script language="language" [src="strFile"]>
     script here
</script>

Arguments

language
The name of the scripting language, such as VBScript or JScript, used in the script block.
strFile
The name of the script file to include into the script block.

Remarks

If XML validation is not enabled, the XML parser ignores all lines inside the <script> element. However, if XML validation is enabled by including the <?XML?> element at the top of the Windows Script (.wsf) file, the XML parser can misinterpret greater than (>), less than (<), and other symbols used in script as XML delimiters.

If you are creating a file that conforms closely to XML syntax, you must ensure that characters in your script element are not treated as XML-reserved characters. To do this, enclose the actual script in a <![CDATA[ ... ]]> section. This applies to all data blocks - <example>, <description>, and <resource>. All may need CDATA markers if <?XML?> is specified and if they include XML-reserved characters.

Note Do not include a CDATA section unless you also include the <?XML?> declaration.

Example

The following example incorporates two jobs into one .wsf file, using two different scripting languages:

<package>
   <job id="DoneInVBS">
   <?job debug="true"?>
      <script language="VBScript">
         WScript.Echo "This is VBScript"
      </script>
   </job>

   <job id="DoneInJS">
   <?job debug="true"?>
      <script language="JScript">
         WScript.Echo("This is JScript");
      </script>
   </job>
</package>

See Also

<runtime> Element | <named> Element | <description> Element | <example> Element | <object> Element | <package> Element | <resource> Element | <?XML?> Element


<usage> Element

Allows user to override default usage display.

<usage>
    This section describes the script
</usage>

Remarks

The <usage> element is similar to the <example> and <description> elements — it contains text that the developer can include in the usage. The difference is that if a <usage> element exists, everything else in the <runtime> element is ignored, and only the text in the <usage> element is displayed. This is so you can completely override the usage display.

Note The <usage> Element should always be enclosed by a <runtime> Element.

Example

The following script demonstrates the use of the <usage> Element:

<job>
<runtime>
<named name="arg1" helpstring="the first arg"/>
<usage>
Your usage text goes here.
</usage>
</runtime>
<script language="vbscript">
WScript.Arguments.ShowUsage
</script>
</job>

This produces the following:

Your usage text goes here.

See Also

<runtime> Element | <named> Element | <description> Element | <example> Element | <package> Element | <resource> Element | <?XML?> Element


Security and Windows Script Host

Windows Script Host, which is a flexible tool for automating Windows, can be dangerous in the hands of someone who is bent on wreaking havoc.

To prevent abuse of Windows Script Host without stifling its power, Windows Script Host 5.6 employs a new security model.

Script users can now verify the authenticity of a script before running it. Script developers can sign their scripts to prevent unauthorized modifications. Administrators can enforce strict policies that determine which users have privileges to run scripts locally or remotely.

In this Section

CryptoAPI Tools

Signing a Script

Signature Verification Policy

Verifying a Script

Software Restriction Policies


CryptoAPI Tools

The CryptoAPI Tools are used to create and verify digital signatures in *.exe, *.cab, *.dll, *.ocx, and script (*js, *.vbs, and *.wsf) files.

CryptoAPI Tools are used to digitally sign files to be used with Microsoft® Authenticode®, and to view and manage certificates, certificate revocation lists (CRLs), and certificate trust lists (CTLs). For more information on CrptoAPI Tools, see the CryptoAPI Start Page at (http://msdn.microsoft.com/library/psdk/crypto/portalapi_3351.htm?RLD=290).

See Also

Security and Windows Script Host | Signing a Script | Verifying a Script | Signature Verification Policy


Signature Verification Policy

In WSH, administrators have the choice to turn signature verification either on or off. If an administrator turns signature verification on, then the machine will only run scripts signed by trusted authorities. With signature verification turned on, there are two possible scenarios:

  • If the trust can't be determined, then the user is prompted to confirm that the script should run.
  • If the trust can't be determined, then the script does not run.

If an administrator turns signature verification off, the machine permits users to run any script.

In Windows 2000, the signature verification policy is set through the Local Security Policy editor. For more information on the Local Security Policy Editor and WSH settings, see the online Windows help system.

The signature verification policy registry key is located in the following hive:

\HKEY_CURRENT_USER\SOFTWARE\Microsoft\Windows Script Host\Settings\TrustPolicy

The key is set to one of the following REG_DWORD values:

  • 0 Run all scripts
  • 1 Prompt user if script is untrusted
  • 2 Run only trusted scripts

See Also

Security and Windows Script Host | Signing a Script | Verifying a Script | WinTrust


Verifying a Script

Verifying a script determines whether the script that you are about to run is from a trusted source. It also allows you to confirm the integrity of the script. WSH verifies scripts before it attempts to run them, but you may have your own reason to verify a script.

Script verification is accomplished programmatically with the Signer object's VerifyFile method.

The VerifyFile method:

  • Verifies the validity of the signature.
  • Verifies that the signature belongs to a person who is trusted in your Trusted Publishers List.
  • Verifies that the script has not been changed since it was signed.
Note Although the VerifyFile method programmatically confirms the digital signature, you should always ensure that you really trust the trusted roots in the Trusted Publishers List.

See Also

Security and Windows Script Host | Signing a Script | Signature Verification Policy | WinTrust


Software Restriction Policies

Software Restriction Policies are trust policies, which are regulations set by an administrator to restrict scripts that are not fully trusted from performing unauthorized actions within the operating system.

The following three criteria are used by Software Restriction Policies in determining a trust level:

  • Any signature information in the script
  • The path from which the script is running
  • File content

Software Restriction Policies define the following default containers:

  • Domain Administrator
  • Machine Administrator
  • Machine User
  • Guest User
  • Denied

Additionally, you can define your own custom container and set your own policies.

See Also

Security and Windows Script Host


Script Encoder

Script Encoder Overview

Script Encoder is a simple command-line tool that enables script designers to encode their final script so that Web hosts and Web clients cannot view or modify their source. Note that this encoding only prevents casual viewing of your code; it will not prevent the determined hacker from seeing what you've done and how.

Web designers use scripting on Web pages and server-side active server pages (.htm) to add virtually every kind of feature you can imagine. In addition, scripting is used by the Windows® Scripting Host (WSH) and in a number of other applications with equally impressive results.

Up to now, one of the shortcomings of using scripts is that they afford no protection of the intellectual property contained within, nor do they provide any assurance that what users get is what you created. Clever algorithms and carefully designed scripts were always completely visible because they were stored as plain text. As a result, script users at every level could see the script designer's code and could then take it, modify it, and make it their own. Obviously, this is not good if you're trying to get an edge in a very competitive environment.

With the introduction of scriptlets, protecting the source code becomes even more important. Script designers want to use this simple component architecture, but they don't necessarily want to share their source code with the world. After a script is encoded, changing any part of the resulting file will render it inoperable, thus ensuring the absolute integrity of your encoded script.

See Also

Using Script Encoder | Script Encoder Syntax | .htm


Using Script Encoder

The Script Encoder encodes only scripting code, with all other file content left untouched to appear as plain text. To use the Script Encoder, develop and debug your script in the usual manner, then use this utility to encode your final script. The Script Encoder uses markers within your source code to identify where encoding should begin.

For Visual Basic® Scripting Edition (VBScript), the following example illustrates how the encoding marker is used to expose a plain-text copyright message:

<SCRIPT LANGUAGE="VBScript">
'Copyright© 1998. XYZ Productions. All rights reserved.
'**Start Encode**
' Your code goes here.
</SCRIPT>

In JScript®, the encoding marker looks like this:

<SCRIPT LANGUAGE="JScript">
//Copyright© 1998. ZYX Productions. All rights reserved.
//**Start Encode**
// Your code goes here.
</SCRIPT>

When the Script Encoder is invoked, anything in the script block before the start marker is left unencoded, while everything else in the script block is encoded. Therefore, if the start marker is omitted, the entire scripting block is encoded, but if the start marker is at the end of the scripting block, nothing is encoded.

After the encoding takes place, you should be aware that the language designator in the <SCRIPT> tag has changed. For VBScript, the new designator looks like this:

<SCRIPT LANGUAGE="VBScript.Encode">

For JScript, the new designator looks like this:

<SCRIPT LANGUAGE="JScript.Encode">

The Script Encoder is invoked on the MS-DOS command line or in the Run dialog box as follows:

SRCENC [switches] inputfile outputfile

See Also

Script Encoder Overview | Script Encoder Syntax | Script Encoding Sample


Script Encoder Syntax

Encodes scripting source code so it cannot be easily viewed or modified by users.

Syntax

SCRENC [/s] [/f] [/xl] [/l defLanguage ] [/e defExtension] input file output file

The .htm has these parts:

Part | Description
/s | Optional. Switch that specifies that the Script Encoder is to work silently, that is, produce no screen output. If omitted, the default is to provide verbose output.
/f | Optional. Specifies that the input file is to be overwritten by the output file. Note that this option destroys your original input source file. If omitted, the output file is not overwritten.
/xl | Optional. Specifies that the @language directive is not added at the top of .htm files. If omitted, @language directive is added for all .htm files.
/l defLanguage | Optional. Specifies the default scripting language (JScript® or VBScript) to use during encoding. Script blocks within the file being encoded that do not contain a language attribute are assumed to be of this specified language. If omitted, JScript is the default language for HTML pages and scriptlets, while VBScript is the default for active server pages. For plain text files, the file extension (either .js or .vbs) determines the default scripting language.
/e defExtension | Optional. Associates the input file with a specific file type. Use this switch when the input file's extension doesn't make the file type obvious, that is, when the input file extension is not one of the recognized extensions, but the file content does fall into one of the recognized types. There is no default for this option. If a file with an unrecognized extension is encountered and this option is not specified, the Script Encoder fails for that unrecognized file. Recognized file extensions are asa, asp, cdx, htm, html, js, sct, and vbs.
inputfile | Required. The name of the input file to be encoded, including any necessary path information relative to the current directory.
outputfile | Required. The name of the output file to be produced, including any necessary path information relative to the current directory.

Remarks

There are four kinds of files than can be processed by the Script Encoder. They are:

  • ASP. This format consists of a text active server page containing valid HTML and embedded scripting blocks within <SCRIPT> ... </SCRIPT> tags or <% ... %> tags. Applications that use this format include Microsoft® Internet Information Services (IIS). Recognized file extensions are .htm, .asa, and .cdx.
  • HTML. This format consists of a text file that contains valid HTML along with embedded script blocks. Applications using this scripting format include Microsoft FrontPage®, Microsoft® Visual InterDev™ and virtually all Web designers and browsers. Recognized file extensions are .htm and .html.
  • Plain text. This format consists of text file that contains only script with no surrounding tags. Applications using scripting format include Windows® Scripting Host (WSH) and Microsoft® Outlook®. Recognized file extensions are .js and .vbs, which are changed to .jse and .vbe, respectively, after encoding.
  • Scriptlet. This format consists of a text file that contains valid scriptlet code within <SCRIPT> ... </SCRIPT> tags. Recognized file extension is .sct and .wsh.

Examples

The following are examples of the use of the Script Encoder and a brief explanation of the results:

To encode input file test.html and produce output file encode.html, use:

screnc test.html encode.html

To encode input file test.htm and overwrite the input file with the encoded output file, use:

screnc /f test.htm

To encode all .htm files in the current directory and place the encoded output files in c:\temp, use:

screnc *.htm c:\temp

To encode all files in the current directory as .htm files and place them in c:\temp, use: screnc /e asp *.* c:\temp

To encode input file test.htm and produce output file encode.htm, ensuring that all script blocks that don't have a language attribute specified use VBScript, use:

screnc /l vbscript test.htm encode.htm

To encode all scriptlet files in the current directory and overwrite them with encoded files, while displaying no message, use:

screnc /s /f *.sct

See Also

Script Encoder Overview | Using Script Encoder | Script Encoding Sample


Script Encoding Sample

Here is a short example of a Web page that includes some JScript code that needs protecting:

<HTML>
<HEAD>
<TITLE>Script Encoder Sample Page</TITLE>
<SCRIPT LANGUAGE="JScript">
<!--//
//Copyright© 1998 Microsoft Corporation. All Rights Reserved.
//**Start Encode**
function verifyCorrectBrowser(){
  if(navigator.appName == "Microsoft Internet Explorer")
    if (navigator.appVersion.indexOf ("5.") >= 0)
      return(true);
    else
      return(false);
}
function getAppropriatePage(){
  var str1 = "Had this been an actual Web site, a page compatible with ";
  var str2 = "browsers other than ";
  var str3 = "Microsoft Internet Explorer 5.0 ";
  var str4 = "would have been loaded.";
  if (verifyCorrectBrowser())
    document.write(str1 + str3 + str4);
  else
    document.write(str1 + str2 + str3 + str4);
}
//-->
</SCRIPT>
</HEAD>
<BODY onload="getAppropriatePage()">
</BODY>
</HTML>
Here's the same page as it appears after being run through the Script Encoder:
<HTML>
<HEAD>
<TITLE>Script Encoder Sample Page</TITLE>
<SCRIPT LANGUAGE="JScript.Encode">
<!--//
//Copyright© 1998 Microsoft Corporation. All Rights Reserved.
//**Start Encode**#@~^QwIAAA==@#@&0;mDkWP7nDb0zZKD.n1YAMGhk+Dvb`@#@&P,kW`UC7kLlDGDcl22gl:n~{'~Jtr1DGkW6YP&xDnD+OPA62sKD+ME#@#@&P,~~k6PvxC\rLmYGDcCwa.n.kkWU bx[+X66Pcr*cJ#,@*{~!*P~P,P~.YEMU`DDEbIP,P,+s/n@#@&P~P,~PM+O;Mx`WC^/n#pN6EU1YbWx,oObaw.WaDrCD+nmL+v#@#@&~P7lMPdY.q,'~J_CN,Y4rkP4nnPCx,C1Y;mV,+(PkrY~~l,wCLPmKhwmYk(snPSkDt~JI@#@&P~\m.PkY.+,'PE8MWA/.kPGDtDPDtmUPri@#@&,P-CMP/D.&,'Pr\rmMWkWWY~(YnDnY,2a2^WDn.,* !,Ep@#@&,P7lD,/D.c,'~JSW;s9Ptm-+,4+U~VKl9+[REI,Pr0,c\DrWHZW..mOAMGS/nM`*#@#@&P,~P9W^Es+UOchDbO+v/YMq~_,/DDfPQ~kY.c*IP,+sd@#@&~~,P[W1;s+UDRSDkD+vdYMF~_,/O.yP_,dYM&P3~dYMc*iNz&R @*^#~@
//-->
</SCRIPT>
</HEAD>
<BODY onload="getAppropriatePage()">
</BODY>
</HTML>
Note After encoding, if you change even one character in the encoded text, the integrity of the entire script is lost and it can no longer be used.

See Also

Script Encoder Overview | Using Script Encoder | Script Encoder Syntax


About

Help file creation (c) 2002 Peter Ostrovski


Behavior Handler Reference

With the Behavior handler, Microsoft® Internet Explorer provides a means for a Behavior script component to communicate back to its containing page through custom events and to access the containing document's object model.

The following elements, properties, and methods are specific to the Behavior Handler.

  • <attach> Element
  • <layout> Element
  • element Property
  • attachNotification Method
  • createEventObject Method
  • fireEvent Method