Objects, Part III. Ready to use some built-in Windows components to speed up routine tasks? Try these.

Component-Based Administration

Objects, Part III. Ready to use some built-in Windows components to speed up routine tasks? Try these.

Whenever you run a script using the Windows Script Host (WSH), the WScript object is created. It includes the Arguments object, which is used to pass command-line arguments to your scripts (see my article, “Supercharge Your Scripts,” in the October 1999 issue) and the Echo method (WScript.Echo), which is used to output text to the screen. It also includes several other objects, including WSHNetwork and WSHShell. These built-in objects can be used to perform a variety of administrative tasks. All of the WScript objects are housed in a file called wshom.ocx.

WSHNetwork

The Network object has three properties: ComputerName, UserDomain, and UserName (of currently logged-on user). All three are Read-Only, so you couldn’t use this component to, say… rename your computer. However, there are certainly going to be occasions when you’ll need to know this information. There are also seven methods for performing network drive and printer operations. Let’s look at two: MapNetworkDrive and RemoveNetworkDrive.

‘MapDrives.vbs
Dim objNetwork
Set objNetwork=CreateObject(“WScript.Network”)
objNetwork.MapNetworkDrive “P:”,
“\\MYSERVER\Public”, True,
“MYDOMAIN\MyOtherAccount”,
“MyPassword”

We now have drive P: mapped to the Public directory on MYSERVER. The first two parameters are required, the last three are optional. “True” tells the script to make the mapping persistent. The last two specify the username and password to use when connecting. In this case, we’re using a user account on MYDOMAIN, which means that I’m either logged directly into a workstation or a different domain, and that my regular account doesn’t have rights to \\MYSERVER\Public. We can remove the mapping just as easily:

‘RemoveDrives.vbs
Dim objNetwork
Set objNetwork=
CreateObject(“WScript.Network”)
objNetwork.RemoveNetworkDrive
“P:”, True, False

In this case, the only required parameter is the drive letter. The first optional parameter (True) tells the script to disconnect the drive even if it’s in use. The second optional parameter tells the script whether or not to make this persistent. Since it’s False, this drive mapping will be restored the next time the user logs on.

The Network object can also be used to add or remove a printer. The scripts to do this are almost identical to the MapDrives script except that printer names are used.

WSHShell

Shell is one of the more versatile objects you’re going to encounter. It gives us access to the Registry, Special Folders, and Event Logs, and even allows us to start applications from within a script. Let’s start by looking at Registry access.

Registry Methods

Let me preface this with the standard disclaimer that if you modify the Registry, you risk disabling applications, causing Windows boot errors, maybe destroying the universe! Use caution. WSHShell has three methods for Registry access: RegRead, RegWrite, and RegDelete. For RegRead and RegDelete the required parameters are the registry key\sub-key and (optionally) the value.

‘RegKill.vbs
Dim objShell
Set objShell=CreateObject(“WScript.Shell”)
objShell.RegDelete “HKEY_CLASSES_ROOT\
Applications\HYPERTRM.EXE\

We’ve just deleted the sub-key of HYPERTRM.EXE and every value it contained. If it happened to contain any sub-keys the operation would have failed. We could have specified the value to delete:

objShell.RegDelete “HKCR\applications\
HYPERTRM.EXE\NoOpenWith

This would only delete the specified value, NoOpenWith, leaving the key and its default value intact. And, yes, you can abbreviate the root keys as I did in the second example (HKCR instead of HKEY_ CLASSES_ROOT)… but I don’t recommend it. It opens the door to mistakes. I only did it to show you that it could be done.

You use RegRead in the same way, except that you must specify where to put it, into a string:

Dim objShell, strData
Set objShell=CreateObject(“WScript.Shell”)
StrData=objShell.RegRead
“HKEY_CLASSES_ROOT\Applications\
HYPERTRM.EXE\NoOpenWith

or echo it directly to the screen:

Dim objShell, strData
Set objShell=CreateObject(“WScript.Shell”)
WScript.Echo objShell.RegRead
HKEY_CLASSES_ROOT\Applications\
HYPERTRM.EXE\NoOpenWith

