Tải bản đầy đủ (.pdf) (51 trang)

sams teach Yourself windows Script Host in 21 Days phần 7 doc

Bạn đang xem bản rút gọn của tài liệu. Xem và tải ngay bản đầy đủ của tài liệu tại đây (1.79 MB, 51 trang )

Listing 13.2 Using createweb.vbs to Create a Web Site
’ FILE: createweb.vbs
’ DESC: This script illustrates how you can
programmatically
’ create a web site using IIS administration
objects.
’ AUTH: Thomas L. Fredell
’ DATE: 11/23/98

’ Copyright 1998 Macmillan Publishing

Option Explicit

On Error Resume Next

Dim oArgs, sComputer, sHostName, sRootDir
Dim oService, nNewServer, oServer, oVDir, oDir
Dim oFS, sBasePath, sCGIDir
Dim sTmp

’ Step 1: Check script arguments
Set oArgs = Wscript.Arguments
If oArgs.Count <> 4 Then
Wscript.Echo "USAGE: createweb [computer]
[hostname]" & _
" [instance] [rootdir]"
Wscript.Echo ""
Wscript.Echo " Creates a new IIS web site on
"
Wscript.Echo " [computer] using the
[hostname]."


Wscript.Echo " [instance] specifies the web
server"
Wscript.Echo " and [rootdir] specifies the
root"
Wscript.Echo " directory on the file system."
Wscript.Echo ""
Wscript.Quit 1
End If
sComputer = oArgs(0)
sHostName = oArgs(1)
nNewServer = oArgs(2)
sRootDir = oArgs(3)

’ Step 2: Get the object that represents the web service
Set oService = GetObject("IIS://" & sComputer &
"/W3SVC")

’ Step 3: Create a new virtual server
’ Determine the new virtual server number by
Simpo PDF Merge and Split Unregistered Version -
’ iterating through the current servers
oService.GetInfo
Set oServer = oService.Create("IIsWebServer",
nNewServer)
If Err.Number <> 0 Then
ShowErr "Unable to create server."
Wscript.Quit Err.Number
End If

’ Step 4: Configure the new server

oServer.DefaultDoc = "default.htm, index.htm"
oServer.ServerComment = "New server created by
createweb.vbs"
oServer.ConnectionTimeout = 600
oServer.ServerBindings = ":80:" & sHostName
oServer.SetInfo
If Err.Number <> 0 Then
ShowErr "An error occurred while setting
configuration params."
Wscript.Quit Err.Number
End If

’ Step 5: Create virtual root directory for the new site
Set oVDir = oServer.Create("IIsWebVirtualDir", "ROOT")
If Err.Number <> 0 Then
ShowErr "Unable to create virtual root directory."
Wscript.Quit Err.Number
End If

’ Step 6: Configure the virtual root directory
Set oFS = CreateObject("Scripting.FileSystemObject")
sBasePath = oFS.GetAbsolutePathName(sRootDir)
oVdir.Path = sBasePath
oVdir.AccessRead = True
oVdir.AccessWrite = True
oVdir.AccessScript = True
oVdir.SetInfo
If Err.Number <> 0 Then
ShowErr "Unable to save settings for virtual root."
Wscript.Quit Err.Number

End If
oVdir.AppCreate False
If Err.Number <> 0 Then
ShowErr "Unable to define virtual root as
application."
Wscript.Quit Err.Number
End If
oVdir.SetInfo

’ Step 7: Create and configure a cgi-bin directory
’ First ensure that the physical directory exists
Simpo PDF Merge and Split Unregistered Version -
sCGIDir = sBasePath & "\cgi-bin"
If Not oFS.FolderExists(sCGIDir) Then
’ Create the physical cgi-bin directory
oFS.CreateFolder sCGIDir
End If

’ Then create the IIsWebDirectory object & configure it
Set oDir = oVDir.Create("IIsWebDirectory", "cgi-bin")
If Err.Number <> 0 Then
ShowErr "Unable to create cgi-bin directory."
Wscript.Quit Err.Number
End If
oDir.AccessRead = False
oDir.AccessWrite = False
oDir.AccessScript = True
oDir.AccessExecute = True
oDir.SetInfo
If Err.Number <> 0 Then

ShowErr "Error setting cgi-bin configuration."
Wscript.Quit Err.Number
End If

’ Step 8: Start the web server
oServer.Start
If Err.Number <> 0 Then
ShowErr "Unable to start new web server."
Wscript.Quit Err.Number
End If

’ Step 9: Done! Quit execution
Wscript.Echo "createweb.vbs: Successfully created new
web site."
Wscript.Echo "createweb.vbs: Instance #=" & nNewServer
Wscript.Echo "createweb.vbs: Host Name=" & sHostName
Wscript.Echo "createweb.vbs: Root Dir=" & sRootDir
Wscript.Quit 0


