WSH Window Scripting

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

Transcript of WSH Window Scripting

Page 1: WSH Window Scripting

One of Windows’s most notabledeficiencies when comparedwith other operating systems

is its lack of a batch language for auto-mating tasks. Although the underlyingMS-DOS supports batch files, they areof little use in the Windows environ-ment: under Windows 3.1 you can’teven launch Windows programs frombatch files.

Support staff wishing to automatetasks for their users have been forcedto use third-party tools like WilsonWinBatch or JP Software’s Take Com-mand. Because these tools are not partof Windows, they must be separatelyinstalled before they can be used. Li-censing of these tools means that addi-tional costs are often incurred, which,if the budget is not available, becomesa problem.

This limitation of Windows was re-moved with the advent of the Win-dows Scripting Host (WSH). Availablesince the release of Internet Explorer3.0, Microsoft originally kept quietabout the facility. This is no longer thecase, and the WSH is one of the stand-ard accessories to be included in Win-

dows 98. It can be also be downloadedfrom www.microsoft.com/scriptingto install on Windows 95 and NT 4.0[and is lso on this month’s CD-ROM -Ed.]. Documentation for the Microsoftscript engines can be viewed online athttp://www.microsoft.com-/scripting/start.HTM.

Scripting ArchitectureInternet Explorer 3.0 introduced the

capability of client-side scripting, us-ing script code embedded in HTMLpages. Instead of making this a dedi-cated feature of Internet Explorer, Mi-crosoft designed the facility in such away that scripting could be incorpo-rated into other applications as well.The application - in this case InternetExplorer - is the scripting host, andexposes various COM objects that ascript can manipulate.

In the WSH, the objects that are pro-vided allow scripts to control certain fea-tures of the operating system. Microsoftproduces one other scripting host: In-ternet Information Server (IIS), whichuses the same script language for server-side scripting. Other developers mayalso write applications that are script-ing hosts since Microsoft has publish-ed the specification for doing so.

Microsoft has also documented theinterface for script engines. This willallow developers to write engines for

other script languages. Once the en-gines are registered with the systemthese script languages can be used inany scripting host. Microsoft has pro-duced two script languages, VBScriptand JavaScript. Engines for otherpopular script languages like Perl andRexx will doubtless soon appear. Inthis article we will focus on usingVBScript, but all of the examples givenhere could be implemented equallywell using JavaScript.

IndependenceThe key point about the scripting

architecture is that script engines andscripting hosts are independent of oneanother. Script engines may incorpo-rate some functionality of their own,but the greater part of the power ofscripting comes from the script’s abil-ity to use the objects exposed by thehost. Scripts can also create OLE Auto-mation objects of other applications onthe system such as Microsoft Wordand Microsoft Excel, which allowsthem to control these applications.

Scripting is a simple and very pow-erful way to automate tasks underWindows. You can create scripts usinga text editor such as Notepad, and savethem to disk as plain text files. Whenyou run a script, the file extension ofthe script file tells the Windows Script-ing Host what language has been used.VBScript scripts must have the exten-sion .VBS. JavaScript scripts use theextension .JS.

The default Open action associatedwith script files is to run the script. Torun a script you (or a user) needs sim-ply to double-click its icon. To have ascript run automatically when Win-dows starts just create a shortcut to itin the StartUp group. To make changesto a user’s system you could send the

Update 116 (June 1998) Page 17 File: T1205.1

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

By Julian Moss

Understanding TheWindows Scripting Host

‘ Hello world! Example script

MsgBox(“Hello world!”)

Figure 1 - The simplest VBS script.

‘ Example showing how to obtain command line arguments

Dim Args, ArgList

Args = WScript.Arguments

For i = 0 to Arg s.Count - 1

ArgList = ArgList & i & “: ” & Arg s(i) & chr(13)

Next

MsgBox “No. of arguments: ” & Args.Count & chr(13) & ArgList

Figure 2 - ARGS.VBS - Command line arguments.

PC Support Advisor

Tutorial:Operating Systems

Page 2: WSH Window Scripting

script to the user as an attachment to amail message and have them run it byopening the attachment. Scripts caneven be run from batch files or a com-mand prompt by running the programCSCRIPT.EXE with the script file nameas the first parameter to the command.

