Home > Articles > Home & Office Computing > Microsoft Windows Desktop

  • Print
  • + Share This
This chapter is from the book

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.

Nested Objects

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.

NOTE

If you need to, you can refer to other objects inside the With statement by using the fully spelled-out object.method.etc syntax.

Releasing Objects

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.


Pattern

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.

  • + Share This
  • 🔖 Save To Your Account

InformIT Promotional Mailings & Special Offers

I would like to receive exclusive offers and hear about products from InformIT and its family of brands. I can unsubscribe at any time.

Overview


Pearson Education, Inc., 221 River Street, Hoboken, New Jersey 07030, (Pearson) presents this site to provide information about products and services that can be purchased through this site.

This privacy notice provides an overview of our commitment to privacy and describes how we collect, protect, use and share personal information collected through this site. Please note that other Pearson websites and online products and services have their own separate privacy policies.

Collection and Use of Information


To conduct business and deliver products and services, Pearson collects and uses personal information in several ways in connection with this site, including:

Questions and Inquiries

For inquiries and questions, we collect the inquiry or question, together with name, contact details (email address, phone number and mailing address) and any other additional information voluntarily submitted to us through a Contact Us form or an email. We use this information to address the inquiry and respond to the question.

Online Store

For orders and purchases placed through our online store on this site, we collect order details, name, institution name and address (if applicable), email address, phone number, shipping and billing addresses, credit/debit card information, shipping options and any instructions. We use this information to complete transactions, fulfill orders, communicate with individuals placing orders or visiting the online store, and for related purposes.

Surveys

Pearson may offer opportunities to provide feedback or participate in surveys, including surveys evaluating Pearson products, services or sites. Participation is voluntary. Pearson collects information requested in the survey questions and uses the information to evaluate, support, maintain and improve products, services or sites, develop new products and services, conduct educational research and for other purposes specified in the survey.

Contests and Drawings

Occasionally, we may sponsor a contest or drawing. Participation is optional. Pearson collects name, contact information and other information specified on the entry form for the contest or drawing to conduct the contest or drawing. Pearson may collect additional personal information from the winners of a contest or drawing in order to award the prize and for tax reporting purposes, as required by law.

Newsletters

If you have elected to receive email newsletters or promotional mailings and special offers but want to unsubscribe, simply email information@informit.com.

Service Announcements

On rare occasions it is necessary to send out a strictly service related announcement. For instance, if our service is temporarily suspended for maintenance we might send users an email. Generally, users may not opt-out of these communications, though they can deactivate their account information. However, these communications are not promotional in nature.

Customer Service

We communicate with users on a regular basis to provide requested services and in regard to issues relating to their account we reply via email or phone in accordance with the users' wishes when a user submits their information through our Contact Us form.

Other Collection and Use of Information


Application and System Logs

Pearson automatically collects log data to help ensure the delivery, availability and security of this site. Log data may include technical information about how a user or visitor connected to this site, such as browser type, type of computer/device, operating system, internet service provider and IP address. We use this information for support purposes and to monitor the health of the site, identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents and appropriately scale computing resources.

Web Analytics

Pearson may use third party web trend analytical services, including Google Analytics, to collect visitor information, such as IP addresses, browser types, referring pages, pages visited and time spent on a particular site. While these analytical services collect and report information on an anonymous basis, they may use cookies to gather web trend information. The information gathered may enable Pearson (but not the third party web trend services) to link information with application and system log data. Pearson uses this information for system administration and to identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents, appropriately scale computing resources and otherwise support and deliver this site and its services.

Cookies and Related Technologies

This site uses cookies and similar technologies to personalize content, measure traffic patterns, control security, track use and access of information on this site, and provide interest-based messages and advertising. Users can manage and block the use of cookies through their browser. Disabling or blocking certain cookies may limit the functionality of this site.

Do Not Track

This site currently does not respond to Do Not Track signals.

Security


Pearson uses appropriate physical, administrative and technical security measures to protect personal information from unauthorized access, use and disclosure.

Children


This site is not directed to children under the age of 13.

Marketing


Pearson may send or direct marketing communications to users, provided that

  • Pearson will not use personal information collected or processed as a K-12 school service provider for the purpose of directed or targeted advertising.
  • Such marketing is consistent with applicable law and Pearson's legal obligations.
  • Pearson will not knowingly direct or send marketing communications to an individual who has expressed a preference not to receive marketing.
  • Where required by applicable law, express or implied consent to marketing exists and has not been withdrawn.

Pearson may provide personal information to a third party service provider on a restricted basis to provide marketing solely on behalf of Pearson or an affiliate or customer for whom Pearson is a service provider. Marketing preferences may be changed at any time.

Correcting/Updating Personal Information


If a user's personally identifiable information changes (such as your postal address or email address), we provide a way to correct or update that user's personal data provided to us. This can be done on the Account page. If a user no longer desires our service and desires to delete his or her account, please contact us at customer-service@informit.com and we will process the deletion of a user's account.

Choice/Opt-out


Users can always make an informed choice as to whether they should proceed with certain services offered by InformIT. If you choose to remove yourself from our mailing list(s) simply visit the following page and uncheck any communication you no longer want to receive: www.informit.com/u.aspx.

Sale of Personal Information


Pearson does not rent or sell personal information in exchange for any payment of money.

While Pearson does not sell personal information, as defined in Nevada law, Nevada residents may email a request for no sale of their personal information to NevadaDesignatedRequest@pearson.com.

Supplemental Privacy Statement for California Residents


California residents should read our Supplemental privacy statement for California residents in conjunction with this Privacy Notice. The Supplemental privacy statement for California residents explains Pearson's commitment to comply with California law and applies to personal information of California residents collected in connection with this site and the Services.

Sharing and Disclosure


Pearson may disclose personal information, as follows:

  • As required by law.
  • With the consent of the individual (or their parent, if the individual is a minor)
  • In response to a subpoena, court order or legal process, to the extent permitted or required by law
  • To protect the security and safety of individuals, data, assets and systems, consistent with applicable law
  • In connection the sale, joint venture or other transfer of some or all of its company or assets, subject to the provisions of this Privacy Notice
  • To investigate or address actual or suspected fraud or other illegal activities
  • To exercise its legal rights, including enforcement of the Terms of Use for this site or another contract
  • To affiliated Pearson companies and other companies and organizations who perform work for Pearson and are obligated to protect the privacy of personal information consistent with this Privacy Notice
  • To a school, organization, company or government agency, where Pearson collects or processes the personal information in a school setting or on behalf of such organization, company or government agency.

Links


This web site contains links to other sites. Please be aware that we are not responsible for the privacy practices of such other sites. We encourage our users to be aware when they leave our site and to read the privacy statements of each and every web site that collects Personal Information. This privacy statement applies solely to information collected by this web site.

Requests and Contact


Please contact us about this Privacy Notice or if you have any requests or questions relating to the privacy of your personal information.

Changes to this Privacy Notice


We may revise this Privacy Notice through an updated posting. We will identify the effective date of the revision in the posting. Often, updates are made to provide greater clarity or to comply with changes in regulatory requirements. If the updates involve material changes to the collection, protection, use or disclosure of Personal Information, Pearson will provide notice of the change through a conspicuous notice on this site or other appropriate way. Continued use of the site after the effective date of a posted revision evidences acceptance. Please contact us if you have questions or concerns about the Privacy Notice or any objection to any revisions.

Last Update: November 17, 2020