’ SUB: ShowErr(Description)
’ DESC: Displays information about a runtime error.

Sub ShowErr(sDescription)
Wscript.Echo "createweb.vbs: " & sDescription
Wscript.Echo "createweb.vbs: An error occurred -
code: " & _
Hex(Err.Number) & " - " & Err.Description
End Sub
You can see the output of the script from the command line in Figure 13.8. If

you go to the Microsoft Management Console, illustrated in Figure 13.9,
you’ll notice that a new Web site has been created.
Simpo PDF Merge and Split Unregistered Version -
Figure 13.8: The command-line output of createweb.vbs.

Figure 13.9: The resulting Web site in the Microsoft Management
Console.

Comments in the script divide the script into different steps. Step one
ensures that the proper arguments have been specified for the script. That’s
a standard step that will be included in any of the sample scripts that take
arguments. Step two retrieves the Web service object using an ADSI path; it
uses the GetObject() function that’s standard for accessing the IIS
administrative objects. Step three creates a new Web server object using the
instance number specified on the command line.
Step four sets some of the properties for the Web server. There are many
properties to choose from; if you examine the code for the first example,
you’ll see a list of them. Step five creates a new virtual root directory for the
Web site, and in step six, it is configured. For the configuration, you set the
path for the root directory, then you set access rights, and finally you set it up
as an out-of-process application.
Step 7 creates and configures the cgi-bin directory. First the code checks
to ensure that the physical cgi-bin directory actually exists. If the physical
directory doesn’t exist, it is created using the FileSystemObject that was
Simpo PDF Merge and Split Unregistered Version -
described in Day 2. Next a Web directory object for cgi-bin is created, and
the access rights are set. The only access that you’ll enable is script and
execute access. That’s plenty of access for the cgi-bin directory and this
will ensure that no one downloads any CGI executables that you put in the
directory.

Finally, step 8 starts the Web server; you check to ensure that it actually
starts by validating that no error occurs. Step 9 stops execution and displays
information about the site that was created.
The script is relatively simple. For the most part, you use the standard ADSI
methods to create new objects. You also use some of the IIS specific
properties to set configuration parameters. You can modify it for your
purposes by creating different objects, such as different directories, or by
setting different properties.
Scanning Sites for Configuration Settings
One of the benefits of using WSH scripts to administer IIS Web servers is
that you can perform automated tasks that would be infeasible or impractical
using the standard Management Console. The script example shown in
Listing 13.3 illustrates a task that would be difficult if not automated. The
following script, scanweb.vbs, scans a Web site and determines whether
any .EXE files are located within directories with either access read or
access write permissions set.
The scanweb.vbs script takes the following arguments, in order:
computer—this is the name of the computer that contains the Web site to
scan, and hostname—this is the hostname of the Web site that you want to
scan.
Listing 13.3 Using scanweb.vbs to Find Configuration Settings
’ FILE: scanweb.vbs
’ DESC: This script illustrates how you can
programmatically
’ scan a web site using IIS administration
objects.
’ AUTH: Thomas L. Fredell
’ DATE: 11/23/98

’ Copyright 1998 Macmillan Publishing


Option Explicit

On Error Resume Next

Dim oArgs, sComputer, sHostName
Dim oService, oServer, oVDir, oFS
Dim sBindings, sToFind, tFound
Dim sTmp

’ Step 1: Check script arguments
Set oArgs = Wscript.Arguments
Simpo PDF Merge and Split Unregistered Version -
If oArgs.Count <> 2 Then
Wscript.Echo "USAGE: scanweb [computer] [hostname]"
Wscript.Echo ""
Wscript.Echo " [computer] = this is the
computer to scan"
Wscript.Echo " [hostname] = this is the
hostname to scan"
Wscript.Echo ""
Wscript.Echo " This scans an IIS web site to
determine if"
Wscript.Echo " executable programs are in
directories"
Wscript.Echo " that have read or write
access."
Wscript.Echo ""
Wscript.Quit 1
End If

sComputer = oArgs(0)
sHostName = oArgs(1)

’ Step 2: Get the object that represents the web service
Set oService = GetObject("IIS://" & sComputer &
"/W3SVC")

’ Step 3: Find the specific web server
oService.GetInfo
sToFind = ":" & sHostName & ":"
tFound = False
For Each oServer In oService
sBindings = Join(oServer.ServerBindings, ":") & ":"
’ sBindings should now be a string in the form:
’ IP1:Port1:Hostname1:IPn:Portn:Hostnamen:
If Err.Number <> 0 Then
Err.Clear
Else
tFound = (InStr(sBindings, sToFind) > 0)
If tFound Then Exit For
End If
Next
If Not tFound Then
Wscript.Echo "scanweb.vbs: Unable to find hostname."
Wscript.Quit 1
End If

