ActiveState!

ActivePerl Documentation
Table of Contents

(Usage Statistics)
(about this ver)


* Getting Started
    * Welcome To ActivePerl
    * Release Notes
    * Readme
    * ActivePerl Change Log
* Install Notes
    * Linux
    * Solaris
    * Windows
* ActivePerl Components
    * Overview
    * PPM
    * Windows Specifics
       * OLE Browser
       * PerlScript
       * Perl for ISAPI
       * PerlEZ
* ActivePerl FAQ
    * Introduction
    * Availability & Install
    * Using PPM
    * Docs & Support
    * Windows Specifics
       * Perl for ISAPI
       * Windows 9X/NT/2000
       * Quirks
       * Web Server Config
       * Web programming
       * Programming
       * Modules & Samples
       * Embedding & Extending
       * Using OLE with Perl
* Windows Scripting
    * Active Server Pages
    * Windows Script Host
    * Windows Script Components

Core Perl Documentation


* perl
* perlfaq
* perltoc
* perlbook

* perlsyn
* perldata
* perlop
* perlreftut
* perldsc
* perllol

* perllexwarn
* perldebug

* perlrun
* perlfunc
* perlopentut
* perlvar
* perlsub
* perlmod
* perlpod

* perlstyle
* perlmodlib
* perlmodinstall
* perltrap
* perlport
* perlsec

* perlref
* perlre
* perlform
* perllocale
* perlunicode

* perlboot
* perltoot
* perltootc
* perlobj
* perlbot
* perltie

* perlipc
* perlnumber
* perlfork
* perlthrtut

* perldiag
* perlfaq1
* perlfaq2
* perlfaq3
* perlfaq4
* perlfaq5
* perlfaq6
* perlfaq7
* perlfaq8
* perlfaq9

* perlcompile

* perlembed
* perlxstut
* perlxs
* perlguts
* perlcall
* perlfilter
* perldbmfilter
* perlapi
* perlintern
* perlapio
* perltodo
* perlhack

* perlhist
* perldelta
* perl5005delta
* perl5004delta

* perlamiga
* perlcygwin
* perldos
* perlhpux
* perlmachten
* perlos2
* perlos390
* perlvms
* perlwin32

Pragmas


* attributes
* attrs
* autouse
* base
* blib
* bytes
* charnames
* constant
* diagnostics
* fields
* filetest
* integer
* less
* lib
* locale
* lwpcook
* open
* ops
* overload
* perllocal
* re
* sigtrap
* strict
* subs
* utf8
* vars
* warnings

Libraries


* ActivePerl
    * DocTools
        * TOC
            * RDF
* AnyDBM_File
* Archive
    * Tar
* AutoLoader
* AutoSplit
* B
    * Asmdata
    * Assembler
    * Bblock
    * Bytecode
    * C
    * CC
    * Debug
    * Deparse
    * Disassembler
    * Lint
    * Showlex
    * Stackobj
    * Terse
    * Xref
* Benchmark
* Bundle
    * LWP
* ByteLoader
* Carp
    * Heavy
* CGI
    * Apache
    * Carp
    * Cookie
    * Fast
    * Pretty
    * Push
    * Switch
* Class
    * Struct
* Compress
    * Zlib
* Config
* CPAN
    * FirstTime
    * Nox
* Cwd
* Data
    * Dumper
* DB
* Devel
    * DProf
    * Peek
    * SelfStubber
* Digest
    * HMAC
    * HMAC_MD5
    * HMAC_SHA1
    * MD2
    * MD5
    * SHA1
* DirHandle
* Dumpvalue
* DynaLoader
* English
* Env
* Errno
* Exporter
    * Heavy
* ExtUtils
    * Command
    * Embed
    * Install
    * Installed
    * Liblist
    * MakeMaker
    * Manifest
    * Miniperl
    * Mkbootstrap
    * Mksymlists
    * MM_Cygwin
    * MM_OS2
    * MM_Unix
    * MM_VMS
    * MM_Win32
    * Packlist
    * testlib
* Fatal
* Fcntl
* File
    * Basename
    * CheckTree
    * Compare
    * Copy
    * CounterFile
    * DosGlob
    * Find
    * Glob
    * Listing
    * Path
    * Spec
        * Functions
        * Mac
        * OS2
        * Unix
        * VMS
        * Win32
    * stat