Writing ScriptsScripts can be very simple. Just like

a batch file, a script can consist of asequence of commands to be executed.

The simplest possible script is shownin Figure 1 which, following the time-honoured tradition for programmingtexts, displays the message “Helloworld!” The example is twice as longas it needs to be because the first line isa comment.

As you can see from this example,scripts need no additional structurecommands. Script commands are exe-cuted sequentially from start to finish.However, within a script you can de-fine BASIC subroutines and functions

using the standard syntax Sub/EndSub or Function/End Function. Thesesubroutines and functions are ignoredon the first pass through the script file,and only executed when they arecalled by script commands.

OmissionsThe VBScript language will be fa-

miliar to anyone who has used VisualBasic or Visual Basic for Applications(VBA.) However it is not a completeimplementation of VBA. Microsoft hasmade a number of simplifications inorder to produce a script language thatis both lean and fast. For example, thereis no GOSUB or WITH statement, andtheOn...Gotoconstruct isnotsupported.Arrays must be zero-based. There is noStatic keyword. The DDE Link com-mands are not supported, and you can-not access the Clipboard from a script.

AdditionsVBScript has several features of its

own that are not found in VBA. Thereis a special group of functions for for-matting numbers, currency and datevalues, and a group of constants forobtaining the current date and time.New string processing functions in-clude Join and Split for converting be-tween arrays and strings ofdelimiter-separated values. To helpyou avoid compatibility problemsthere are functions for obtaining theversion of the script engine in use.

VBScript is not an alternative to full-blown programming languages, evenif you are prepared to live with the factthat scripts are written in plain text forall to see and tinker with. You cannotcreate forms or dialog boxes, so thepossibilities for creating scripts that in-teract with the user are limited. Youcan display message boxes withYes/No or OK/Cancel buttons, and arather clunky input box that displays aprompt and allows the user to entersome text. If your application requiresa greater degree of interaction than thatyou will need to fire up Visual Basic.

Functionality specific to the Win-dows Scripting Host is accessed usingits primary object WScript. This objectis always present, and so does not haveto be created. It provides several im-

File: T1205.2 Update 116 (June 1998) Page 18

‘ update one file with another

‘ if modification time is later

Function Update( source, target )

Dim f1,f2,d1,d2,c1,c2

if fs.FileExists( source ) then

‘ source file is accessible

set f1 = fs.GetFile( source )

d1 = f1.DateLastModified

c1 = Year(d1) * 10000 + Month(d1) * 100 + Day(d1)

if fs.FileExists( target ) then

set f2 = fs.GetFile( target )

d2 = f2.DateLastModified

c2 = Year(d2) * 10000 + Month(d2) * 100 + Day(d2)

else

c2 = 0

end if

if c1 > c2 then

‘ overwrite local copy with new version

f1.Copy target,True

end if

end if

End Function

‘ begin script execution

Dim fs

set fs = WScript.CreateObject(“Scripting.FileSystemObject”)

s = “\\Server\Server_c\AVP\sigfile.dat”

t = “C:\AVP\sigfile.dat”

update s, t

Figure 4 - UPDATE.VBS - Update local file from server

Dim Dict ‘Create an instance

Set Dict = CreateObject(“Scripting.Dictionary”)

Dict.Add “a”, “Athens” ‘Add some keys and items

Dict.Add “b”, “Belgrade”

Dict.Add “c”, “Cairo”

Dict.Add “d”, “Doncaster”

Dict.Add “e”, “Eastwood”

key = InputBox(“Enter a letter a - e”)

MsgBox “Item selected: ” & Dict.Item(key)

Figure 3 - DICTIONARY.VBS - Using a Dictionary object.

PC Support Advisor

Tutorial:Operating Systems

Page 3: WSH Window Scripting

portant methods such as CreateObjectwhich is used to create instances ofother objects, and Quit which allowsyou to terminate a script before the endof the script file.

The WScript object has an Argu-ments property which can be used toobtain the command line argumentspassed to a script. This is illustrated inFigure 2, which displays the argu-ments in a message box. Commandline arguments for a script can be speci-fied following the script filename in theTarget field of a shortcut, or when run-ning a script from a command promptusing CSCRIPT. Unfortunately scriptsare not treated by Windows as an ex-ecutable file type so you can’t pass file-names to them dynamically by