’ Step 4: Get the ROOT directory for the site
Set oFS =
Wscript.CreateObject("Scripting.FileSystemObject")

Wscript.Echo "scanweb.vbs: Beginning scan on " &
sHostName
Wscript.Echo ""
Set oVDir = oServer.GetObject("IIsWebVirtualDir",
"ROOT")
Simpo PDF Merge and Split Unregistered Version -
If Err.Number <> 0 Then
ShowErr "Unable to get root directory."
Wscript.Quit Err.Number
End If

’ Step 5: Recursively iterate through the directory &
all
’ sub-directories, checking for .EXE files
ScanDir oVDir, ""

’ Step 6: Done! Quit execution
Wscript.Echo ""
Wscript.Echo "scanweb.vbs: Site scan complete."
Wscript.Quit 0


’ SUB: ScanDir(oDir)
’ DESC: Scans a directory for executable files, then
’ checks directory access permissions.

Sub ScanDir(oDir, sParentPath)
Dim obj
Dim tReadOrWrite
Dim sThisParentPath


If oDir.Class = "IIsWebVirtualDir" Then
sThisParentPath = oDir.Path
Else
sThisParentPath = sParentPath & "\" & oDir.Name
End If
Wscript.Echo "Scanning " & oDir.ADsPath & " "
Wscript.Echo " " & "(" & sThisParentPath &
")"

’ Check if we need to examine this directory for
.exe files
If oDir.AccessRead Or oDir.AccessWrite Then
’ This is a read or write directory, so check
for .exe
Dim oFolder
Dim oFiles
Dim oFile
Dim iFile

’ We scan files using a FileSystemObject,
because
’ we may not get IIsFile objects for every file
Set oFolder = oFS.GetFolder(sThisParentPath)
If Err.Number <> 0 Then
ShowErr "Unable to get folder ’" & _
sThisParentPath & "’."
Simpo PDF Merge and Split Unregistered Version -
Err.Clear
Else

’ Scan files within the directory
Set oFiles = oFolder.Files
For Each oFile In oFiles
If InStr(UCase(oFile.ShortName), ".EXE")
> 0 Then
Wscript.Echo " WARNING: This
" & _
"read or write directory
contains a .exe"
Exit For
End If
Next
If Err.Number <> 0 Then
ShowErr "An error occurred while
checking files."
Err.Clear
End If
End If
End If

Wscript.Echo ""

’ Finally we recurse and check sub-directories
For Each obj In oDir
Select Case obj.Class
Case "IIsWebVirtualDir"
ScanDir obj, sThisParentPath
Case "IIsWebDirectory"
ScanDir obj, sThisParentPath
End Select

Next
End Sub


’ SUB: ShowErr(Description)
’ DESC: Displays information about a runtime error.

Sub ShowErr(sDescription)
Wscript.Echo "scanweb.vbs: " & sDescription
Wscript.Echo "scanweb.vbs: An error occurred -
code:
" & _
Hex(Err.Number) & " - " & Err.Description
End Sub
The scanweb.vbs script enables you to specify a computer and a
hostname to begin a site scan. You’ll run it on the sample Web site that you
created with the previous script, after you’ve added some .EXE files. Figure
13.10 shows a directory listing of the Web site that you’re going to scan. The
results of the scan are illustrated in Figure 13.11.
Simpo PDF Merge and Split Unregistered Version -
Figure 13.10: The directory listing of the Web site that will be
scanned.

If you examine how the script functions, you’ll notice that it begins with the
typical check for correct command-line parameters in step 1. In step 2, you
get an object for the IIsWebService on the specified computer. In step 3,
you iterate through all the IIsWebServer objects associated with the
IIsWebService until a Web server is found that matches the hostname
specified on the command line. The hostname check is done using the
ServerBindings property; ServerBindings is a list of strings in the form

"IP address:Port number:hostname".
Next, in step 4, assuming that you found the correct Web server, you access
the root directory of the Web server. Just before you access the root
directory, you instantiate a WSH FileSystemObject. The
FileSystemObject will be used when you scan directories for the files that
they contain. You begin the directory scanning by calling the ScanDir()
function in step 5.
ScanDir() is where most of the work occurs in this script. It first determine
s
the path for the current directory that is being scanned. If the current
directory is a virtual directory, the Path property returns the correct physical
file directory. However, if it is a standard directory, in other words an
IIsWebDirectory object, it does not have a Path property. Consequently,
you must append the value of the Name property to the parent path to
calculate the physical directory. Next, a message is displayed that indicates
the directory and physical file folder that is being scanned. The AccessRead
and AccessWrite properties of the directory are checked to determine
whether either is enabled. If either is enabled, the physical file directory is
scanned for files with the extension .EXE. If a file is found with the .EXE
extension, a warning message is printed. The example illustrated in Figure
13.11 shows the warning message.
Simpo PDF Merge and Split Unregistered Version -
Figure 13.11: The output from the scanweb.vbs script.