* FileCache
* FileHandle
* FindBin
* Font
    * AFM
* Getopt
    * Long
    * Std
* HTML
    * AsSubs
    * Element
    * Entities
    * Filter
    * Form
    * FormatPS
    * Formatter
    * FormatText
    * HeadParser
    * LinkExtor
    * Parse
    * Parser
    * TokeParser
    * TreeBuilder
* HTTP
    * Cookies
    * Daemon
    * Date
    * Headers
        * Util
    * Message
    * Negotiate
    * Request
        * Common
    * Response
    * Status
* I18N
    * Collate
* IO
    * Dir
    * File
    * Handle
    * Pipe
    * Poll
    * Seekable
    * Select
    * Socket
        * INET
        * UNIX
* IPC
    * Msg
    * Open2
    * Open3
    * Semaphore
    * SysV
* LWP
    * Debug
    * MediaTypes
    * MemberMixin
    * Protocol
    * RobotUA
    * Simple
    * UserAgent
* Math
    * BigFloat
    * BigInt
    * Complex
    * Trig
* MD5
* MIME
    * Base64
    * QuotedPrint
* NDBM_File
* Net
    * Cmd
    * Config
    * Domain
    * DummyInetd
    * FTP
    * hostent
    * libnetFAQ
    * netent
    * Netrc
    * NNTP
    * PH
    * Ping
    * POP3
    * protoent
    * servent
    * SMTP
    * SNPP
    * Time
* O
* ODBM_File
* Opcode
* Pod
    * Checker
    * Find
    * Html
    * InputObjects
    * Man
    * Parser
    * ParseUtils
    * Plainer
    * Select
    * Text
        * Color
        * Termcap
    * Usage
* POSIX
* PPM
    * SOAPClient
    * SOAPServer
* Safe
* SDBM_File
* Search
    * Dict
* SelectSaver
* SelfLoader
* SHA
* Shell
* SOAP
    * Defs
    * Envelope
    * EnvelopeMaker
    * GenericHashSerializer
    * GenericInputStream
    * GenericScalarSerializer
    * Lite
    * OutputStream
    * Packager
    * Parser
    * Transport
        * HTTP
            * Apache
            * CGI
            * Client
            * Server
        * LOCAL
        * MAILTO
        * POP3
        * TCP
    * TypeMapper
* Socket
* Symbol
* Sys
    * Hostname
    * Syslog
* Term
    * ANSIColor
    * Cap
    * Complete
    * ReadLine
* Test
    * Harness
* Text
    * Abbrev
    * ParseWords
    * Soundex
    * Tabs
    * Wrap
* Thread
    * Queue
    * Semaphore
    * Signal
    * Specific
* Tie
    * Array
    * Handle
    * Hash
    * RefHash
    * Scalar
    * SubstrHash
* Time
    * gmtime
    * Local
    * localtime
    * tm
* UDDI
    * Lite
* UNIVERSAL
* URI
    * data
    * Escape
    * file
    * Heuristic
    * ldap
    * URL
    * WithBase
* User
    * grent
    * pwent
* Win32
    * AuthenticateUser
    * ChangeNotify
    * Clipboard
    * Console
    * Event
    * EventLog
    * File
    * FileSecurity
    * Internet
    * IPC
    * Mutex
    * NetAdmin
    * NetResource
    * ODBC
    * OLE
        * Const
        * Enum
        * NEWS
        * NLS
        * TPJ
        * Variant
    * PerfLib
    * Pipe
    * Process
    * Registry
    * Semaphore
    * Service
    * Sound
    * TieRegistry
* Win32API
    * File
    * Net
    * Registry
* WWW
    * RobotRules
        * AnyDBM_File
* XML
    * Element
    * Parser
        * Expat
    * PPD
    * PPMConfig
    * ValidatingElement
* XSLoader

 Rough Guide to Windows Script Host


Windows Script Host (ASP)

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.

Running a WSH File

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.

The Object Model

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!".
    <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.

The Windows Script Object

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.