dragging files and dropping them on ascript icon or shortcut.

VBScript provides two types of ob-ject, defined by the built-in Scriptingobject, which you are likely to find use-ful in your scripts. Dictionary objectscan be used to hold indexed lists ofdata in a manner similar to a Perl asso-ciative array. Figure 3 gives a brief tasteof how they are used.

File AccessThe FileSystemObject object is one

of the most important objects availableto your scripts. It allows them to carryout file management activities like test-ing whether files or folders exist andcopying, deleting and moving files and

folders. FileSystemObject objects havemethods that themselves return objectsrepresenting drives, folders and files.These objects can be used to get informa-tion such as the attributes of a folder orthe size and modification date of a file.

FileSystemObjecthastoomanyprop-erties and methods to cover in detailhere, but an example of its use is shownin Figure 4. This script, or a derivationof it, could be launched from a user’sStartUp group, and will run silently inthe background when the PC starts. Itcompares the modification date of afile on a network server with the modi-fication date of the same file on thelocal hard disk. If the server copy isnewer it is copied to the local system.A script working along these linescould be used to update the signaturefiles for a workstation’s anti-virus soft-ware from copies kept on the server.

Walk-ThroughA brief explanation of the code in

Figure 4 may be beneficial. Note thatthe code for updating the file has beenwritten as a function. This makes it ageneric function that could be calledmultiple times with different argu-ments to update a number of differentfiles if you so wished. Execution of thescript begins by declaring and creatingthe FileSystemObject object which isneeded in order for many of the func-tions used by the Update function tobecome available. Variables s and t areinitialised to the source and target file-names. This isn’t necessary: the file-names could be specified as constantswhen the function “update” is called.

The function first checks to see if thesource file exists. If it cannot be foundfor any reason - even if the server isinaccessible - the FileExists functionsimply returns False and nothing moreis done. If the file is found then a fileobject f1 is created for it. This is used toobtain the file’s modification date. Be-cause this is returned as a text string ind1 it must be converted to an integervalue c1 for comparison. As we areonly interested in whether one file isnewer than another, and not by pre-cisely how many days, a simple con-version to the form yyyymmdd is used.

The modification date d2 for thesecond file is found in a similar way. If

Update 116 (June 1998) Page 19 File: T1205.3

Dim WSHNet, fs

Set WSHNet = WScript.CreateObject(“WScript.Network”)

set fs = WScript.CreateObject(“Scripting.FileSystemObject”)

Function MapDrive( letter, UNCname)

If fs.DriveExists( UNCname) Then

WSHNet.MapNetworkDrive letter, UNCname

End If

End Function

MapDrive “E:”, “\\DARWIN\DARWIN_C”

MapDrive “F:”, “\\DARWIN\DARWIN_D”

Figure 6 - MAPDRIVE.VBS - Map network drives.

Dim WSHShell, fs

Set WSHShell = WScript.CreateObject(“WScript.Shell”)

Set fs = WScript.CreateObject(“Scripting.FileSystemObject”)

Function MakeDesktopShortcut( name, target )

Dim Shortcut,DesktopPath,StartupPath

DesktopPath = WSHShell.SpecialFolders(“Desktop”)

Set Shortcut = WSHShell.CreateShortcut(DesktopPath & “\” &

name & “.lnk”)

Shortcut.TargetPath = target

StartupPath = fs.GetParentFolderName( target )

If fs.FolderExists( StartupPath ) then

Shortcut.WorkingDirectory = StartupPath

End If

Shortcut.Save

End Function

MakeDesktopShortcut “Shortcut to Notepad”, “C:\Windows\-

Notepad.exe”

Figure 5 - SHORTCUT.VBS - Create a shortcut on the desktop.

PC Support Advisor

Scripting Host

Tutorial:Operating Systems

Page 4: WSH Window Scripting

the file does not exist at all the value forcomparison c2 is set to 0. The two val-ues are then compared, and if c1 isgreater than c2 file f1 is copied to thetarget filename, overwriting the pre-vious version if it existed.

Two other methods of the FileSys-temObject object which we won’t gointo here, OpenTextFile and CreateText-File, create TextStream objects. Theseobjects have methods that allow you toread from and write to text files in aserial manner. It is not difficult to seehow you could enhance the function-ality of the code in Figure 4 by usingTextStream objects to read a file con-taining a list of the files to be updatedor write a log of updates carried out.

