Sunteți pe pagina 1din 4

Tutorial:Operating Systems

Understanding The
Windows Scripting Host
Automating common tasks for users is relatively easy with the Scripting Host built into Windows.

By Julian Moss

O ne of Windows’s most notable


deficiencies when compared
with other operating systems
is its lack of a batch language for auto-
dows 98. It can be also be downloaded
from www.microsoft.com/scripting
to install on Windows 95 and NT 4.0
[and is lso on this month’s CD-ROM -
other script languages. Once the en-
gines are registered with the system
these script languages can be used in
any scripting host. Microsoft has pro-
mating tasks. Although the underlying Ed.]. Documentation for the Microsoft duced two script languages, VBScript
MS-DOS supports batch files, they are script engines can be viewed online at and JavaScript. Engines for other
of little use in the Windows environ- http://www.microsoft.com-/scripti popular script languages like Perl and
ment: under Windows 3.1 you can’t ng/start.HTM. Rexx will doubtless soon appear. In
even launch Windows programs from this article we will focus on using
batch files. Scripting Architecture VBScript, but all of the examples given
Support staff wishing to automate here could be implemented equally
tasks for their users have been forced Internet Explorer 3.0 introduced the well using JavaScript.
to use third-party tools like Wilson capability of client-side scripting, us-
WinBatch or JP Software’s Take Com- ing script code embedded in HTML Independence
mand. Because these tools are not part pages. Instead of making this a dedi-
of Windows, they must be separately cated feature of Internet Explorer, Mi- The key point about the scripting
installed before they can be used. Li- crosoft designed the facility in such a architecture is that script engines and
censing of these tools means that addi- way that scripting could be incorpo- scripting hosts are independent of one
tional costs are often incurred, which, rated into other applications as well. another. Script engines may incorpo-
if the budget is not available, becomes The application - in this case Internet rate some functionality of their own,
a problem. Explorer - is the scripting host, and but the greater part of the power of
This limitation of Windows was re- exposes various COM objects that a scripting comes from the script’s abil-
moved with the advent of the Win- script can manipulate. ity to use the objects exposed by the
dows Scripting Host (WSH). Available In the WSH, the objects that are pro- host. Scripts can also create OLE Auto-
since the release of Internet Explorer vided allow scripts to control certain fea- mation objects of other applications on
3.0, Microsoft originally kept quiet tures of the operating system. Microsoft the system such as Microsoft Word
about the facility. This is no longer the produces one other scripting host: In- and Microsoft Excel, which allows
case, and the WSH is one of the stand- ternet Information Server (IIS), which them to control these applications.
ard accessories to be included in Win- uses the same script language for server- Scripting is a simple and very pow-
side scripting. Other developers may erful way to automate tasks under
‘ Hello world! Example script
also write applications that are script- Windows. You can create scripts using
MsgBox(“Hello world!”)
ing hosts since Microsoft has publish- a text editor such as Notepad, and save
ed the specification for doing so. them to disk as plain text files. When
Microsoft has also documented the you run a script, the file extension of
Figure 1 - The simplest VBS script. interface for script engines. This will the script file tells the Windows Script-
allow developers to write engines for ing Host what language has been used.
VBScript scripts must have the exten-
‘ Example showing how to obtain command line arguments sion .VBS. JavaScript scripts use the
Dim Args, ArgList extension .JS.
Args = WScript.Arguments The default Open action associated
For i = 0 to Args.Count - 1 with script files is to run the script. To
ArgList = ArgList & i & “: ” & Args(i) & chr(13) run a script you (or a user) needs sim-
Next ply to double-click its icon. To have a
MsgBox “No. of arguments: ” & Args.Count & chr(13) & ArgList script run automatically when Win-
dows starts just create a shortcut to it
in the StartUp group. To make changes
Figure 2 - ARGS.VBS - Command line arguments. to a user’s system you could send the

Update 116 (June 1998) Page 17


PC Support Advisor File: T1205.1
Tutorial:Operating Systems

