home
***
CD-ROM
|
disk
|
FTP
|
other
***
search
/
Chip 2000 May
/
Chip_2000-05_cd1.bin
/
zkuste
/
Perl
/
ActivePerl-5.6.0.613.msi
/
䆊䌷䈹䈙䏵-䞅䞆䞀㡆䞃䄦䠥
/
_b568deaa9903daa55461a86af96592f5
< prev
next >
Wrap
Text File
|
2000-03-22
|
22KB
|
506 lines
<HTML>
<HEAD>
<TITLE>Rough Guide to Windows Script Host</TITLE>
<LINK rel="stylesheet" href="../Active.css" type="text/css">
<LINK rev="made" href="mailto:">
<META name="GENERATOR" content="Microsoft FrontPage 4.0">
<META name="ProgId" content="FrontPage.Editor.Document">
</HEAD>
<BODY>
<TABLE border="0" cellpadding="0" cellspacing="0" width="100%">
<TR>
<TD class="block" valign="MIDDLE" width="100%" bgcolor="#cccccc"><STRONG>
<P class="block"> Rough Guide to Windows Script Host</P>
</STRONG></TD>
</TR>
</TABLE>
<A name="__index__"></A>
<UL>
<LI><A href="#introduction">Windows Script Host (WSH)</A>
<UL>
<LI><A href="#executing">Running a WSH File</A>
<LI><A href="#objectmodel">The Object Model</A>
<UL>
<LI><A href="#wscript">The Windows Script Object</A>
<LI><A href="#wshshell">The WshShell Object</A>
<UL>
<LI><A href="#shortcut">Creating Shortcuts</A>
<LI><A href="#specialfolder">Special Folders</A>
<LI><A href="#registry">working with The Registry</A>
<LI><A href="#misc">Miscellanous</A>
</UL>
<LI><A href="#network">The WshNetwork Object</A>
</UL>
<LI><A href="#elementref">XML Element Referece</A>
<UL>
<LI><A href="#elemjob"><job></A>
<LI><A href="#elemscr"><script></A>
<LI><A href="#elemres"><resource></A>
<LI><A href="#elemref"><reference></A>
</UL>
</UL>
</LI>
<LI><A href="#author and copyright">AUTHOR AND COPYRIGHT</A>
</UL>
<P><A name="introduction">
<HR>
<H1>Windows Script Host (ASP)</H1>
Windows Script Host (WSH) is a scripting host for ActiveX Scripting Engines such as PerlScript. As a
host, WSH enables you to use the scripting language from the command-line and from within the
Windows desktop with the WSH features.<BR>
<BR>
</A><A name="executing">
<H2>Running a WSH File</H2>
In order to execute a WSH-file, use one of two executable files depending on your needs: WScript.exe
for Windows desktop files and CScript.exe is for command-line scripts. You can set the behavior and
appearance of these executed scripts by running the executable without providing a file; if so,
WScript will display a properties page that you can modify, and CScript will show the available
switches. At work, WSH enables you to use more than one scripting engine in the same file, include
typelibraries, and run more than a single job from one file to name a few.<BR>
<BR>
</A><A name="objectmodel">
<H2>The Object Model</H2>
Implemented as an object-model, WSH provides a simple interface for its tasks. As you author, the
WSH file uses XML as its markup for separating the elements. Let's look at a simple wSH file that
prints "Hello World!".
<UL>
<CODE><Job ID="HelloWorld"><BR>
<script language=PerlScript><BR>
$WScript->Echo("Hello World!");<BR>
</script><BR>
</Job></CODE>
</UL>
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.<BR>
<BR>
</A><A name="wscript">
<H2>The Windows Script Object</H2>
The WScript object is a built-in object; therefore, you do not need to create a specific instance of
it within your WSH. On the contrary, the object in place is used to create instances of most other
objects exposed through the wSH programming interface.<BR>
<BR>
The <CODE>CreateObject</CODE> 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.
<UL>
<CODE><Job ID="Test"><BR>
<script language=PerlScript><BR>
$conn=$WScript->CreateObject('ADODB.Connection');<BR>
$conn->Open(<<EOF);<BR>
Provider=SQLOLEDB;<BR>
User ID=sa;<BR>
Catalog=Northwind;<BR>
EOF<BR>
<BR>
if($conn->{State} == 1) {<BR>
$WScript->Echo("Connection Successful!")<BR>
}<BR>
else {<BR>
$WScript->Echo("Connection Failed ...");<BR>
}<BR>
</script><BR>
</Job></CODE>
</UL>
In addition to the above, you can specify a second parameter in the call to <CODE>CreateObject</CODE>.
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, <CODE>WillConnect</CODE> is called before a connection starts, and <CODE>Connectcomplete</CODE>
is called after a connection has been started. They can be easily intercepted within the wSH file.
<UL>
<CODE><Job ID="Test"><BR>
<script language=PerlScript><BR>
$conn=$WScript->CreateObject('ADODB.Connection', 'MyWSH_');<BR>
$conn->Open(<<EOF);<BR>
Provider=SQLOLEDB;<BR>
User ID=sa;<BR>
Catalog=Northwind;<BR>
EOF<BR>
<BR>
if($conn->{State} == 1) {<BR>
$WScript->Echo("Connection Successful!")<BR>
}<BR>
else {<BR>
$WScript->Echo("Connection Failed ...");<BR>
}<BR>
<BR>
sub MyWSH_ConnectComplete {<BR>
$WScript->Echo("ConnectComplete was fired ... ");<BR>
}<BR>
<BR>
sub MyWSH_WillConnect {<BR>
$WScript->Echo("WillConnect was fired ... ");<BR>
}<BR>
</script><BR>
</Job></CODE>
</UL>
For the same result as above, you can use the <CODE>ConnectObject</CODE>-method whose syntax is <CODE>$WScript->ConnectObject(Object,
Prefix);</CODE>. The method <CODE>$WScript->DisconnectObject(Object);</CODE> will disconnect its
event handling provided that the object is connected. Some other methods are as follows: <CODE>$Wscript->Echo(1,
2, 3, n);</CODE> 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.<BR>
<BR>
<CODE>$WScript->GetObject(Pathname [,ProgID], [Prefix]);</CODE> Retrieves an Automation object
from a file or an object specified by the strProgID parameter.<BR>
<BR>
<CODE>$WScript->Quit([$int_errorcode]);</CODE> Quit and process and optionally provide an integer
which represents an error code.<BR>
<BR>
<CODE>Sleep: $WScript->Sleep($int_milliseconds);</CODE> Places the script process into an
inactive state for the number of milliseconds specified and then continues execution.<BR>
<BR>
And its properties are: <CODE>Application: $WScript->{Application};</CODE> Provides the IDispatch
interface on the WScript object<BR>
<BR>
<CODE>Arguments: $WScript->{Arguments};</CODE> Returns a pointer to the WshArguments collection
or identifies arguments for the shortcut to the collection.<BR>
<BR>
<CODE>Fullname: $WScript->{Fullname};</CODE> Returns a string containing the full path to the
host executable file or shortcut object.<BR>
<BR>
<CODE>Name: $WScript->{Name};</CODE> Returns a string containing the friendly name of the WScript
object.<BR>
<BR>
<CODE>Path: $WScript->{Path};</CODE> Provides a string containing the name of the directory where
WScript.exe or CScript.exe resides.<BR>
<BR>
<CODE>ScriptFullname: $WScript->{Scriptfullname};</CODE> Provides the full path to the script
currently being run.<BR>
<BR>
<CODE>ScriptName: $WScript->{Scriptname};</CODE> Provides the file name of the script currently
being run.<BR>
<BR>
<CODE>StdError: $WScript->{StdError};</CODE> Exposes the write-only error output stream for the
current script. Only applicable with CScript command-line WSH files.<BR>
<BR>
<CODE>StdIb: $WScript->{StdIn};</CODE> Exposes the read-only input stream for the current script.
CScript only.<BR>
<BR>
<CODE>StdOut: $WScript->{StdOut};</CODE> Exposes the write-only output stream for the current
script. CScript only.<BR>
<BR>
<CODE>Version: $WScript->{Version};</CODE> Returns the version of Microsoft Windows Script Host.<BR>
<BR>
On a final note, if you are using Cscript.exe and passing arguments to the file, you can read the
arguments as follows:
<UL>
<CODE><Job ID="args"><BR>
<script language=PerlScript><BR>
$arg = $WScript->{Arguments};<BR>
<BR>
$countArgs = $arg->{Count};<BR>
<BR>
for($i=0; $i<$countArgs; $i++) {<BR>
$WScript->Echo($arg->Item($i));<BR>
}<BR>
</script><BR>
</job></CODE>
</UL>
</A><A name="wshshell">
<H2>The WShShell Object</H2>
The WshShell object must be instantiated by the WScript object.
<UL>
<CODE>$WshShell = $WScript->CreateObject("WScript.Shell")</CODE>
</UL>
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.
<UL>
<CODE><Job Id="WshShell"><BR>
<script language=PerlScript><BR>
$WshShell = $WScript->CreateObject("WScript.Shell");<BR>
$WshShell->Run("notepad");<BR>
$WshShell->AppActivate("Untitled - Notepad");<BR>
<BR>
my($message) = "Hello from PerlScript!\n";<BR>
<BR>
for($i=0; $i<length($message); $i++) {<BR>
$char = substr($message, $i, 1);<BR>
$WScript->Sleep(100);<BR>
$WshShell->SendKeys($char);<BR>
}<BR>
</script><BR>
</job></CODE>
</UL>
The <CODE>SendKeys</CODE>-method simply sends keystrokes to the active windows. The <CODE>Run</CODE>
method is a little more flexible.
<UL>
<CODE>$WshShell->Run(Command, [WindowStyle], [WaitOnReturn]);</CODE>
</UL>
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.</A><A name="shortcut">
<H3>Creating Shortcuts</H3>
In addition, you can create shortcuts. Either you create a dekstop shortcut or a URL shortcul. The
method call <CODE>CreateShortcut($path_or_url)</CODE> returns an object reference to a <CODE>WshShortcut</CODE>-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.<BR>
<BR>
With the WshShortcut-object, one method exists, so it is mainly properties regarding the shortcut
that you need to set. The <CODE>Description</CODE>-property contains a string describing the
shortcut, <CODE>Fullname</CODE> returns the full path to the host executable, <CODE>Hotkey</CODE>
allows for combinations such as "ALT+CTRL+X" as hotkeys for shortcuts on the Windows
dekstop or windows startmenu, <CODE>IconLocation</CODE> is a property that you set to "Path,
index" to provide the Icon location of the shortcut. In addition, use the <CODE>TargetPath</CODE>-property
to set the path to the executable file pointed to by the shortcut, <CODE>WindowStyle</CODE> can be
set to either 1, 3, or 7 for the shortcut object, and <CODE>WorkingDirectory</CODE> defines the
directory in which the shortcut should start. If you are shortcutting a URL, you have only the <CODE>Fullname</CODE>
and <CODE>TargetPath</CODE> properties where the latter one is a URL. All shortcut objects are final
when you call the <CODE>Save</CODE> method.</A><A name="specialfolder">
<H3>Special Folders</H3>
The WshShell object can also return a WshSpecialFolders object which contains paths to shell folders
such as the desktop, start menu, and personal documents.
<UL>
<CODE><Job Id="SpecialFolder"><BR>
<script language=PerlScript><BR>
$WshShell = $WScript->CreateObject("WScript.Shell");<BR>
$numFolders = $WshShell->SpecialFolders->{Count};<BR>
$title = "PerlScript & WSH Example";<BR>
$style = 1;<BR>
<BR>
for($i=0; $i<$numFolders; $i++) {<BR>
$ok_or_cancel = $WshShell->Popup(<BR>
$WshShell->SpecialFolders($i),<BR>
undef,<BR>
$title,<BR>
$style);<BR>
<BR>
exit if ($ok_or_cancel == 2);<BR>
}<BR>
<BR>
</script><BR>
</job></CODE>
</UL>
</A><A name="registry">
<H3>Working With the Registry</H3>
The WshShell object provides functionality for working with the registry. The three methods for this
are: <CODE>RegRead</CODE>, <CODE>RegWrite</CODE>, and <CODE>RegDelete</CODE>. 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
<UL>
<LI>REG_SZ
<LI>REG_EXPAND_SZ
<LI>REG_DWORD
<LI>REG_BINARY
<LI>REG_MULTI_SZ
</UL>
RegWrite requires a few extra parameters:
<UL>
<CODE>$WshShell->RegWrite(Name, Value [,Type]);</CODE>
</UL>
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:
<UL>
<LI>REG_SZ
<LI>REG_EXPAND_SZ
<LI>REG_DWORD
<LI>REG_BINARY
</UL>
</A><A name="misc">
<H3>Miscellanous</H3>
Expands the requested environment variable from the running process:
<UL>
<CODE>$WshShell->ExpandEnvironmentStrings($string);</CODE>
</UL>
In addition, log an event in the NT event log or WSH.log (Windows 9x) file using:
<UL>
<CODE>$WshShell->LogEvent(Type, Message [,Target]);</CODE>
</UL>
Target is the name of the system on NT, thus only applicable on NT. The Type of event is either
<UL>
<LI>0 (SUCCESS)
<LI>1 (ERROR)
<LI>2 (WARNING)
<LI>4 (INFORMATION),
<LI>8 (AUDIT_SUCCESS)
<LI>16 (AUDIT_FAILURE)
</UL>
This method returns a boolean value indicating success or failure. Another method is Popup, which
sends a Windows messagebox up on the screen.
<UL>
<CODE>$retval = $WshShell->Popup(Text, [SecondsWait], [Title], [Type]);</CODE>
</UL>
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:
<UL>
<LI>0 (Ok)
<LI>1 (Ok and Cancel)
<LI>2 (Abort, Retry, and Ignore)
<LI>3 (Yes, No, and Cancel)
<LI>4 (Yes and No)
<LI>5 (Retry and Cancel)
</UL>
The value that you choose can also be combined with an icon:
<UL>
<LI>16 (Stop Mark)
<LI>32 (Question Mark)
<LI>48 (Exclamation Mark)
<LI>64 (Information Mark)
</UL>
The return values returned to <CODE>$retval</CODE> indicates which button was pressed. The value
will be one of the following:
<UL>
<LI>1 (OK)
<LI>2 (Cancel)
<LI>3 (Abort)
<LI>4 (Retry)
<LI>5 (Ignore)
<LI>6 (Yes)
<LI>7 (No)
</UL>
</A><A name="network">
<H2>The WshNetwork Object</H2>
The WshNetwork object exposes some network functionality. To begin:
<UL>
<CODE>$WshNetwork->AddPrinterConnection($LocalName, $RemoteName[,$UpdateProfile][,$User][,$Password]);</CODE>
</UL>
User and password are parameters two parameters with given meaning. Localname and Remotename is the
name 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:
<UL>
<CODE>$WshNetwork->AddWindowsPrinterConnection($PrinterPath, $DriverName[,$Port])</CODE>
</UL>
As easily as adding a printer, you can remove a printer. Simply do <CODE>$WshNetwork->RemovePrinterConnection($Name,
[$Force], [$UpdateProfile]);</CODE> 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.<BR>
<BR>
If you're happy with your printers, you can set one of the printer as your default printer by a
quick call:
<UL>
<CODE>$WshNetwork->SetDefaultPrinter($PrinterName);</CODE>
</UL>
To return a collection of all your printers, call:
<UL>
<CODE>$Printers = $WshNetwork->EnumPrinterConnections();</CODE>
</UL>
Then use the Count-property to retrieve the number of items in the $Printers collection object.<BR>
<BR>
When you want to map a drive to a network share, you can use the MapNetworkDrive method. <CODE>$WshNetwork->MapNetworkDrive($LocalName,
$RemoteName, [$UpdateProfile], [$User], [$Password]);</CODE> For example:
<UL>
<CODE>$WshNetwork->MapNetworkDrive('C:\', '\\MyComputerServer\\ShareHere);</CODE>
</UL>
Remove a network drive using the now familiar syntax <CODE>$WshNetwork->RemoveNetworkDrive($Name,
[$Force], [$UpdateProfile])</CODE> or enumerate the network drives as:
<UL>
<CODE>$Drives = $WshNetwork->EnumNetworkDrive();</CODE>
</UL>
<BR>
<BR>
The three properties of the network object are ComputerName, UserName, and UserDomain.</A><A name="elementref">
<H2>XML Element Reference</H2>
Like Windows Script Components, the Windows Script Host has a set of XML elements that can be
deployed. For a basic understanding of how they are used, please refer to the section about Windows
Script Components.</A><A name="elemjob">
<H3>The Job Element</H3>
The Job element is used to define the beginning and the end of the components. It encapsulates all
other tags. Would your WSH file contain more than one job, encapsulate them within a <PACKAGE>
element. When declaring jobs, the ID attribute is optional. Syntax:
<UL>
<CODE><Job [id=JobID]></CODE>
</UL>
For example:
<UL>
<PRE><CODE><package> </CODE></PRE>
<CODE>
<UL>
<PRE><Job id="PrintOutput">
</Job> </PRE>
</UL>
<UL>
<PRE><Job id="ReadInput">
</Job> </PRE>
</UL>
<PRE></package></CODE></PRE>
</UL>
<BR>
<BR>
You can also set a boolean value of true (1) or false (0) for error checking or debugging by using
the additional tag <CODE><? job error="true" debug="true" ?></CODE><BR>
<BR>
</A>
<PRE><A name="elemscr"> </A></PRE>
<A name="elemscr">
<H3>The Script Element</H3>
The script element lets you define the scripting language to use, and then with its closing-tag
functions as delimiters for the script code. Syntax:
<UL>
<CODE><script language="languageName"> code </script></CODE>
</UL>
For example.
<UL>
<CODE><BR>
<?XML version="1.0"?><BR>
<job><BR>
...<BR>
<script language="PerlScriptt"><BR>
<![CDATA[<BR>
sub ReturnValue {<BR>
#<BR>
# Perl code here<BR>
#<BR>
}<BR>
]]><BR>
</script><BR>
</job></CODE>
</UL>
<BR>
<BR>
</A><A name="elemres">
<H3>The Resource Element</H3>
The resource element is a placeholder for strings or numeric data that should be separate from the
script commands yet may be used within the script. Syntax:
<PRE><resource id="resourceID">
text or number to represent resource goes here
</resource></PRE>
You use the <CODE>getResource(resourceID)</CODE> to retrieve the contents of the resource specified
in the resourceID parameter.<BR>
<BR>
</A>
<PRE><A name="elemref"></A> </PRE>
<H3>The Reference Element</H3>
You can import external type libraries by using the reference element. By importing a type library,
you will be able to naturally access the constants that belongs to it, too. Syntax:
<PRE><reference
[object="progID"|guid="typelibGUID"] [version="versionNo"]
/>
</PRE>
<HR>
<H1><A name="author and copyright">AUTHOR AND COPYRIGHT</A></H1>
<P>Written document copyright (c) 2000 Tobias Martinsson. All rights reserved.</P>
<P>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 <EM>outside</EM> of that package
require that special arrangements be made with copyright holder.</P>
<P>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.</P>
<P>Windows Script Host is copyright (c) 1991-1999 Microsoft Corporation. All Rights Reserved.</P>
<TABLE border="0" cellpadding="0" cellspacing="0" width="100%">
<TR>
<TD class="block" valign="MIDDLE" width="100%" bgcolor="#cccccc"><STRONG>
<P class="block"> Rough Guide to Windows Script Host</P>
</STRONG></TD>
</TR>
</TABLE>
</BODY>
</HTML>