The last part of the ScanDir() function causes the recursion. If the
directory contains any IIsWebDirectory or IIsWebVirtualDir objects,
the ScanDir() function is called with the subdirectory.
The script finishes execution when there are no more directories upon which
to call ScanDir(). Step 6 simply outputs a "finished" message and then
calls the standard Wscript.Quit() function.

Performing Mass Changes to Groups of IIS Web
Sites
Listing 13.4 shows how you can perform mass changes to groups of IIS Web
sites. You’ll provide a put function that enables you to put a specific file
within a directory that matches a regular expression search criterion. This
time you’ve implemented the script using the JScript language because the
language contains inherent support for regular expression searches.
The name of the script is putfile.js
, and you can refer to the source code
in Listing 13.4. The script takes the following arguments, in order:
computer—this is the name of the computer that contains the Web site;
instance—this is the instance number of the Web site; file—this is the
file that you want to put on the Web site; and direxp—this is a regular
expression that will be used to match directories.
Listing 13.4 Using putfile.js to Change Web Site Groups
// FILE: putfile.js
// DESC: This script illustrates how you can
programmatically
// replace a file within a web site using IIS
// administration objects.
// AUTH: Thomas L. Fredell
// DATE: 11/24/98
//
// NOTE: This script uses JScript for regular expression
// functionality, so consequently, with this
Simpo PDF Merge and Split Unregistered Version -
version
// of JScript, there is no capability for robust
// error checking and handling.
//

// Copyright 1998 Macmillan Publishing

var oArgs, sComputer, nInstance, sFile, sDirExp;
var oRootDir, oFS, oRegEx;