script to the user as an attachment to a The simplest possible script is shown using the standard syntax Sub/End
mail message and have them run it by in Figure 1 which, following the time- Sub or Function/End Function. These
opening the attachment. Scripts can honoured tradition for programming subroutines and functions are ignored
even be run from batch files or a com- texts, displays the message “Hello on the first pass through the script file,
mand prompt by running the program world!” The example is twice as long and only executed when they are
CSCRIPT.EXE with the script file name as it needs to be because the first line is called by script commands.
as the first parameter to the command. a comment.
As you can see from this example, Omissions
Writing Scripts scripts need no additional structure
commands. Script commands are exe- The VBScript language will be fa-
Scripts can be very simple. Just like cuted sequentially from start to finish. miliar to anyone who has used Visual
a batch file, a script can consist of a However, within a script you can de- Basic or Visual Basic for Applications
sequence of commands to be executed. fine BASIC subroutines and functions (VBA.) However it is not a complete
implementation of VBA. Microsoft has
made a number of simplifications in
Dim Dict ‘Create an instance
order to produce a script language that
Set Dict = CreateObject(“Scripting.Dictionary”)
is both lean and fast. For example, there
Dict.Add “a”, “Athens” ‘Add some keys and items
is no GOSUB or WITH statement, and
Dict.Add “b”, “Belgrade”
the On...Goto construct is not supported.
Dict.Add “c”, “Cairo” Arrays must be zero-based. There is no
Dict.Add “d”, “Doncaster” Static keyword. The DDE Link com-
Dict.Add “e”, “Eastwood” mands are not supported, and you can-
key = InputBox(“Enter a letter a - e”) not access the Clipboard from a script.
MsgBox “Item selected: ” & Dict.Item(key)

Additions
Figure 3 - DICTIONARY.VBS - Using a Dictionary object.
VBScript has several features of its
own that are not found in VBA. There
‘ update one file with another is a special group of functions for for-
‘ if modification time is later matting numbers, currency and date
Function Update( source, target ) values, and a group of constants for
Dim f1,f2,d1,d2,c1,c2 obtaining the current date and time.
if fs.FileExists( source ) then New string processing functions in-
‘ source file is accessible clude Join and Split for converting be-
set f1 = fs.GetFile( source ) tween arrays and strings of
d1 = f1.DateLastModified delimiter-separated values. To help
c1 = Year(d1) * 10000 + Month(d1) * 100 + Day(d1) you avoid compatibility problems
if fs.FileExists( target ) then there are functions for obtaining the
set f2 = fs.GetFile( target ) version of the script engine in use.
d2 = f2.DateLastModified VBScript is not an alternative to full-
c2 = Year(d2) * 10000 + Month(d2) * 100 + Day(d2) blown programming languages, even
else if you are prepared to live with the fact
c2 = 0 that scripts are written in plain text for
end if all to see and tinker with. You cannot
if c1 > c2 then create forms or dialog boxes, so the
‘ overwrite local copy with new version possibilities for creating scripts that in-
f1.Copy target,True teract with the user are limited. You
end if can display message boxes with
end if Yes/No or OK/Cancel buttons, and a
End Function rather clunky input box that displays a
‘ begin script execution prompt and allows the user to enter
Dim fs some text. If your application requires
set fs = WScript.CreateObject(“Scripting.FileSystemObject”) a greater degree of interaction than that
s = “\\Server\Server_c\AVP\sigfile.dat” you will need to fire up Visual Basic.
t = “C:\AVP\sigfile.dat” Functionality specific to the Win-
update s, t dows Scripting Host is accessed using
its primary object WScript. This object
is always present, and so does not have
Figure 4 - UPDATE.VBS - Update local file from server to be created. It provides several im-

File: T1205.2
PC Support Advisor Update 116 (June 1998) Page 18
Tutorial:Operating Systems

Scripting Host