The 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="Test">
    <script language=PerlScript>
    $conn=$WScript->CreateObject('ADODB.Connection');
    $conn->Open(<<EOF);
    Provider=SQLOLEDB;
    User ID=sa;
    Catalog=Northwind;
    EOF

    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(<<EOF);
    Provider=SQLOLEDB;
    User ID=sa;
    Catalog=Northwind;
    EOF

    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.

Sleep: $WScript->Sleep($int_milliseconds); Places the script process into an inactive state for the number of milliseconds specified and then continues execution.

And its properties are: Application: $WScript->{Application}; Provides the IDispatch interface on the WScript object

Arguments: $WScript->{Arguments}; Returns a pointer to the WshArguments collection or identifies arguments for the shortcut to the collection.

Fullname: $WScript->{Fullname}; Returns a string containing the full path to the host executable file or shortcut object.

Name: $WScript->{Name}; Returns a string containing the friendly name of the WScript object.

Path: $WScript->{Path}; Provides a string containing the name of the directory where WScript.exe or CScript.exe resides.

ScriptFullname: $WScript->{Scriptfullname}; Provides the full path to the script currently being run.

ScriptName: $WScript->{Scriptname}; Provides the file name of the script currently being run.

StdError: $WScript->{StdError}; Exposes the write-only error output stream for the current script. Only applicable with CScript command-line WSH files.

StdIb: $WScript->{StdIn}; Exposes the read-only input stream for the current script. CScript only.

StdOut: $WScript->{StdOut}; Exposes the write-only output stream for the current script. CScript only.

Version: $WScript->{Version}; Returns the version of Microsoft Windows Script Host.

On a final note, if you are using Cscript.exe and passing arguments to the file, you can read the arguments as follows:
    <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>

The WShShell Object

The WshShell object must be instantiated by the WScript object.
    $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.

Creating Shortcuts

In addition, you can create shortcuts. Either you create a dekstop shortcut or a URL shortcul. The method call 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.

With the WshShortcut-object, one method exists, so it is mainly properties regarding the shortcut that you need to set. The 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.

Special Folders

The WshShell object can also return a WshSpecialFolders object which contains paths to shell folders such as the desktop, start menu, and personal documents.
    <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>

Working With the Registry

The WshShell object provides functionality for working with the registry. The three methods for this are: 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
  • REG_SZ
  • REG_EXPAND_SZ
  • REG_DWORD
  • REG_BINARY
  • REG_MULTI_SZ
RegWrite requires a few extra parameters:
    $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

Miscellanous

Expands the requested environment variable from the running process:
    $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
  • 0 (SUCCESS)
  • 1 (ERROR)
  • 2 (WARNING)
  • 4 (INFORMATION),
  • 8 (AUDIT_SUCCESS)
  • 16 (AUDIT_FAILURE)
This method returns a boolean value indicating success or failure. Another method is Popup, which sends a Windows messagebox up on the screen.
    $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:
  • 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 value that you choose can also be combined with an icon:
  • 16 (Stop Mark)
  • 32 (Question Mark)
  • 48 (Exclamation Mark)
  • 64 (Information Mark)
The return values returned to $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)

The WshNetwork Object

The WshNetwork object exposes some network functionality. To begin:
    $WshNetwork->AddPrinterConnection($LocalName, $RemoteName[,$UpdateProfile][,$User][,$Password]);
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:
    $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.

If you're happy with your printers, you can set one of the printer as your default printer by a quick call:
    $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.

When you want to map a drive to a network share, you can use the MapNetworkDrive method. $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.

XML Element Reference

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.

The Job Element

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:
    <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" ?>

 

The Script Element

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:
    <script language="languageName"> code </script>
For example.

    <?XML version="1.0"?>
    <job>
    ...
    <script language="PerlScriptt">
    <![CDATA[
    sub ReturnValue {
    #
    # Perl code here
    #
    }
    ]]>
    </script>
    </job>


The Resource Element

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:
<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.

 

The Reference Element

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:
<reference
    [object="progID"|guid="typelibGUID"] [version="versionNo"]
/>

AUTHOR AND COPYRIGHT

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-1999 Microsoft Corporation. All Rights Reserved.

 Rough Guide to Windows Script Host