Mapping a Network Drive and Starting an ApplicationThe following WSH script, written in VBScript, shows how to use a WshNetwork object to map a network drive, doing so only when it is Administrator that is logged in. The script also uses the Run method of WshShell to start the Excel application on a particular spreadsheet file. This could be expanded to start Word or other applications on commonly used files, as a quick way to prepare for the day's work.
The WshNetwork object has properties UserName, UserDomain, and ComputerName. Here we check to see if UserName matches "Administrator". The MapNetworkDrive method is then used to set up a mapped network drive named K that corresponds to "\\cisdept\users\smithj". The parameters to this method are the drive letter, the remote name, an optional boolean flag that indicates whether to save this drive mapping in the user's profile (default false), and an optional user name and password. If the user name and password for the network drive are those of the logged in user, these two parameters can be omitted. This script also creates a WshShell object and uses its Run method to start Excel. Note the use of Chr(34) to get a double quote character. The & concatenation operator is used to build up the needed parameter for shell.Run. The space character in the pathname is the reason that an extra set of quotes is needed around this pathname. An equivalent method would be to use:
In a similar way, the following program starts up Word on two particular files,
c:\init.vbs and c:\hello.vbs.
This script does not map any network drives; it simply starts Word. Two double
quotes in a row are used to enclose the path to Word. This is needed because
the space in "program files" would otherwise cause us to attempt to run
"c:\program" on the parameters that follow. The Chr(34) method could be
used instead.
The following is a variation on the init.vbs script. This one just displays a message and quits if you are logged in as Administrator. Otherwise, the script opens Excel on a particular spreadsheet in a particular location. Obviously, if your pathname to Excel.exe is different or if you do not have a spreadsheet by the name given below at the indicated location, you will get an error message. This script does not do any mapping of a network drive. Rather, it assumes that the M drive is the correct one to use.
The following is a variation on the init2.vbs script. It shows you how your might open Word on two documents, when a space occurs in the path to the documents. This complication is handled by quoting.
Back to the Using WSH to Automate Tasks page |