If you don’t specify a value, the Default value is read.

Finally, RegWrite creates a new key or value in the specified location. Again, if you don’t specify a value, one called Default is created. The second parameter specifies the data itself. An optional parameter specifies the type of value: REG_SZ or REG_EXPAND_SZ for strings, REG_DWORD for a 32-bit integer, and REG_BINARY for a 32-bit binary value.

Dim objShell
Set objShell=CreateObject(“WScript.Shell”)
objShell.RegWrite
“HKEY_CLASSES_ROOT\
Applications\HYPERTRM.EXE\
LastUsed”, “4/1/2000”, “REG_SZ”

Run

You can use this method just like the Start Menu “Run” option. You can include optional parameters, too. This is extremely useful. Even though WSH can do almost anything, it’s not necessary to always use its objects. For example, let’s say you’re running a script and need to save a directory listing to a file. You don’t need to do any verification to it and it doesn’t affect anything else in the script. This is a perfect use for Shell.Run.

Dim objShell
Set objShell=CreateObject(“WScript.Shell”)
objShell.Run(“cmd /c dir c:\myfiles >
c:\logs\MyLog.txt”)

We’ve just created a file in the \logs folder of c: called MyLog.txt. Sure, we could’ve used the Windows FileSystemObject to open the drive, list the directory, and save it to a file, but it would have taken several more lines of script. Since this was a non-critical function, it’s much easier to use Shell to execute the DOS “DIR” command.Another use for Shell.Run is to execute another script from within this script. Anything that can be executed at the command line can be executed using this method.

LogEvent

This is another invaluable administrative tool. You can use the Shell.LogEvent method to write an event into the application log (on NT 4.0 and Windows 2000). If you use this method on a Windows 9x machine, an event is added to WSH.log in the Windows\System directory. As your scripts get more complex and start to use error-handling, this becomes vital. You can use six different event codes:

• 0—Success Event
• 1—Error Event
• 2—Warning Event
• 4—Information Event
• 8—Audit Success
• 16—Audit Failure

If we put the following code at the end of a script, it will log an event that the “Script was successfully completed” along with the standard event information such as date and time:

Dim objShell
Set objShell=CreateObject(“WScript.Shell”)
objShell.LogEvent 0,
“Script was successfully completed.”

Special Folders

Windows has several “special” folders that are always used for the same thing, but may have different names. As such, they should never be accessed by name. The Shell.SpecialFolders object allows you to reference these items by their “special” name, regardless of where they are.

This script (see Listing 1) uses the FileSystemObject to create a Folder object that points to the “MyDocuments” folder of the current user. This works even if this folder has been moved or renamed. Dazzling!

Listing 1. This script uses the FileSystemObject to create a Folder object that points to the "My Documents" folder of the current user.

Dim objShell, objSFolders, objFSO,
objFolder
Set objShell=CreateObject(
"WScript.Shell")
Set objFSO=CreateObject(
"Scripting.FileSystemObject")
Set objSFolders=objShell.SpecialFolders
Set objFolder=objFSO.GetFolder(
objSFolders("MyDocuments"))
WScript.Echo "Folder " &
objSFolders("MyDocuments") &
" created on " &
objFolder.DateCreated

Next month we’ll discuss error-handling and include it in some scripts to perform redundant administrative tasks.

Featured

  • Microsoft Starts Countdown to Dynamics GP End-of-Support

    Dynamics GP, Microsoft's venerable enterprise resource planning (ERP) solution for midsized businesses, is set to lose support in four years.

  • Image of a futuristic maze

    The 2024 Microsoft Product Roadmap

    Everything Microsoft partners and IT pros need to know about major Microsoft product milestones this year.

  • Windows Recall Preview Starts Rolling Out with Windows 11 24H2

    Microsoft on Tuesday began rolling out Windows 11 version 24H2, describing the update as a "full OS swap that contains new foundational elements required to deliver transformational Al experiences and exceptional performance."

  • An image of planes flying around a globe

    2024 Microsoft Conference Calendar: For Partners, IT Pros and Developers

    Here's your guide to all the IT training sessions, partner meet-ups and annual Microsoft conferences you won't want to miss.