Using Objects with VBScript
To use objects in VBScript, you first need to create an instance of an object and store its reference in a VBScript variable. Then, the methods and properties of the object can be accessed using variable.propertyname or variable.methodname. This is easier to demonstrate than explain, so here's an example (this is a short script that tells whether your C: drive has a folder named \windows):
set fso = CreateObject("Scripting.FileSystemObject") if fso.FolderExists("c:\windows") then WScript.echo "There is a folder named \Windows" end if
In the first line of the script, we create an instance of a Scripting.FileSystemObject. This is an object class provided with WSH that has handy properties and methods you can use when examining and manipulating disks and files.
Except for the word set, this looks just like a typical call to a function with the returned value being assigned to a variable. That's just what it is. CreateObject is a function that creates a new object instance. What's new is the word set, which VBScript requires you to use to indicate that an object reference is being stored rather than a regular value.
In general, the syntax to create an object instance in VBScript is
set variablename = CreateObject("objectname")
where variablename is the variable you want to use to hold the object reference, and objectname is the type of object you want to create.
In the second line of the example, we use the FolderExists method to find out whether a specified folder exists. Remember that methods and properties are just like regular functions and subroutines; they just happen to "live" in a separate program that provides the object class. The presence of fso. before FolderExists tells VBScript that the FolderExists function is part of the object class to which fso refers, which in this example is Scripting.FileSystemObject.
Some properties and methods take arguments, as you saw with FolderExists. When they do, you have to use parentheses in the same way you would with any other VBScript function or subroutine call. If the method or property returns a function value, you must use parentheses:
variable = object.property("arguments", "in", "parens")
If a method doesn't return a value, you can omit the parentheses:
object.method "arguments", "without", "parens"
Does this look familiar? We used objects all through the VBScript tutorial in Chapter 2, in statements such as this:
WScript.echo "Today's date is", date
Now, you should be able to recognize that WScript is an object variable and that echo is one of its methods. We never needed to use CreateObject to get WScript set up, though, because VBScript provides it automatically. The WScript object has several other handy methods and properties that we'll discuss later in this chapter.
As mentioned earlier, some properties and methods return another object as their value. For example, Scripting.FileSystemObject has a GetFile method that returns a File object. The File object can then be used to examine and manipulate the file. Here's a sample script that gives the size and creation date of the program file \windows\notepad.exe:
set fso = CreateObject("Scripting.FileSystemObject") set file = fso.GetFile("c:\windows\notepad.exe ") WScript.echo "Notepad.exe was created on", file.DateCreated WScript.echo "and is", file.Size, "bytes long"
The first line is the same as in the previous script, and it creates an instance of the helpful Scripting.FileSystemObject.
The second line asks the FileSystemObject to return a File object representing the file c:\windows\notepad.exe. Because I want to use this object several times, I saved it in the variable file, using the set keyword. (Although file is a reserved word in Visual Basic, it's not in VBScript, so it's available for use as a variable name.)
The next two lines use the File object's DateCreated and Size properties. Because these functions don't need arguments, there are no parentheses. The returned date/time and numeric values are printed by the WScript.echo method. On my computer, this prints the following:
Notepad.exe was created on 4/1/2001 7:27:08 AM and is 50960 bytes long
Automation and Document Files
The GetObject function may be used to obtain an object that represents some already existing document file, through a process called Automation. GetObject uses the name of the document file to find the appropriate object class server, through the Windows standard file type association mechanism (the list of file types and applications you see in Windows Explorer when you click Tools, Folder Options, File Types).
For example, you can create a Word document object representing an existing file and print it:
set obj = GetObject("C:\docs\userlist.doc") ' get object for existing document obj.Printout ' print the document set obj = Nothing ' release the object
GetObject can also obtain a reference to an already existing object that was created by some other program, through a name called a moniker. Several preexisting objects can be used to manage networking, Windows, and Active Directory user accounts. We'll cover these in Chapter 7, "Windows Management Instrumentation (WMI)," and Chapter 8, "Active Directory Scripting Interface (ADSI)."
The Difference Between Properties and Methods
I don't know about you, but for a long time I found the distinction between properties and methods to be confusing. Now, it's not crucially important to understand the difference, but if you're curious, I'll tell you how I finally came to an understanding of sorts.
If you look back in the preceding section, you'll see I mentioned the FolderExists method that is part of the object FileSystemObject. Why is FolderExists a method and not a property? It comes down to these main points:
Properties relate directly to aspects of the object, or rather, of the thing the object represents.
Properties act like variables: You just refer to them by their name.
Every property returns a value of some sort. Retrieving a property's value doesn't change anything about the object or whatever it represents.
Some properties let you assign new values to them. This changes the attribute of the object and the underlying thing it represents.
Methods are the things the object's program can do for you.
Methods act like functions and subroutines: They can have arguments passed to them.
Methods don't have to return a value, but some do.
Invoking a method can change something about the object or the real-world thing it represents.
Therefore, FolderExists is a method because it takes an argument (the name of the file it is to look up). Properties don't need arguments because they are intrinsic attributes of the object itself. As such, they don't need any additional information in order to return a value.
There is something else I should mention about properties: In many cases you can both evaluate them (examine their values) and assign new values to them. They work just like variables in this regard. The difference is that when you assign a new value to a property, the object software makes a corresponding change in the actual thing that the object represents. For example, assigning a new value to a File object's Name property changes the actual file's name, as shown here:
WScript.echo file.Name ' evaluate the property file.Name = "newname" ' assign a new value to the property
Keep in mind, however, that some objects don't let you change a property's value. In this case, the object's documentation will call it a read-only property.
One other thing I want to point out is that you don't necessarily need to save every object reference in a variable. In the previous example that displayed information about Notepad.exe, if I only wanted to see the creation date, I could have skipped the step of storing the File object in variable file and could have used these statements:
set fso = CreateObject("Scripting.FileSystemObject") WScript.echo "Notepad.exe was created on",_ fso.GetFile("c:\windows\notepad.exe ").DateCreated
In this case, VBScript refers to fso to call the GetFile method, and the returned object is used to call the DateCreated property. It's not unusual to see several levels of objects this way; this is called a nested object reference.
When you're working with Microsoft Word objects, this is very common. In scripts or Word macros, you may often see statements like these:
ActiveDocument.PageSetup.Orientation = wdOrientLandscape ActiveDocument.PageSetup.TopMargin = InchesToPoints(0.5) ActiveDocument.PageSetup.BottomMargin = InchesToPoints(0.5) ActiveDocument.PageSetup.PageWidth = InchesToPoints(11)
In this example, the ActiveDocument object returns a PageSetup object, which has orientation and margin properties you can set. You could save yourself some extra keystrokes in creating this script by saving a reference to the PageSetup object, as follows:
set ps = ActiveDocument.PageSetup ps.Orientation = wdOrientLandscape ps.TopMargin = InchesToPoints(0.5) ps.BottomMargin = InchesToPoints(0.5) ps.PageWidth = InchesToPoints(11)
However, VBScript has a special program construction called the With statement that makes this even easier. The previous example could be rewritten this way:
with ActiveDocument.PageSetup .Orientation = wdOrientLandscape .TopMargin = InchesToPoints(0.5) .BottomMargin = InchesToPoints(0.5) .PageWidth = InchesToPoints(11) end with
The With statement lets you specify an object reference that is taken as the "default" object between With and End With. Inside the With statement, you can refer to the default object's methods and properties by preceding them with a period but no variable name. Not only can this save you a lot of typing, but it's easier to read, and it lessens the workload on VBScript, thus speeding up your script.
If you need to, you can refer to other objects inside the With statement by using the fully spelled-out object.method.etc syntax.
When you create an object, Windows activates the object's class server program to manage the object for you. In the case of Scripting.FileSystemObject, you will usually create one of these objects at the beginning of your script and use it throughout. When your script completes, Windows releases the object you've created. The class server program takes care of freeing up its memory and other housekeeping chores. You really don't have to worry about it at all.
However, if you use a script to create multiple objects, you may find that it's appropriate to explicitly release them when you are through using them. For instance, a script that creates multiple Word documents should tell Word to close each document when you're finished with it, lest you end up with hundreds of documents open at once.
You can explicitly tell an object that you're finished with it by assigning the value Nothing to the variable that holds the object reference. Later in this book, you will see examples of this in some of the sample scripts.
Working with Collections
If you ask Scripting.FileSystemObject for the files or subfolders contained in a folder or drive, it may need to return multiple File or Folder objects. In order to manage this, it actually returns a single collection object that contains all the File or Folder objects inside it. You can then examine the contents of the collection to look at the individual items.
A collection object has a Count property that tells how many items are inside and an Item method that returns a specific item from the collection. This would lead you to expect that you could write a script like this to print the names of the files of the root folder on your hard drive:
set fso = CreateObject("Scripting.FileSystemObject") set files = fso.GetFolder("c:\").Files for i = 1 to files.Count WScript.echo files.Item(i).Name next
However, this script doesn't work. With a folder colection, Item doesn't allow you to retrieve items by number. It requires you to specify the name of the particular object you want, and if you don't yet know the names, this isn't much very useful.
So, to scan through collection objects, each scripting language provides a way to scan through collections without knowing what they contain. VBScript, for example, provides a special version of the For loop called For Each.
To scan through a collection object named collection in VBScript, use the For Each loop as follows:for each objectvar in collection ...statements using objectvar next
The For Each loop runs through the statements once for each object in the collection, and the variable objectvar will be made to refer to each of the individual objects in turn. Using For Each, and using a variable named file to hold the individual file objects, our folder-listing script will now work:
set fso = CreateObject("Scripting.FileSystemObject") set files = fso.GetFolder("c:\").Files for each file in files WScript.echo file.Name next
You could even use the following:
set fso = CreateObject("Scripting.FileSystemObject") for each file in fso.GetFolder("c:\").Files WScript.echo file.Name next
Now, if you don't plan on writing scripts in any other languages, skip ahead to the section titled "Using the WScript Object" of this chapter for more information about the built-in WScript object.