Rough Guide to Windows Script Host |
<Job ID="HelloWorld">
<script language=PerlScript>
$WScript->Echo("Hello World!");
</script>
</Job>
The XML Job-elements encloses the ID of the Job that is run, and the script
elements define PerlScript as the script language to use. You will experience
different results depending if you execute this from the command-line or from
the windows desktop. The first instance will print text to the screen, but the
Windows desktop will pop up a messagebox with "Hello World!" Next,
let's look at what the WScript object has to offer.CreateObject
method will create an instance of a given object.
In the following example, we'll see how an ADO Connection object is easily
created within WSH.
<Job ID="ADOSample1">
<script language=PerlScript>
$conn = $WScript->CreateObject('ADODB.Connection');
$conn->Open('ADOSamples');
if($conn->{State} == 1) {
$WScript->Echo("Connection
Successful!")
}
else {
$WScript->Echo("Connection
Failed ...");
}
</script>
</Job>
In addition to the above, you can specify a second parameter in the call to CreateObject
.
This parameter contains a string which defines a prefix that you specify. By
doing so, the object's outgoing interface is connected and any time an event is
fired from the object, you can intercept it within the WSH file. For example, in
the ADO connection object, there are a number of events. Sparing the details, WillConnect
is called before a connection starts, and Connectcomplete
is called
after a connection has been started. They can be easily intercepted within the
WSH file.
<Job ID="Test">
<script language=PerlScript>
$conn=$WScript->CreateObject('ADODB.Connection', 'MyWSH_');
$conn->Open('ADOSamples');
if($conn->{State} == 1) {
$WScript->Echo("Connection
Successful!")
}
else {
$WScript->Echo("Connection
Failed ...");
}
sub MyWSH_ConnectComplete {
$WScript->Echo("ConnectComplete
was fired ... ");
}
sub MyWSH_WillConnect {
$WScript->Echo("WillConnect
was fired ... ");
}
</script>
</Job>
For the same result as above, you can use the ConnectObject
-method
whose syntax is $WScript->ConnectObject(Object, Prefix);
. The
method $WScript->DisconnectObject(Object);
will disconnect its
event handling provided that the object is connected. Some other methods are as
follows: $Wscript->Echo(1, 2, 3, n);
Print text to the standard
output defined by WSH. Separating the arguments cause only a space to separate
the items in a desktop environment and a newline to separate the items in a
command-line scenario.
$WScript->GetObject(Pathname [,ProgID] [,Prefix]);
Retrieves an Automation object from a file or an object specified by the
strProgID parameter.
$WScript->Quit([$int_errorcode]);
Quit and process and optionally provide an integer which represents an error
code.
$WScript->Sleep($int_milliseconds);
Places the script process into an inactive state for the number of milliseconds
specified and then continues execution.
$WScript->{Application};
Provides the IDispatch interface on the WScript object
$WScript->{Arguments};
Returns a pointer to the WshArguments collection or identifies arguments for the
shortcut to the collection.
$WScript->{Fullname};
Returns a string containing the full path to the host executable file or
shortcut object.
$WScript->{Name};
Returns a string containing the friendly name of the WScript object.
$WScript->{Path};
Provides a string containing the name of the directory where WScript.exe or
CScript.exe resides.
$WScript->{Scriptfullname};
Provides the full path to the script currently being run.
$WScript->{Scriptname};
Provides the file name of the script currently being run.
$WScript->{StdError};
Exposes the write-only error output stream for the current script. Only
applicable with CScript command-line WSH files.
$WScript->{StdIn};
Exposes the read-only input stream for the current script. CScript only.
WScript->{StdOut};
Exposes the write-only output stream for the current script. CScript only.
$WScript->{Version};
Returns the version of Microsoft Windows Script Host.
<Job ID="args">
<script language=PerlScript>
$arg = $WScript->{Arguments};
$countArgs = $arg->{Count};
for($i=0; $i<$countArgs; $i++) {
$WScript->Echo($arg->Item($i));
}
</script>
</job>
$WshShell = $WScript->CreateObject("WScript.Shell")
An interesting method of the WshShell object is the ability to activate an
application window and putting it in focus. This is done by calling AppActivate
either with the title in the title bar of the running application window as a
parameter or by using the task ID as a parameter.
<Job Id="WshShell">
<script language=PerlScript>
$WshShell = $WScript->CreateObject("WScript.Shell");
$WshShell->Run("notepad");
$WshShell->AppActivate("Untitled -
Notepad");
my $message = "Hello from PerlScript!\n";
for($i=0; $i < length($message); $i++) {
$char = substr($message, $i,
1);
$WScript->Sleep(100);
$WshShell->SendKeys($char);
}
</script>
</job>
The SendKeys
-method simply sends keystrokes to the active windows.
The Run
method is a little more flexible.
$WshShell->Run(Command, [WindowStyle], [WaitOnReturn]);
The WindowStyle can be an integer between 0 through 10, and WaitOnReturn is a
boolean value or 1 (TRUE) or 0 (FALSE). FALSE is the default value it means that
an immeditate return to script execution contrary to waiting for the process to
end is preferable. It also returns an error code of zero while TRUE returns any
error code generated by the active application.
CreateShortcut($path_or_url)
returns
an object reference to a WshShortcut
-object. Keep in mind that a
dekstop shortcut has tbe extension .lnk and an URL shortcul has the file
extension .url. In the latter case, a WshURLShortcut object is returned.Description
-property
contains a string describing the shortcut, Fullname
returns the
full path to the host executable, Hotkey
allows for combinations
such as "ALT+CTRL+X" as hotkeys for shortcuts on the Windows dekstop
or windows startmenu, IconLocation
is a property that you set to
"Path, index" to provide the Icon location of the shortcut. In
addition, use the TargetPath
-property to set the path to the
executable file pointed to by the shortcut, WindowStyle
can be set
to either 1, 3, or 7 for the shortcut object, and WorkingDirectory
defines the directory in which the shortcut should start. If you are
shortcutting a URL, you have only the Fullname
and TargetPath
properties where the latter one is a URL. All shortcut objects are final when
you call the Save
method.
<Job Id="SpecialFolder">
<script language=PerlScript>
$WshShell = $WScript->CreateObject("WScript.Shell");
$numFolders = $WshShell->SpecialFolders->{Count};
$title = "PerlScript & WSH Example";
$style = 1;
for($i=0; $i<$numFolders; $i++) {
$ok_or_cancel = $WshShell->Popup(
$WshShell->SpecialFolders($i),
undef,
$title,
$style);
exit if ($ok_or_cancel == 2);
}
</script>
</job>
RegRead
, RegWrite
, and RegDelete
.
Simply provide either method with a string such as the short form HKCU\ScriptEngine\Val
or longer variant HKEY_CURRENT_USER\ScrtipeEngine\Val. Notice that a key is
returned if the last character is a backslash, and a value is returned if no
backslash is at the end. The RegRead method supports the following data types
RegWrite requires a few extra parameters:
- REG_SZ
- REG_EXPAND_SZ
- REG_DWORD
- REG_BINARY
- REG_MULTI_SZ
$WshShell->RegWrite(Name, Value [,Type]);
The name is a fully qualified string such as HKCU\ScriptEngine\Val where the
same rules apply for key and value as previously mentioned. The Type-parameter
is optional, but if used, it must be one of the following data types:
- REG_SZ
- REG_EXPAND_SZ
- REG_DWORD
- REG_BINARY
$WshShell->ExpandEnvironmentStrings($string);
In addition, log an event in the NT event log or WSH.log (Windows 9x) file
using:
$WshShell->LogEvent(Type, Message [,Target]);
Target is the name of the system on NT, thus only applicable on NT. The Type of
event is either
This method returns a boolean value indicating success or failure. Another method is Popup, which sends a Windows messagebox up on the screen.
- 0 (SUCCESS)
- 1 (ERROR)
- 2 (WARNING)
- 4 (INFORMATION),
- 8 (AUDIT_SUCCESS)
- 16 (AUDIT_FAILURE)
$retval = $WshShell->Popup(Text, [SecondsWait], [Title], [Type]);
The method allows you to define the text to pop up, alternatively seconds to
wait before closing window, the title of the window, and lastly the type of
buttons available in the window. They can be:
The value that you choose can also be combined with an icon:
- 0 (Ok)
- 1 (Ok and Cancel)
- 2 (Abort, Retry, and Ignore)
- 3 (Yes, No, and Cancel)
- 4 (Yes and No)
- 5 (Retry and Cancel)
The return values returned to
- 16 (Stop Mark)
- 32 (Question Mark)
- 48 (Exclamation Mark)
- 64 (Information Mark)
$retval
indicates which button was
pressed. The value will be one of the following:
- 1 (OK)
- 2 (Cancel)
- 3 (Abort)
- 4 (Retry)
- 5 (Ignore)
- 6 (Yes)
- 7 (No)
$WshNetwork->AddPrinterConnection($LocalName, $RemoteName[,$UpdateProfile][,$User][,$Password]);
User and password are parameters two parameters with given meaning. Localname
and Remotename are the names of the printer resource. Set UpdateProfile to TRUE
for storing this mapping in the user profile. Next, AddWindowsPrinterConnection()
adds a printer just as you would add one using the control panel. On Windows
NT/2000 the only parameter you need to call this method with is the path to the
printer while windows 9x requires you to specify the driver to use, and
optionally specify which port to which it is connected. In the last event, the
syntax is:
$WshNetwork->AddWindowsPrinterConnection($PrinterPath, $DriverName[,$Port])
As easily as adding a printer, you can remove a printer. Simply do
$WshNetwork->RemovePrinterConnection($Name, [$Force], [$UpdateProfile]);
If you set $Force to TRUE (1), it will remove the connection regardless if it is
being used, and setting $UpdateProfile to true will remove any user profile
mapping.
$WshNetwork->SetDefaultPrinter($PrinterName);
To return a collection of all your printers, call:
$Printers = $WshNetwork->EnumPrinterConnections();
Then use the Count-property to retrieve the number of items in the $Printers
collection object.
$WshNetwork->MapNetworkDrive($LocalName, $RemoteName,
[$UpdateProfile], [$User], [$Password]);
For example:
$WshNetwork->MapNetworkDrive('C:\', '\\MyComputerServer\\ShareHere);
Remove a network drive using the now familiar syntax
$WshNetwork->RemoveNetworkDrive($Name, [$Force], [$UpdateProfile])
or enumerate the network drives as:
$Drives = $WshNetwork->EnumNetworkDrive();
The three properties of the network object are ComputerName, UserName, and
UserDomain.
<Job [id=JobID]>
For example:
<package>
<Job id="PrintOutput">
</Job>
<Job id="ReadInput">
</Job>
</package>
You can also set a boolean value of true (1) or false (0) for error checking or
debugging by using the additional tag
<? job error="true" debug="true" ?>
<script language="languageName"> code </script>
For example.
<?XML version="1.0"?>
<job>
...
<script language="PerlScriptt">
<![CDATA[
sub ReturnValue {
#
# Perl code here
#
}
]]>
</script>
</job>
<resource id="resourceID"> text or number to represent
resource goes here </resource>
You use the getResource(resourceID)
to retrieve the contents of the
resource specified in the resourceID parameter.
<reference [object="progID" | guid="typelibGUID"]
[version="versionNo"] />
Written document copyright (c) 2000 Tobias Martinsson. All rights reserved.
When included as part of the Standard Version of Perl, or as part of its complete documentation whether printed or otherwise, this work may be distributed only under the terms of Perl's Artistic License. Any distribution of this file or derivatives thereof outside of that package require that special arrangements be made with copyright holder.
Irrespective of its distribution, all code examples in this file are hereby placed into the public domain. You are permitted and encouraged to use this code in your own programs for fun or for profit as you see fit. A simple comment in the code giving credit would be courteous but is not required.
Windows Script Host is copyright (c) 1991-2000 Microsoft Corporation. All Rights Reserved.
Rough Guide to Windows Script Host |