A by-product of this capability isthat it would be possible to writescripts that create or modify otherscripts. Whilst this is unlikely to begenerally very useful, it does seem tomake the possibility of script file vi-ruses at least technically possible.

Shell ObjectBesides the objects that are pro-

vided by VBScript and hence availableto scripts running under Internet Ex-plorer or IIS, two important objects areprovided by the WScript object of theWindows Scripting Host. The Shell ob-ject has a number of useful functions.It allows you to find out the location ofspecial folders such as the Windowsdesktop or Start Menu, to obtain thecontents of MS-DOS environmentstrings, to run programs, pop up mes-sage boxes (a function that is more orless duplicated by the VBScriptMsgBox function), create shortcutsand read from, write to or delete keysin the Windows Registry.

Figure 5 illustrates some of the fea-tures of the Shell object. It contains a

generic function MakeDesktop-Shortcut which, as the name suggests,creates a shortcut on the user’s desk-top. The function takes two arguments:name, which is the name of the short-cut, and target, which is the filenameor URL which is launched when theshortcut is double-clicked.

The function uses the SpecialFold-ers method of the Shell object to obtainthe location of the Windows desktopfor the current user. It then creates ashortcut object using the Shell methodCreateShortcut. The shortcut’s Target-Path property is set to the filename orURL. Two FileSystemObject methods,GetParentFolderName and FolderEx-ists, are used to set the working direc-tory to the folder containing the target.If this is an Internet URL the result ofGetParentFolder is invalid, so theWorkingDirectory property is only setif the folder actually exists. The Savemethod of the Shortcut object must beused to actually create the shortcut fileon the hard disk.

Network ObjectThe other object provided by

WScript is the Network object. This letsyou find out information like the username, computer name and organisa-tion name. It also lets you connect anddisconnect network drives, add andremove printer connections and set thedefault printer.

Figure 6 is a short script that mapsnetwork drives if they are accessible. Insome situations this may be preferableto the normal Windows mechanismwhich displays a warning message if itis unable to connect to a drive. How-ever, the real value of the example is toillustrate how it can be done so thatyou can create scripts that map drivesusing a degree of intelligence.

The function MapDrive uses theFileSystemObject method DriveExiststo test whether the network volume isaccessible using its UNC name. If thedrive is found, the MapNetworkDrivemethod of the WScript.Network objectis used to make the connection. With-out the test, the script would fail withan error message if the network vol-ume was not accessible when it tried tomap it.

OLEAs mentioned earlier, scripts can cre-

ate and use automation objects exposedby any Windows application that sup-ports OLE Automation. This includesall the major Office suites and manyother applications that claim to be Mi-crosoft Office compatible. Thoughmany of these applications may havescript languages of their own, it mayoften be more convenient to scriptthem using a standalone, application-independent script language. Figure 7shows a very trivial illustration of howto automate Microsoft Word by creat-ing a new document, inserting sometext in it, saving the document andclosing it. The purpose of the exampleis simply to show that it can be done,using exactly the same commands aswould be used in Visual Basic or VBA.

ConclusionThe Windows Scripting Host is the

tool that Windows has needed since itsinception. It fulfils admirably the func-tion of a batch language and automat-ion tool, whilst its ability to automateother applications extends its powertremendously. Support professionalswill undoubtedly find it to be a valu-able tool. But many advanced usersmay also enjoy the facility to writescripts that make their time at the key-board more productive.

Dim MSWord, WSHShell

Set WSHShell = WScript.CreateObject(“WScript.Shell”)

Set MSWord = WScript.CreateObject(“Word.Basic”)

MSWord.FileNew(“Normal”)

MSWord.Insert(“The quick brown fox jumps over” & Chr(13))

MSWord.Insert(“the lazy dog.”)

MSWord.FileSaveAs(WSHShell.SpecialFolders(12) & “\Test.doc”)

MSWord.FileClose

Figure 7 - WORD.VBS - Automating Microsoft Word

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

PCSA

The AuthorJulian Moss is a freelance technicalwriter and software developer. Hecan be contacted by email [email protected].

PC Support Advisor

Tutorial:Operating Systems