// Step 1: Check script arguments
oArgs = WScript.arguments;
if (oArgs.length != 4) {
WScript.echo("USAGE: putfile [computer] [instance]
" +
"[file] [direxp]");
WScript.echo("");
WScript.echo(" [computer] = this is the
computer");
WScript.echo(" to scan");
WScript.echo(" [instance] = this is the web
server");
WScript.echo(" to scan");
WScript.echo(" [file] = this is the file
to");
WScript.echo(" add to the
directory");
WScript.echo(" [direxp] = this is a
regular");
WScript.echo(" expression filter
that");
WScript.echo(" will be used to
match");
WScript.echo(" directories");
WScript.echo("");

WScript.echo(" This puts a specific file in
every");
WScript.echo(" directory that matches a
regular");
WScript.echo(" expression search pattern.");
WScript.echo("");
WScript.quit(1);
}
sComputer = oArgs(0);
nInstance = oArgs(1);
sFile = oArgs(2);
sDirExp = oArgs(3);
oRegEx = new RegExp(sDirExp);

// Step 2: Get the root of the specified web server
oRootDir = GetObject("IIS://" + sComputer + "/W3SVC/" +
nInstance + "/ROOT");

Simpo PDF Merge and Split Unregistered Version -
// Step 3: Iterate through the directories on the web
server
WScript.echo("putfile.js: Beginning scan for matching
directories ");
WScript.echo("");
oFS = new ActiveXObject("Scripting.FileSystemObject");
PutFile(oRootDir, "", sFile, oRegEx);

// Step 4: Done! Quit execution
WScript.echo("");
WScript.echo("putfile.js: Finished adding file to

sites.");
WScript.quit(0);

///////////////////////////////////////////////////////
// FUNC: PutFile(oDir, sParentPath, sFile, oRegEx)
// DESC: Puts a file recursively into matching
// IIsWebDirectory or IIsWebVirtualDir.
///////////////////////////////////////////////////////
function PutFile(oDir, sParentPath, sFile, oRegEx) {
var obj;
var sThisParentPath;
var oFolder;
var enumDirs;

// Determine what the next "parent path" will be
if (oDir.Class == "IIsWebVirtualDir")
sThisParentPath = oDir.Path;
else
sThisParentPath = sParentPath + "\\" +
oDir.Name;

// Check if the current directory name matches the
// directory expression
if (oRegEx.test(oDir.Name)) {
var sFilename, sDestination;

// It matches, so put the file in its directory
WScript.echo("putfile.js: Found matching " +
"directory - " + oDir.Name);


// Get just the file name
sFilename = oFS.getFileName(sFile);

// Calculate the new name & path
sDestination = oFS.buildPath(sThisParentPath,
sFilename);

// Now copy the file
WScript.echo(" Copy " + sFile +
" to " + sDestination);
Simpo PDF Merge and Split Unregistered Version -
oFS.copyFile(sFile, sDestination, true);
}

// Now recurse and check sub-directories
enumDirs = new Enumerator(oDir);
obj = enumDirs.item();
while (obj != null) {
switch (obj.Class) {
case "IIsWebVirtualDir":
case "IIsWebDirectory":
PutFile(obj, sThisParentPath, sFile,
oRegEx);
}
enumDirs.moveNext();
obj = enumDirs.item();
}
}
In Figure 13.12, you’ve run the putfile.js script to place a test.htm file
in all the directories on a Web site. That functionality would enable you to, for

example, automatically replace all the index.htm or default.htm files
throughout a site. Figure 13.13 shows the result when a regular expression
is used as a filter. In that example, you’ve used a filter expression that only
selects directories that begin with the letters cgi You could use that with
your site to replace every instance of a cgi script that you use with an
updated version.
Figure 13.12: Using putfile.js to put the test.htm file in all the
directories of a Web site.

Simpo PDF Merge and Split Unregistered Version -
Figure 13.13: Using putfile.js with the directory filter cgi* to
put the test2.htm file in all directories that begin with the letters cgi.

Like the other scripts, the example begins with a check for command-line
parameters in step 1. In step 2, the root directory of the Web site is
associated with the instance command-line parameter. Step 3 creates an
instance of a FileSystemObject that is used in the PutFile() function.
Then PutFile() is called with the Web site root directory, the name of the
file to put on the site, the parent directory (which at the root is blank), and the
regular expression object that contains the search expression that used to
match directories.
Most of the work in this script occurs in the PutFile() function. It begins by
calculating the current "parent directory." This is necessary because you
need to concatenate the path if the function is called with a standard
IIsWebDirectory object. Next, the function checks the current directory to
determine whether it matches the regular expression filter for the directory
name. If the current directory matches, it determines the new path for the file,
copies the file to the directory, and displays a message indicating that it
copied the file. Finally, PutFile() calls itself recursively with the
subdirectories that it finds. When PutFile() returns, step 4 is executed,

which displays a "Done" message and quits the script.
This script can be useful if you need to perform mass changes to a Web site.
You can reuse the techniques for directory matching that are implemented in
the PutFile() function, and you can replace the functionality that occurs.
For example, instead of putting a file in directories on a site, you could easily
alter this script to delete files. Alternatively, if you only want to change
directory settings on a site, you could replace the logic in PutFile() that
copies files with logic that changes directory settings instead.

Summary
IIS is an excellent Web server with a good administration interface provided by the
Microsoft Management Console. The Management Console works well; however, as
your sites grow, it can become difficult to keep track of and maintain everything.
Consequently, you might want to automate some of your administrative tasks using
scripts. Those scripts can use the IIS administration objects, which provide access to
the IIS metabase that contains IIS administration settings.
Simpo PDF Merge and Split Unregistered Version -
This chapter shows you a few examples of various scripts that use the IIS administration
objects. Those scripts are just the beginning. You can modify them, if they are similar
enough to what you want to accomplish, or you can take ideas from them to create your
own scripts. In any event, if you’re an IIS administrator who is frustrated with the
capabilities of the standard Management Console, now you have the capability to create
your own scripts to automate your IIS administration.

Q&A
Q
What objects can I access using the GetObject() function?
A
Assuming that you can specify the full ADSI path, you can access any IIS
administration objects, anywhere in the hierarchy, directly using GetObject().

Q Will a property in a subobject override an inherited property from a parent
object?
A
Yes, if a property is explicitly set in a subobject, it will override an inherited property.
Q How can I remove properties from subobjects so that they use inherited
properties instead?
A
You can use the PutEx() function to remove properties from subobjects. After
you’ve removed a property from it, the subobject will use the value from an inherited
property.



























Simpo PDF Merge and Split Unregistered Version -

Day 14: Overview of WSH and Application
Scripting Capabilities
By Ian D. Morrish
Overview
WSH includes some useful built-in functions, but the real power comes from the
capability to automate other applications and make use of the Component Object Model
(COM).
Scripting has become the glue that can tie all the pieces together. Whether it is WSH,
Active Server Pages, Commerce Server Pipe Lines, or Transaction Server, you will see
that scripting is everywhere. This chapter will explain the programmer’s terminology that
you need to understand in order to make use of all the cool stuff programmers have
provided in their applications and components.
In this chapter, you will learn about the following:
• Definitions of terms
• Object models
• Tools to help identify component capabilities

Introduction to Scripting Applications
In the old DOS days, you often used a batch file to run a program that could take
command-line parameters. The program would start using these parameters, and the
required action was completed. Windows applications have become so feature-rich that
the number of command-

line options required to support all the possible combinations of
actions that you might want to perform would be unmanageable.
Running Applications the Standard Way
Applications can be run in many ways on the Windows platform:
• From a shortcut to the application
• From the Explorer window
• As batch files
• By file association
For an application such as Microsoft Word, you have limited control over what happens
when you start the application. Using the command line to execute the application, you
can specify a filename to automatically open the application and some switches to
control its behavior, as in the following example:
Winword.exe /tautomate /mstart
Simpo PDF Merge and Split Unregistered Version -
This command causes Word to start, load a template file called automate
, and then run
a macro in that template called start.
Other applications might make more extensive use of command-line options. For
example, PKZip from PKWARE, Inc. ( />), has the following
command-line options:
Usage: PKZIP [options] zipfile [@list] [files ]
-a Add files
-b[drive] create temp zipfile on alternative drive
-d Delete files
-e[xx,x,n,f,s,0] Use [Extreme|eXtra|Normal (default)|Fast|Super
fast|Store]
-f Freshen files
-l display software License agreement
-m[f,u] Move files [with Freshen | with Update]
-u Update files

-p|P store Pathnames|p=recursed into|P=specified &
recursed into
-r Recurse subdirectories
-s[pwd] Scramble with password [If no pwd is given,
prompt for pwd]
-v[b][r][m][t][c] View .ZIP
[Brief][Reverse][More][Technical][Comment] sort by [d,e,n,o,p,s]
[Date|Extension|Name|natural Order(default)|Percentage|Size]
-&[f|u|l Span disks [Format|Unconditional format|Low
density
h|w|v] High density|Wipe disk|enable dos Verify|
[s[drive]] Back up entire disk w/ subdirs (-rp) [drive to
back up]]
Most people would use a GUI-based compression program such as WINZip, but I have
yet to find one that can be automated. The problem with using the DOS program is that
there is a limit to the number of files you can specify on the command line. Long
filenames also have a big impact on this.
Running Applications with Macros
Many Windows applications can be automated by using built-in macro capabilities.
These work well for power users who want to automate common tasks. Macro
languages enable a user to record repetitive tasks so that they can be repeated when
required. They generally require the user to start the application and then to select the
required macro to run. The user then watches the macro perform the actions that would
otherwise be achieved through keyboard or menu actions. Microsoft developed Visual
Basic for Applications to provide powerful automation within applications.
VBA can be used from within an application to automate other applications, but
compared with WSH, it has a much greater overhead.
Running Applications Using OLE Automation
When Microsoft combined a number of applications into an office suite, they found that
people wanted to combine features from one application with the documents created in

another application. For example, a user might want to embed a range of cells from an
Excel spreadsheet in a Word document.
Simpo PDF Merge and Split Unregistered Version -
Dynamic data exchange (DDE) was the first attempt at enabling data and commands to
be sent to other applications. This developed into object linking and embedding (OLE),
which supported drag-and-drop and in-place editing. OLE Automation was developed as
a way of enabling other applications to access the functions of an application.
For example, the menu item in Word to open a document can be automated with the
following script:
Set objWord = Wscript.CreateObject("Word.Application")
appWord.Documents.Open("C:\test.doc")
Note
This is not a complete script, and the next chapter, "Scripting the Microsoft
Office Suite," covers automating Word in more detail.
OLE Automation is exposed through the Component Object Model (COM). COM is also
the basis for many small components (utilities) that have been developed that don’t have
any user interface and can only be accessed through automation. These are often
called ActiveX controls.
Compare the previous PKZip command-line example with this component from Inner
Media Inc.:
Set oZip = Wscript.CreateObject("dzactxctrl.dzactxctrl.1")
oZip.ItemList = "C:\test.doc"
oZip.ZIPFile = "C:\test.zip"
oZip.ActionDZ = 4 ’Add to zip
Wscript.Echo "Done " & oZip.ErrorCode
You can download a 30-day evaluation copy of this control from
/>.
Not all controls are suitable for use with WSH. Some controls require a user interface that
is provided by the hosting application. WSH does not manage windows and cannot use
these types of controls. An example of such a control is the Microsoft ProgressBar

control that is often used in VB applications or in Internet Explorer Web pages.

Definition of Terms
A good understanding of the terms used when describing the use of components and
OLE Automation will help most when you have to talk to a programmer or post
questions to the newsgroups. It will also help you understand what I’m talking about in
the rest of the chapter.
COM (Component Object Model)
This is a standard that defines the interface through which your script or other
components can communicate with a COM component or OLE Automation application.
The term "object" can get very confusing, and most COM objects should just be called
"components."
COM is more significant than the language used to create the component or application
because it is a language-independent standard. It fits in well with the object-oriented
programming methods.
Simpo PDF Merge and Split Unregistered Version -
Interface
An interface is a collection of functions that can be accessed through the name of the
interface. All COM components support at least the Iunknown interface. This provides
the information required by high-level languages to query the component for additional
information. Windows also uses this interface to track the use of the component and
remove it from memory when it is no longer required.
Idispatch is an interface that makes a COM component an Automation object. It is
used by applications that can explore all the interfaces available in a component. Such
an application is the Microsoft OLE Viewer, which you will be looking at later in this
chapter. Most functions of a small component are accessed by WSH through this
interface.
Method
A method is a function that performs an action. Just like a function in VBScript, a
method can also accept parameters. A method usually initiates an action, such as

opening, saving, getting, and putting.
Property
A property is a variable used by a function or attribute of an object. It can be read or
written; however, it can sometimes be read-only. Things such as color, size, height, and
width are properties. This is where you must remember that VBScript only supports
variants, which might not be compatible with some components.
Events
When you call an object’s method, your script will wait for the function to complete if the
object is synchronous. This means that next line of your script will not be executed until
the method you called is complete.
Some objects are asynchronous, which means that program execution will not wait for
the method to complete. In this case, the object will use events to let the calling
application know that a state has changed or a task has been completed. These types
of objects are a bit more difficult to use with WSH because you must make the script
wait for the event to happen.
Object
Within an application, there can be a number of objects that have their own specific
methods and properties. For example, Microsoft Outlook has many objects, including
the following:

Application object

NameSpace object

Explorer object

Folders Collection object

Items Collection object
Simpo PDF Merge and Split Unregistered Version -

To access these objects, you reference them by assigning them a variable name—the
same as creating the application variable. For example, to determine the current folder a
user is viewing in Outlook, you can use the following code:
Set objOL = Wscript.CreateObject("Outlook.Application")
Set olFolder = objOL.ActiveExplorer.CurrentFolder
CurFolder = olFolder
Wscript.Echo "Current folder name = " & CurFolder
The second Set statement (olFolder) has given you a reference to the current folder.
See the description of object models later in this chapter.
Collections
An object is often a container holding a number of items that in turn have properties. For
example, your Inbox is an object within the folders object. Each mail item within the
Inbox has several properties, such as sender's name, date/time sent, subject, and
message text.
You can programmatically iterate through the collection of items with the For Each
statement or the object might support a count property that you can use for the upper
bound of a For Next loop. For example, this code will tell you how many items are
in your currently selected Outlook folder:
Set objOL = Wscript.CreateObject("Outlook.Application")
Set olFolder = objOL.ActiveExplorer.CurrentFolder
CurFolder = olFolder
Set oFolderItems = olFolder.Items ’ get collection of items in
folder
NumItems = oFolderItems.Count
Wscript.Echo "Current folder name = " & CurFolder & vbLF &_
"Number of items = " & NumItems
Note
Outlook collections start at 1, as opposed to arrays, which start at 0.
By adding this code to the previous example, you can access the properties of each
item:

For I = 1 to NumItems
Set oMyItem = oFolderItems(I)
Wscript.Echo oMyItem.Subject
Next
Instantiate
Instantiate is the term used when you
create an instance of an object. WSH does this for
you when you use the Wscript.CreateObject command. This involves loading it
into memory if it is not already there and using the Iunknown interface to register the
fact that WSH is using the object.
Program ID
The program ID is the key piece of information you need to instan
tiate the object you
Simpo PDF Merge and Split Unregistered Version -
How to find the program ID is covered later in this chapter.
There are two Program IDs. A version-independent ID is normally the one you use
unless you want to use methods that are only in a particular version, in which case you
would use the version-specific ID. For example, if you want to use a specific method
available in Outlook 2000, you could use the following command to ensure that an older
version of Outlook is not used:
Set appOutl = Wscript.CreateObject("Outlook.Application.9")
If Err.Number <>0 Then
Wscript.Echo "Outlook 2000 required"
Wscript.Quit()
End If
CLSID
Everything that has a COM interface is defined in the Registry. The CLSID is a unique
128-bit identifier. You will find these in the Registry under
HKEY_CLASSES_ROOT\CLSID. For example, Word 2000 has a CLSID of:
000209FF-0000-0000-C000-000000000046

When you use the Wscript.CreateObject command, the program ID is found in the
Registry, and the relevant CLSID key contains the information Windows needs to make
the object available.
These Registry keys are created when you install an application or register a component
with the regsvr32.exe program.
Type Library
This is an interface (ItypeLib or ItypeInfo) that is not required but is very useful if you
have it. It is a way of documenting the parameters that are supported by each function.
This is how an object viewer application such as the Microsoft OLE Viewer can display
property names and data types supported by an object.

Understanding Object Models
The Object Model is a visual representation of what is available in the COM interface of
a component or OLE–Automation-enabled application (you can also call this an OLE
Automation Server).
A well-documented object model is invaluable when trying to automate a complicated
application such as Microsoft Outlook. You will usually find an object model in the
application's documentation or online help. See Figure 14.1 for an example of the
Outlook 2000 object model.
Simpo PDF Merge and Split Unregistered Version -
Figure 14.1: The Outlook 2000 object model.

You can drill down into each object to get more information by clicking it.
For example, look at the Explorers object. This is a collection of all Outlook windows
(not all of them might be visible). For each window, you can access the CommandBars
object. This is a collection of all menus and toolbars. Having access to this object lets
you execute any menu or toolbar command.
Here is a sample script that will bring up the Out of Office dialog box:
Set objOutlook = Wscript.CreateObject("Outlook.Application")
Set objOlEx = objOutlook.ActiveExplorer

Set objOlCB = objOlEx.CommandBars
Set menu = objOlCB("Menu Bar")
Set Tools = menu.Controls("Tools")
Set myTool = Tools.Controls("Out of Office Assistant ")
myTool.Execute

Active Explorer is a quick way of referencing the currently active Outlook Explorer
window. After you have a reference to the CommandBars object, you can specify the
menu bar and then each menu and submenu just as seen when using the application
interactively.
You can find the name of each toolbar with the following code:
Set objOutlook = Wscript.CreateObject("Outlook.Application")
Set objOlEx = objOutlook.ActiveExplorer
Set objOlCB = objOlEx.CommandBars
For each cbar in objOlCB
Wscript.Echo cbar.Name ’& " " & _
cbar.NameLocal & " " & cbar.Visible
Next

As you can see, the Outlook object model is very powerful, and if it weren’t for COM and
OLE Automation, you would not have access to these features from WSH.
Simpo PDF Merge and Split Unregistered Version -
Here are some links to other object model diagrams available on the Web:

IE4: workingfig01.htm

Office Applications:
OMG/default.htm

Advanced Data Objects:

adosql_2.htm

Tools
You would be surprised how many OLE–Automation-capable applications and COM
components are available on your Windows PC. There are two powerful applications
that can help you understand how to use these objects.
The first is Microsoft's free OLE Viewer. You can download this from
/>. The other is the VBA editor that ships with
Microsoft Office.
OLE Viewer
This application searches the Registry to display a list of all registered objects. You can
view all the objects or list them by category, as seen in Figure 14.2.
Figure 14.2: The OLE/COM object viewer.

The group Grouped by Component Category relates to Internet Explorer, not WSH.
Although you might be able to use some of these controls with WSH, IE will display a
warning if an HTML document contains a component that is not in this category.
Expand the All Objects folder and wait a while (see Figure 14.3). Scroll down to Internet
Explorer (Ver1.0) and expand it.
Simpo PDF Merge and Split Unregistered Version -
Figure 14.3: The All Objects folder in expanded view.

Because this object has an Idispatch interface (third item in the left window), you can
probably automate it. You can see the program ID in the right window.
You can now create an instance of Internet Explorer using the following code:
Set objIE = Wscript.CreateObject("InternetExplorer.Application")
To find what methods and properties are available, double-click the Idispatch
interface and select the View TypeInfo button. Depending on the version of IE, you
might see different results. A typical view is shown in Figure 14.4.
Figure 14.4: Idispatch interface with the View TypeInfo button selected.


If you expand the Inherited Interfaces, you will see even more available methods. This is
where the experimentation starts.
Find the Visible method and highlight it. You will see the following information displayed:
[id(0x00000192), propput, helpstring("Determines whether the
application is visible or hidden.")]HRESULT Visible([in]
VARIANT_BOOL pBool);
Simpo PDF Merge and Split Unregistered Version -
This tells you how to use the method. VARIANT_BOOL means that the value can be 0 or
1, so you can add another line to your script:
objIE.Visible=1
Now, look at the Navigate2 method:
[id(0x000001f4), helpstring("Navigates to a URL or file or
pidl.")]
HRESULT Navigate2(
[in] VARIANT* URL,
[in, optional] VARIANT* Flags,
[in, optional] VARIANT* TargetFrameName,
[in, optional] VARIANT* PostData,
[in, optional] VARIANT* Headers);
This tells you that you must supply the URL as a VARIANT (other parameters are
optional). This is the last line of the script:
objIE.navigate2 " />Two items are shown for most methods. This means that you read and write
parameters. If there is only one item, it will be for [in] (write) or [out] (read-only) use.
VBA Editor
The VBA editor is a little more user-friendly for VBScript developers because VBA has a
lot in common with VBScript.
After starting an Office application, you can access the VBA development environment
by pressing the Alt and F11 keys.
In the Tools menu, select References. Then select Microsoft Internet Controls, as shown

in Figure 14.5.
Figure 14.5: Tools menu in the VBA development environment.

If you want to work with a DLL or OXC not in this list, you can use the Browse icon to
locate the control.
Simpo PDF Merge and Split Unregistered Version -

×