portant methods such as CreateObject dragging files and dropping them on a folders. FileSystemObject objects have
which is used to create instances of script icon or shortcut. methods that themselves return objects
other objects, and Quit which allows VBScript provides two types of ob- representing drives, folders and files.
you to terminate a script before the end ject, defined by the built-in Scripting These objects can be used to get informa-
of the script file. object, which you are likely to find use- tion such as the attributes of a folder or
The WScript object has an Argu- ful in your scripts. Dictionary objects the size and modification date of a file.
ments property which can be used to can be used to hold indexed lists of FileSystemObject has too manyprop-
obtain the command line arguments data in a manner similar to a Perl asso- erties and methods to cover in detail
passed to a script. This is illustrated in ciative array. Figure 3 gives a brief taste here, but an example of its use is shown
Figure 2, which displays the argu- of how they are used. in Figure 4. This script, or a derivation
ments in a message box. Command of it, could be launched from a user’s
line arguments for a script can be speci- File Access StartUp group, and will run silently in
fied following the script filename in the the background when the PC starts. It
Target field of a shortcut, or when run- The FileSystemObject object is one compares the modification date of a
ning a script from a command prompt of the most important objects available file on a network server with the modi-
using CSCRIPT. Unfortunately scripts to your scripts. It allows them to carry fication date of the same file on the
are not treated by Windows as an ex- out file management activities like test- local hard disk. If the server copy is
ecutable file type so you can’t pass file- ing whether files or folders exist and newer it is copied to the local system.
names to them dynamically by copying, deleting and moving files and A script working along these lines
could be used to update the signature
files for a workstation’s anti-virus soft-
Dim WSHShell, fs ware from copies kept on the server.
Set WSHShell = WScript.CreateObject(“WScript.Shell”)
Set fs = WScript.CreateObject(“Scripting.FileSystemObject”)
Walk-Through
Function MakeDesktopShortcut( name, target ) A brief explanation of the code in
Dim Shortcut,DesktopPath,StartupPath Figure 4 may be beneficial. Note that
DesktopPath = WSHShell.SpecialFolders(“Desktop”) the code for updating the file has been
Set Shortcut = WSHShell.CreateShortcut(DesktopPath & “\” & written as a function. This makes it a
name & “.lnk”) generic function that could be called
Shortcut.TargetPath = target multiple times with different argu-
StartupPath = fs.GetParentFolderName( target ) ments to update a number of different
If fs.FolderExists( StartupPath ) then files if you so wished. Execution of the
Shortcut.WorkingDirectory = StartupPath script begins by declaring and creating
End If the FileSystemObject object which is
Shortcut.Save needed in order for many of the func-
End Function tions used by the Update function to
become available. Variables s and t are
MakeDesktopShortcut “Shortcut to Notepad”, “C:\Windows\- initialised to the source and target file-
Notepad.exe” names. This isn’t necessary: the file-
names could be specified as constants
when the function “update” is called.
Figure 5 - SHORTCUT.VBS - Create a shortcut on the desktop. The function first checks to see if the
source file exists. If it cannot be found
for any reason - even if the server is
Dim WSHNet, fs inaccessible - the FileExists function
Set WSHNet = WScript.CreateObject(“WScript.Network”) simply returns False and nothing more
set fs = WScript.CreateObject(“Scripting.FileSystemObject”) is done. If the file is found then a file
object f1 is created for it. This is used to
Function MapDrive( letter, UNCname) obtain the file’s modification date. Be-
If fs.DriveExists( UNCname) Then cause this is returned as a text string in
WSHNet.MapNetworkDrive letter, UNCname d1 it must be converted to an integer
End If value c1 for comparison. As we are
End Function only interested in whether one file is
newer than another, and not by pre-
MapDrive “E:”, “\\DARWIN\DARWIN_C” cisely how many days, a simple con-
MapDrive “F:”, “\\DARWIN\DARWIN_D” version to the form yyyymmdd is used.
The modification date d2 for the
Figure 6 - MAPDRIVE.VBS - Map network drives. second file is found in a similar way. If

Update 116 (June 1998) Page 19


PC Support Advisor File: T1205.3
Tutorial:Operating Systems

the file does not exist at all the value for generic function MakeDesktop- The function MapDrive uses the
comparison c2 is set to 0. The two val- Shortcut which, as the name suggests, FileSystemObject method DriveExists
ues are then compared, and if c1 is creates a shortcut on the user’s desk- to test whether the network volume is
greater than c2 file f1 is copied to the top. The function takes two arguments: accessible using its UNC name. If the
target filename, overwriting the pre- name, which is the name of the short- drive is found, the MapNetworkDrive
vious version if it existed. cut, and target, which is the filename method of the WScript.Network object
Two other methods of the FileSys- or URL which is launched when the is used to make the connection. With-
temObject object which we won’t go shortcut is double-clicked. out the test, the script would fail with
into here, OpenTextFile and CreateText- The function uses the SpecialFold- an error message if the network vol-
File, create TextStream objects. These ers method of the Shell object to obtain ume was not accessible when it tried to
objects have methods that allow you to the location of the Windows desktop map it.
read from and write to text files in a for the current user. It then creates a
serial manner. It is not difficult to see shortcut object using the Shell method OLE
how you could enhance the function- CreateShortcut. The shortcut’s Target-
ality of the code in Figure 4 by using Path property is set to the filename or As mentioned earlier, scripts can cre-
TextStream objects to read a file con- URL. Two FileSystemObject methods, ate and use automation objects exposed
taining a list of the files to be updated GetParentFolderName and FolderEx- by any Windows application that sup-
or write a log of updates carried out. ists, are used to set the working direc- ports OLE Automation. This includes
A by-product of this capability is tory to the folder containing the target. all the major Office suites and many
that it would be possible to write If this is an Internet URL the result of other applications that claim to be Mi-
scripts that create or modify other GetParentFolder is invalid, so the crosoft Office compatible. Though
scripts. Whilst this is unlikely to be WorkingDirectory property is only set many of these applications may have
generally very useful, it does seem to if the folder actually exists. The Save script languages of their own, it may
make the possibility of script file vi- method of the Shortcut object must be often be more convenient to script
ruses at least technically possible. used to actually create the shortcut file them using a standalone, application-
on the hard disk. independent script language. Figure 7
Shell Object shows a very trivial illustration of how
Network Object to automate Microsoft Word by creat-
Besides the objects that are pro- ing a new document, inserting some
vided by VBScript and hence available The other object provided by text in it, saving the document and
to scripts running under Internet Ex- WScript is the Network object. This lets closing it. The purpose of the example
plorer or IIS, two important objects are you find out information like the user is simply to show that it can be done,
provided by the WScript object of the name, computer name and organisa- using exactly the same commands as
Windows Scripting Host. The Shell ob- tion name. It also lets you connect and would be used in Visual Basic or VBA.
ject has a number of useful functions. disconnect network drives, add and
It allows you to find out the location of remove printer connections and set the Conclusion
special folders such as the Windows default printer.
desktop or Start Menu, to obtain the Figure 6 is a short script that maps The Windows Scripting Host is the
contents of MS-DOS environment network drives if they are accessible. In tool that Windows has needed since its
strings, to run programs, pop up mes- some situations this may be preferable inception. It fulfils admirably the func-
sage boxes (a function that is more or to the normal Windows mechanism tion of a batch language and automat-
less duplicated by the VBScript which displays a warning message if it ion tool, whilst its ability to automate
MsgBox function), create shortcuts is unable to connect to a drive. How- other applications extends its power
and read from, write to or delete keys ever, the real value of the example is to tremendously. Support professionals
in the Windows Registry. illustrate how it can be done so that will undoubtedly find it to be a valu-
Figure 5 illustrates some of the fea- you can create scripts that map drives able tool. But many advanced users
tures of the Shell object. It contains a using a degree of intelligence. may also enjoy the facility to write
scripts that make their time at the key-
board more productive.
Dim MSWord, WSHShell
Set WSHShell = WScript.CreateObject(“WScript.Shell”) PCSA
Set MSWord = WScript.CreateObject(“Word.Basic”)
MSWord.FileNew(“Normal”)
MSWord.Insert(“The quick brown fox jumps over” & Chr(13)) The Author
MSWord.Insert(“the lazy dog.”)
MSWord.FileSaveAs(WSHShell.SpecialFolders(12) & “\Test.doc”) Julian Moss is a freelance technical
MSWord.FileClose writer and software developer. He
can be contacted by email as
jmoss@cix.co.uk.
Figure 7 - WORD.VBS - Automating Microsoft Word

File: T1205.4
PC Support Advisor Update 116 (June 1998) Page 20

S-ar putea să vă placă și