Sie sind auf Seite 1von 275

VBScript Reference

Using the VBScript Reference


QuickTest's Expert View is a VBScript Editor. Therefore, in addition to entering test object statements and other testing-oriented functions, you can manually enter any valid Microsoft VBScript statement. You can
also use the Step Generator from the Expert View or from the Keyword View to insert many VBScript statements.
To assist you, the QuickTest Professional Help includes Microsoft's Visual Basic Scripting documentation. The included documentation is composed of three sections, each of which contain information that can be
relevant when working with QuickTest:
VBScript. Includes a user's guide and a thorough reference of objects, methods, properties, functions, and other elements that can be used when writing VBScript scripts.
Script Runtime. Describes the Dictionary object, FileSystemObject object, and the Script Encoder tool.
Windows Script Host. Includes overview information and a reference for working with the Microsoft Windows Script Host tool.
Note: Although some of the topics in these three sections may contain both VBScript and JScript information or examples, QuickTest supports only VBScript. Do not attempt to use JScript examples from the
VBScript reference in QuickTest.
Using the Microsoft Visual Basic Scripting Documentation

All Help topics under the VBScript Reference > VBScript, VBScript Reference > Script Runtime, and VBScript Reference > Windows Script Host sections are from Microsoft. These Help files were not
prepared by HP and HP is not responsible for their content. These help files were taken directly from Microsoft's Script56.chm help file, downloaded from http://msdn.microsoft.com/library/default.asp?
url=/downloads/list/webdev.asp.
In accordance with section 1d of the End-User License Agreement for Microsoft Software, provided with Microsoft Windows Script 5.6, only unmodified portions of the documentation from the Script56.CHM help
file relating to VBScript have been included herein under the VBScript Reference heading.
The information under the VBScript Reference heading may contain errors, problems, or other limitations. HP makes no representations whatsoever as to the accuracy, adequacy, reliability, currentness,
completeness, suitability or applicability of the information under the VBScript Reference heading. HP is not responsible for any damages, including the loss of time, which may result from using the information in
the help files under the VBScript Referenceheading.
The content under the VBScript Reference heading may contain links to Internet sites. Such links may not provide access to the intended site, or any site. Further, such links are not endorsements of any products or
services in such sites, and no information in such site has been endorsed by HP. SOME OF THESE HELP PAGES OR INTERNET SITES WILL MAKE REFERENCE TO JSCRIPT, HOWEVER THESE
REFERENCES ARE NOT APPLICABLE TO QUICKTEST PROFESSIONAL BECAUSE QUICKTEST PROFESSIONAL DOES NOT SUPPORT JSCRIPT .
Windows, Microsoft, JScript, and Visual Basic are registered trademarks of Microsoft Corporation in the United States and other countries. There is no relationship between Microsoft Corporation and HP.
The views expressed in the Help topics under the VBScript Reference heading are solely those of Microsoft Corporation.
The following notice applies to the Microsoft VBScript Help topics:
2001 Microsoft Corporation. All rights reserved.
Build: Topic Version 5.6.9309.1546

Visual Basic Scripting Edition

Copyright 2009 Mercury Interactive (Israel) Ltd.

VBScript
VBScipt User's Guide
VBScript Langauge Reference

2001 Microsoft Corporation. All rights reserved.


Build: Topic Version 5.6.9309.1546
Visual Basic Scripting Edition

VBScript User's Guide


What Is VBScript?
Adding VBScript Code to an HTML Page
VBScript Fundamentals
VBScript Data Types
VBScript Variables
VBScript Constants
VBScript Operators
Using Conditional Statements
Looping Through Code
VBScript Procedures
VBScript Coding Conventions

2001 Microsoft Corporation. All rights reserved.


Build: Topic Version 5.6.9309.1546
Visual Basic Scripting Edition

What Is VBScript?
Microsoft Visual Basic Scripting Edition brings active scripting to a wide variety of environments, including Web client scripting in Microsoft Internet Explorer and Web server scripting in Microsoft Internet Information
Service.

Easy to Use and Learn


If you already know Visual Basic or Visual Basic for Applications (VBA), VBScript will be very familiar. Even if you do not know Visual Basic, once you learn VBScript, you are on your way to programming with the whole
family of Visual Basic languages. Although you can learn about VBScript in just these few Web pages, they do not teach you how to program. To learn programming, take a look at Step by Step books available from Microsoft
Press.

Windows Script
VBScript talks to host applications using Windows Script. With Windows Script, browsers and other host applications do not require special integration code for each scripting component. Windows Script enables a host to
compile scripts, obtain and call entry points, and manage the namespace available to the developer. With Windows Script, language vendors can create standard language run times for scripting. Microsoft will provide run-time
support for VBScript. Microsoft is working with various Internet groups to define the Windows Script standard so that scripting engines can be interchangeable. Windows Script is used in Microsoft Internet Explorer and in
Microsoft Internet Information Service.

VBScript in Other Applications and Browsers


As a developer, you can license VBScript source implementation at no charge for use in your products. Microsoft provides binary implementations of VBScript for the 32-bit Windows API, the 16-bit Windows API, and the
Macintosh. VBScript is integrated with World Wide Web browsers. VBScript and Windows Script can also be used as a general scripting language in other applications.

2001 Microsoft Corporation. All rights reserved.


Build: Topic Version 5.6.9309.1546
Visual Basic Scripting Edition

Adding VBScript Code to an HTML Page


You can use the SCRIPT element to add VBScript code to an HTML page.

The <SCRIPT> Tag


VBScript code is written within paired <SCRIPT> tags. For example, a procedure to test a delivery date might appear as follows:
<SCRIPT LANGUAGE="VBScript">
<!-Function CanDeliver(Dt)
CanDeliver = (CDate(Dt) - Now()) > 2
End Function
-->
</SCRIPT>

Beginning and ending <SCRIPT> tags surround the code. The LANGUAGE attribute indicates the scripting language. You must specify the language because browsers can use other scripting languages. Notice that the
CanDeliver function is embedded in comment tags (<! and >). This prevents browsers that don't understand the <SCRIPT> tag from displaying the code.
Since the example is a general function it is not tied to any particular form control you can include it in the HEAD section of the page:
<HTML>
<HEAD>
<TITLE>Place Your Order</TITLE>
<SCRIPT LANGUAGE="VBScript">
<!-Function CanDeliver(Dt)
CanDeliver = (CDate(Dt) - Now()) > 2
End Function
-->
</SCRIPT>
</HEAD>
<BODY>
...

You can use SCRIPT blocks anywhere in an HTML page. You can put them in both the BODY and HEAD sections. However, you will probably want to put all general-purpose scripting code in the HEAD section in order to
keep all the code together. Keeping your code in the HEAD section ensures that all code is read and decoded before it is called from within the BODY section.
One notable exception to this rule is that you may want to provide inline scripting code within forms to respond to the events of objects in your form. For example, you can embed scripting code to respond to a button click in a
form:
<HTML>
<HEAD>
<TITLE>Test Button Events</TITLE>
</HEAD>
<BODY>
<FORM NAME="Form1">
<INPUT TYPE="Button" NAME="Button1" VALUE="Click">
<SCRIPT FOR="Button1" EVENT="onClick" LANGUAGE="VBScript">
MsgBox "Button Pressed!"
</SCRIPT>
</FORM>
</BODY>
</HTML>

Most of your code will appear in either Sub or Function procedures and will be called only when specified by your code. However, you can write VBScript code outside procedures, but still within a SCRIPT block. This code is
executed only once, when the HTML page loads. This allows you to initialize data or dynamically change the look of your Web page when it loads.

2001 Microsoft Corporation. All rights reserved.


Build: Topic Version 5.6.9309.1546
Visual Basic Scripting Edition

VBScript Features not in Visual Basic for Applications


The following table lists VBScript features not in Visual Basic for Applications.
Category
Declarations
Miscellaneous

Feature/Keyword
Class
Eval
Execute
Objects
RegExp
Script Engine Identification ScriptEngine
ScriptEngineBuildVersion
ScriptEngineMajorVersion
ScriptEngineMinorVersion

2001 Microsoft Corporation. All rights reserved.


Build: Topic Version 5.6.9309.1546
Visual Basic Scripting Edition

Visual Basic for Applications Features Not In VBScript


The following table lists Visual Basic for Applications Features not in VBScript.
Category
Array Handling

Omitted Feature/Keyword
Option Base
Declaring arrays with lower bound <> 0
Collection
Add, Count, Item, Remove
Access to collections using ! character
Conditional Compilation #Const
#If...Then...#Else
Control Flow
DoEvents
GoSub...Return, GoTo
On Error GoTo
On...GoSub, On...GoTo
Line numbers, Line labels
Conversion
CVar, CVDate
Str, Val
Data Types
All intrinsic data types except Variant
Type...End Type
Date/Time
Date statement, Time statement
DDE
LinkExecute, LinkPoke, LinkRequest, LinkSend
Debugging
Debug.Print
End, Stop
Declaration
Declare (for declaring DLLs)
Optional
ParamArray
Static
Error Handling
Erl
Error
Resume, Resume Next
File Input/Output
All traditional Basic file I/O
Financial
All financial functions
Object Manipulation
TypeOf
Objects
Clipboard
Collection
Operators
Like
Options
Deftype
Option Base
Option Compare
Option Private Module
Select Case
Expressions containing Is keyword or any comparison operators
Expressions containing a range of values using the To keyword.
Strings
Fixed-length strings
LSet, RSet
Mid Statement
StrConv
Using Objects
Collection access using !

2001 Microsoft Corporation. All rights reserved.


Build: Topic Version 5.6.9309.1546
Visual Basic Scripting Edition

VBScript Fundamentals
VBScript Data Types
VBScript Variables
VBScript Constants
VBScript Operators
Using Conditional Statements
Looping Through Code
VBScript Procedures
VBScript Coding Conventions

2001 Microsoft Corporation. All rights reserved.


Build: Topic Version 5.6.9309.1546
Visual Basic Scripting Edition

A Simple VBScript Page


A Simple Page
With Microsoft Internet Explorer, you can view the page produced by the following HTML code. If you click the button on the page, you see VBScript in action.
<HTML>
<HEAD><TITLE>A Simple First Page</TITLE>
<SCRIPT LANGUAGE="VBScript">
<!-Sub Button1_OnClick
MsgBox "Mirabile visu."
End Sub
-->
</SCRIPT>
</HEAD>

<BODY>
<H3>A Simple First Page</H3><HR>
<FORM><INPUT NAME="Button1" TYPE="BUTTON" VALUE="Click Here"></FORM>
</BODY>
</HTML>

The result is a little underwhelming: a dialog box displays a Latin phrase ("Wonderful to behold"). However, there's quite a bit going on.
When Internet Explorer reads the page, it finds the <SCRIPT> tags, recognizes there is a piece of VBScript code, and saves the code. When you click the button, Internet Explorer makes the connection between the button and
the code, and runs the procedure.
The Sub procedure in the <SCRIPT> tags is an event procedure. There are two parts to the procedure name: the name of the button, Button1 (from the NAME attribute in the <INPUT> tag), and an event name, OnClick. The
two names are joined by an underscore(_). Any time the button is clicked, Internet Explorer looks for and runs the corresponding event procedure, Button1_OnClick.
Internet Explorer defines the events available for form controls in the Internet Explorer Scripting Object Model documentation, which can be found on the Microsoft Web site (http://www.microsoft.com).
Pages can use combinations of controls and procedures, too. VBScript and Forms shows some simple interactions between controls.
Other Ways to Attach Code to Events
Although the preceding way is probably the simplest and most general, you can attach VBScript code to events in two other ways. Internet Explorer allows you to add short sections of inline code in the tag defining the control.
For example, the following <INPUT> tag performs the same action as the previous code example when you click the button:
<INPUT NAME="Button1" TYPE="BUTTON"
VALUE="Click Here" OnClick='MsgBox "Mirabile visu."'>

Notice that the function call itself is enclosed in single quotation marks, and the string for the MsgBox function is enclosed in double quotation marks. You can use multiple statements as long as you separate the statements with
colons (:).
You can also write a <SCRIPT> tag so that it applies only to a particular event for a specific control:
<SCRIPT LANGUAGE="VBScript" EVENT="OnClick" FOR="Button1">
<!-MsgBox "Mirabile visu."
-->
</SCRIPT>

Because the <SCRIPT> tag already specifies the event and the control, you don't use Sub and End Sub statements.

2001 Microsoft Corporation. All rights reserved.


Build: Topic Version 5.6.9309.1546
Visual Basic Scripting Edition

VBScript Features
The following table is a list of VBScript features.
Category
Array handling

Keywords
Array
Dim, Private, Public, ReDim
IsArray
Erase
LBound, UBound
Assignments
Set
Comments
Comments using ' or Rem
Constants/Literals Empty
Nothing
Null
True, False
Control flow
Do...Loop
For...Next
For Each...Next
If...Then...Else
Select Case
While...Wend
With
Conversions
Abs
Asc, AscB, AscW
Chr, ChrB, ChrW
CBool, CByte
CCur, CDate
CDbl, CInt
CLng, CSng, CStr
DateSerial, DateValue
Hex, Oct
Fix, Int
Sgn
TimeSerial, TimeValue
Dates/Times
Date, Time
DateAdd, DateDiff, DatePart
DateSerial, DateValue
Day, Month, MonthName
Weekday, WeekdayName, Year
Hour, Minute, Second
Now
TimeSerial, TimeValue
Declarations
Class
Const
Dim, Private, Public, ReDim
Function, Sub
Property Get, Property Let, Property Set
Error Handling
On Error
Err
Expressions
Eval
Execute
RegExp
Replace
Test
Formatting Strings FormatCurrency
FormatDateTime
FormatNumber
FormatPercent
Input/Output
InputBox
LoadPicture

Literals

Math

Miscellaneous

Objects

Operators

Options
Procedures

Rounding

Script Engine ID

Strings

Variants

MsgBox
Empty
False
Nothing
Null
True
Atn, Cos, Sin, Tan
Exp, Log, Sqr
Randomize, Rnd
Eval Function
Execute Statement
RGB Function
CreateObject
Err Object
GetObject
RegExp
Addition (+), Subtraction (-)
Exponentiation (^)
Modulus arithmetic (Mod)
Multiplication (*), Division (/)
Integer Division (\)
Negation (-)
String concatenation (&)
Equality (=), Inequality (<>)
Less Than (<), Less Than or Equal To (<=)
Greater Than (>)
Greater Than or Equal To (>=)
Is
And, Or, Xor
Eqv, Imp
Option Explicit
Call
Function, Sub
Property Get, Property Let, Property Set
Abs
Int, Fix, Round
Sgn
ScriptEngine
ScriptEngineBuildVersion
ScriptEngineMajorVersion
ScriptEngineMinorVersion
Asc, AscB, AscW
Chr, ChrB, ChrW
Filter, InStr, InStrB
InStrRev
Join
Len, LenB
LCase, UCase
Left, LeftB
Mid, MidB
Right, RightB
Replace
Space
Split
StrComp
String
StrReverse
LTrim, RTrim, Trim
IsArray
IsDate
IsEmpty
IsNull
IsNumeric
IsObject
TypeName
VarType

2001 Microsoft Corporation. All rights reserved.


Build: Topic Version 5.6.9309.1546
Visual Basic Scripting Edition

VBScript Data Types


VBScript has only one data type called a Variant. A Variant is a special kind of data type that can contain different kinds of information, depending on how it is used. Because Variant is the only data type in VBScript, it is
also the data type returned by all functions in VBScript.
At its simplest, a Variant can contain either numeric or string information. A Variant behaves as a number when you use it in a numeric context and as a string when you use it in a string context. That is, if you are working
with data that looks like numbers, VBScript assumes that it is numbers and does what is most appropriate for numbers. Similarly, if you're working with data that can only be string data, VBScript treats it as string data. You can
always make numbers behave as strings by enclosing them in quotation marks (" ").

Variant Subtypes
Beyond the simple numeric or string classifications, a Variant can make further distinctions about the specific nature of numeric information. For example, you can have numeric information that represents a date or a time.
When used with other date or time data, the result is always expressed as a date or a time. You can also have a rich variety of numeric information ranging in size from Boolean values to huge floating-point numbers. These
different categories of information that can be contained in a Variant are called subtypes. Most of the time, you can just put the kind of data you want in a Variant, and the Variant behaves in a way that is most appropriate for
the data it contains.
The following table shows subtypes of data that a Variant can contain.
Subtype
Empty
Null
Boolean
Byte
Integer
Currency
Long
Single
Double
Date (Time)
String

Description
Variant is uninitialized. Value is 0 for numeric variables or a zero-length string ("") for string variables.
Variant intentionally contains no valid data.
Contains either True or False.
Contains integer in the range 0 to 255.
Contains integer in the range -32,768 to 32,767.
-922,337,203,685,477.5808 to 922,337,203,685,477.5807.
Contains integer in the range -2,147,483,648 to 2,147,483,647.
Contains a single-precision, floating-point number in the range -3.402823E38 to -1.401298E-45 for negative values; 1.401298E-45 to 3.402823E38 for positive values.
Contains a double-precision, floating-point number in the range -1.79769313486232E308 to -4.94065645841247E-324 for negative values; 4.94065645841247E-324 to
1.79769313486232E308 for positive values.
Contains a number that represents a date between January 1, 100 to December 31, 9999.
Contains a variable-length string that can be up to approximately 2 billion characters in length.

Object
Error

Contains an object.
Contains an error number.

You can use conversion functions to convert data from one subtype to another. In addition, the VarType function returns information about how your data is stored within a Variant.

2001 Microsoft Corporation. All rights reserved.


Build: Topic Version 5.6.9309.1546
Visual Basic Scripting Edition

VBScript Variables
A variable is a convenient placeholder that refers to a computer memory location where you can store program information that may change during the time your script is running. For example, you might create a variable called
ClickCount to store the number of times a user clicks an object on a particular Web page. Where the variable is stored in computer memory is unimportant. What is important is that you only have to refer to a variable by name
to see or change its value. In VBScript, variables are always of one fundamental data type, Variant.

Declaring Variables
You declare variables explicitly in your script using the Dim statement, the Public statement, and the Private statement. For example:
Dim DegreesFahrenheit

You declare multiple variables by separating each variable name with a comma. For example:
Dim Top, Bottom, Left, Right

You can also declare a variable implicitly by simply using its name in your script. That is not generally a good practice because you could misspell the variable name in one or more places, causing unexpected results when your
script is run. For that reason, the Option Explicit statement is available to require explicit declaration of all variables. The Option Explicit statement should be the first statement in your script.

Naming Restrictions
Variable names follow the standard rules for naming anything in VBScript. A variable name:

Must begin with an alphabetic character.


Cannot contain an embedded period.
Must not exceed 255 characters.
Must be unique in the scope in which it is declared.

Scope and Lifetime of Variables


A variable's scope is determined by where you declare it. When you declare a variable within a procedure, only code within that procedure can access or change the value of that variable. It has local scope and is a procedurelevel variable. If you declare a variable outside a procedure, you make it recognizable to all the procedures in your script. This is a script-level variable, and it has script-level scope.
The lifetime of a variable depends on how long it exists. The lifetime of a script-level variable extends from the time it is declared until the time the script is finished running. At procedure level, a variable exists only as long as
you are in the procedure. When the procedure exits, the variable is destroyed. Local variables are ideal as temporary storage space when a procedure is executing. You can have local variables of the same name in several
different procedures because each is recognized only by the procedure in which it is declared.

Assigning Values to Variables


Values are assigned to variables creating an expression as follows: the variable is on the left side of the expression and the value you want to assign to the variable is on the right. For example:
B = 200

Scalar Variables and Array Variables


Much of the time, you only want to assign a single value to a variable you have declared. A variable containing a single value is a scalar variable. Other times, it is convenient to assign more than one related value to a single
variable. Then you can create a variable that can contain a series of values. This is called an array variable. Array variables and scalar variables are declared in the same way, except that the declaration of an array variable uses
parentheses ( ) following the variable name. In the following example, a single-dimension array containing 11 elements is declared:
Dim A(10)

Although the number shown in the parentheses is 10, all arrays in VBScript are zero-based, so this array actually contains 11 elements. In a zero-based array, the number of array elements is always the number shown in
parentheses plus one. This kind of array is called a fixed-size array.
You assign data to each of the elements of the array using an index into the array. Beginning at zero and ending at 10, data can be assigned to the elements of an array as follows:
A(0) = 256
A(1) = 324
A(2) = 100
. . .
A(10) = 55

Similarly, the data can be retrieved from any element using an index into the particular array element you want. For example:
. . .
SomeVariable = A(8)
. . .

Arrays aren't limited to a single dimension. You can have as many as 60 dimensions, although most people can't comprehend more than three or four dimensions. You can declare multiple dimensions by separating an array's
size numbers in the parentheses with commas. In the following example, the MyTable variable is a two-dimensional array consisting of 6 rows and 11 columns:
Dim MyTable(5, 10)

In a two-dimensional array, the first number is always the number of rows; the second number is the number of columns.
You can also declare an array whose size changes during the time your script is running. This is called a dynamic array. The array is initially declared within a procedure using either the Dim statement or using the ReDim
statement. However, for a dynamic array, no size or number of dimensions is placed inside the parentheses. For example:
Dim MyArray()
ReDim AnotherArray()

To use a dynamic array, you must subsequently use ReDim to determine the number of dimensions and the size of each dimension. In the following example, ReDim sets the initial size of the dynamic array to 25. A subsequent
ReDim statement resizes the array to 30, but uses the Preserve keyword to preserve the contents of the array as the resizing takes place.
ReDim MyArray(25)
. . .
ReDim Preserve MyArray(30)

There is no limit to the number of times you can resize a dynamic array, although if you make an array smaller, you lose the data in the eliminated elements.

2001 Microsoft Corporation. All rights reserved.


Build: Topic Version 5.6.9309.1546
Visual Basic Scripting Edition

VBScript Constants
A constant is a meaningful name that takes the place of a number or string and never changes. VBScript defines a number of intrinsic constants . You can get information about these intrinsic constants from the VBScript
Language Reference.

Creating Constants
You create user-defined constants in VBScript using the Const statement. Using the Const statement, you can create string or numeric constants with meaningful names and assign them literal values. For example:
Const MyString = "This is my string."
Const MyAge = 49

Note that the string literal is enclosed in quotation marks (" "). Quotation marks are the most obvious way to differentiate string values from numeric values. You represent Date literals and time literals by enclosing them in
number signs (#). For example:
Const CutoffDate = #6-1-97#

You may want to adopt a naming scheme to differentiate constants from variables. This will prevent you from trying to reassign constant values while your script is running. For example, you might want to use a "vb" or "con"
prefix on your constant names, or you might name your constants in all capital letters. Differentiating constants from variables eliminates confusion as you develop more complex scripts.

2001 Microsoft Corporation. All rights reserved.


Build: Topic Version 5.6.9309.1546
Visual Basic Scripting Edition

VBScript Operators
VBScript has a full range of operators, including arithmetic operators, comparison operators, concatenation operators, and logical operators.

Operator Precedence
When several operations occur in an expression, each part is evaluated and resolved in a predetermined order called operator precedence. You can use parentheses to override the order of precedence and force some parts of an
expression to be evaluated before others. Operations within parentheses are always performed before those outside. Within parentheses, however, standard operator precedence is maintained.
When expressions contain operators from more than one category, arithmetic operators are evaluated first, comparison operators are evaluated next, and logical operators are evaluated last. Comparison operators all have equal
precedence; that is, they are evaluated in the left-to-right order in which they appear. Arithmetic and logical operators are evaluated in the following order of precedence.
Arithmetic
Description
Symbol
Exponentiation
^
Unary negation
Multiplication
*
Division
/
Integer division
\
Modulus arithmetic Mod
Addition
+
Subtraction
String concatenation &
Comparison
Description
Equality
=
Inequality
<>
Less than
<
Greater than
>
Less than or equal to <=
Greater than or equal to >=
Object equivalence
Is

Symbol

Logical
Description
Symbol
Logical negation Not
Logical conjunction And
Logical disjunction Or
Logical exclusion Xor
Logical equivalence Eqv
Logical implication Imp
When multiplication and division occur together in an expression, each operation is evaluated as it occurs from left to right. Likewise, when addition and subtraction occur together in an expression, each operation is evaluated in
order of appearance from left to right.
The string concatenation (&) operator is not an arithmetic operator, but in precedence it falls after all arithmetic operators and before all comparison operators. The Is operator is an object reference comparison operator. It does
not compare objects or their values; it checks only to determine if two object references refer to the same object.

2001 Microsoft Corporation. All rights reserved.


Build: Topic Version 5.6.9309.1546
Visual Basic Scripting Edition

Using Conditional Statements


Controlling Program Execution
You can control the flow of your script with conditional statements and looping statements. Using conditional statements, you can write VBScript code that makes decisions and repeats actions. The following conditional

statements are available in VBScript:

If...Then...Else statement
Select Case statement

Making Decisions Using If...Then...Else


The If...Then...Else statement is used to evaluate whether a condition is True or False and, depending on the result, to specify one or more statements to run. Usually the condition is an expression that uses a comparison
operator to compare one value or variable with another. For information about comparison operators, see Comparison Operators. If...Then...Else statements can be nested to as many levels as you need.
Running Statements if a Condition is True
To run only one statement when a condition is True, use the single-line syntax for the If...Then...Else statement. The following example shows the single-line syntax. Notice that this example omits the Else keyword.
Sub FixDate()
Dim myDate
myDate = #2/13/95#
If myDate < Now Then myDate = Now
End Sub

To run more than one line of code, you must use the multiple-line (or block) syntax. This syntax includes the End If statement, as shown in the following example:
Sub AlertUser(value)
If value = 0 Then
AlertLabel.ForeColor = vbRed
AlertLabel.Font.Bold = True
AlertLabel.Font.Italic = True
End If
End Sub

Running Certain Statements if a Condition is True and Running Others if a Condition is False
You can use an If...Then...Else statement to define two blocks of executable statements: one block to run if the condition is True, the other block to run if the condition is False.
Sub AlertUser(value)
If value = 0 Then
AlertLabel.ForeColor =
AlertLabel.Font.Bold =
AlertLabel.Font.Italic
Else
AlertLabel.Forecolor =
AlertLabel.Font.Bold =
AlertLabel.Font.Italic
End If
End Sub

vbRed
True
= True
vbBlack
False
= False

Deciding Between Several Alternatives


A variation on the If...Then...Else statement allows you to choose from several alternatives. Adding ElseIf clauses expands the functionality of the If...Then...Else statement so you can control program flow based on different
possibilities. For example:
Sub ReportValue(value)
If value = 0 Then
MsgBox value
ElseIf value = 1 Then
MsgBox value
ElseIf value = 2 then
Msgbox value
Else
Msgbox "Value out of range!"
End If

You can add as many ElseIf clauses as you need to provide alternative choices. Extensive use of the ElseIf clauses often becomes cumbersome. A better way to choose between several alternatives is the Select Case statement.

Making Decisions with Select Case


The Select Case structure provides an alternative to If...Then...ElseIf for selectively executing one block of statements from among multiple blocks of statements. A Select Case statement provides capability similar to the
If...Then...Else statement, but it makes code more efficient and readable.
A Select Case structure works with a single test expression that is evaluated once, at the top of the structure. The result of the expression is then compared with the values for each Case in the structure. If there is a match, the
block of statements associated with that Case is executed, as in the following example.
Select Case Document.Form1.CardType.Options(SelectedIndex).Text
Case "MasterCard"
DisplayMCLogo
ValidateMCAccount
Case "Visa"
DisplayVisaLogo
ValidateVisaAccount
Case "American Express"
DisplayAMEXCOLogo
ValidateAMEXCOAccount
Case Else
DisplayUnknownImage
PromptAgain
End Select

Notice that the Select Case structure evaluates an expression once at the top of the structure. In contrast, the If...Then...ElseIf structure can evaluate a different expression for each ElseIf statement. You can replace an
If...Then...ElseIf structure with a Select Case structure only if each ElseIf statement evaluates the same expression.

2001 Microsoft Corporation. All rights reserved.


Build: Topic Version 5.6.9309.1546
Visual Basic Scripting Edition

Looping Through Code


Looping allows you to run a group of statements repeatedly. Some loops repeat statements until a condition is False; others repeat statements until a condition is True. There are also loops that repeat statements a specific
number of times.
The following looping statements are available in VBScript:

Do...Loop: Loops while or until a condition is True.


While...Wend: Loops while a condition is True.
For...Next: Uses a counter to run statements a specified number of times.
For Each...Next: Repeats a group of statements for each item in a collection or each element of an array.

Using Do Loops
You can use Do...Loop statements to run a block of statements an indefinite number of times. The statements are repeated either while a condition is True or until a condition becomes True.

Repeating Statements While a Condition is True


Use the While keyword to check a condition in a Do...Loop statement. You can check the condition before you enter the loop (as shown in the following ChkFirstWhile example), or you can check it after the loop has run at
least once (as shown in the ChkLastWhile example). In the ChkFirstWhile procedure, if myNum is set to 9 instead of 20, the statements inside the loop will never run. In the ChkLastWhile procedure, the statements inside the loop
run only once because the condition is already False.
Sub ChkFirstWhile()
Dim counter, myNum
counter = 0
myNum = 20
Do While myNum > 10
myNum = myNum - 1
counter = counter + 1
Loop
MsgBox "The loop made " & counter & " repetitions."
End Sub
Sub ChkLastWhile()
Dim counter, myNum
counter = 0
myNum = 9
Do
myNum = myNum - 1
counter = counter + 1
Loop While myNum > 10
MsgBox "The loop made " & counter & " repetitions."
End Sub

Repeating a Statement Until a Condition Becomes True


There are two ways to use the Until keyword to check a condition in a Do...Loop statement. You can check the condition before you enter the loop (as shown in the following ChkFirstUntil example), or you can check it after the
loop has run at least once (as shown in the ChkLastUntil example). As long as the condition is False, the looping occurs.
Sub ChkFirstUntil()
Dim counter, myNum
counter = 0
myNum = 20
Do Until myNum = 10
myNum = myNum - 1
counter = counter + 1
Loop
MsgBox "The loop made " & counter & " repetitions."
End Sub
Sub ChkLastUntil()
Dim counter, myNum
counter = 0
myNum = 1
Do
myNum = myNum + 1
counter = counter + 1
Loop Until myNum = 10
MsgBox "The loop made " & counter & " repetitions."
End Sub

Exiting a Do...Loop Statement from Inside the Loop


You can exit a Do...Loop by using the Exit Do statement. Because you usually want to exit only in certain situations, such as to avoid an endless loop, you should use the Exit Do statement in the True statement block of an
If...Then...Else statement. If the condition is False, the loop runs as usual.
In the following example, myNum is assigned a value that creates an endless loop. The If...Then...Else statement checks for this condition, preventing the endless repetition.
Sub ExitExample()
Dim counter, myNum
counter = 0
myNum = 9
Do Until myNum = 10
myNum = myNum - 1
counter = counter + 1
If myNum < 10 Then Exit Do
Loop
MsgBox "The loop made " & counter & " repetitions."
End Sub

Using While...Wend
The While...Wend statement is provided in VBScript for those who are familiar with its usage. However, because of the lack of flexibility in While...Wend, it is recommended that you use Do...Loop instead.

Using For...Next
You can use For...Next statements to run a block of statements a specific number of times. For loops, use a counter variable whose value increases or decreases with each repetition of the loop.
The following example causes a procedure called MyProc to execute 50 times. The For statement specifies the counter variable x and its start and end values. The Next statement increments the counter variable by 1.
Sub DoMyProc50Times()
Dim x
For x = 1 To 50
MyProc
Next
End Sub

Using the Step keyword, you can increase or decrease the counter variable by the value you specify. In the following example, the counter variable j is incremented by 2 each time the loop repeats. When the loop is finished, the
total is the sum of 2, 4, 6, 8, and 10.
Sub TwosTotal()
Dim j, total
For j = 2 To 10 Step 2
total = total + j
Next
MsgBox "The total is " & total
End Sub

To decrease the counter variable, use a negative Step value. You must specify an end value that is less than the start value. In the following example, the counter variable myNum is decreased by 2 each time the loop repeats. When
the loop is finished, total is the sum of 16, 14, 12, 10, 8, 6, 4, and 2.
Sub NewTotal()
Dim myNum, total
For myNum = 16 To 2 Step -2
total = total + myNum
Next
MsgBox "The total is " & total
End Sub

You can exit any For...Next statement before the counter reaches its end value by using the Exit For statement. Because you usually want to exit only in certain situations, such as when an error occurs, you should use the Exit
For statement in the True statement block of an If...Then...Else statement. If the condition is False, the loop runs as usual.

Using For Each...Next


A For Each...Next loop is similar to a For...Next loop. Instead of repeating the statements a specified number of times, a For Each...Next loop repeats a group of statements for each item in a collection of objects or for each

element of an array. This is especially helpful if you don't know how many elements are in a collection.
In the following HTML code example, the contents of a Dictionary object is used to place text in several text boxes.
<HTML>
<HEAD><TITLE>Forms and Elements</TITLE></HEAD>
<SCRIPT LANGUAGE="VBScript">
<!-Sub cmdChange_OnClick
Dim d
'Create a variable
Set d = CreateObject("Scripting.Dictionary")
d.Add "0", "Athens"
'Add some keys and items
d.Add "1", "Belgrade"
d.Add "2", "Cairo"
For Each I in d
Document.frmForm.Elements(I).Value = D.Item(I)
Next
End Sub
-->
</SCRIPT>
<BODY>
<CENTER>
<FORM NAME="frmForm"
<Input Type
<Input Type
<Input Type
<Input Type
<Input Type
</FORM>
</CENTER>
</BODY>
</HTML>

=
=
=
=
=

"Text"><p>
"Text"><p>
"Text"><p>
"Text"><p>
"Button" NAME="cmdChange" VALUE="Click Here"><p>

2001 Microsoft Corporation. All rights reserved.


Build: Topic Version 5.6.9309.1546
Visual Basic Scripting Edition

VBScript Procedures
In VBScript, there are two kinds of procedures; the Sub procedure and the Function procedure.

Sub Procedures
A Sub procedure is a series of VBScript statements (enclosed by Sub and End Sub statements) that perform actions but don't return a value. A Sub procedure can take arguments (constants, variables, or expressions that are
passed by a calling procedure). If a Sub procedure has no arguments, its Sub statement must include an empty set of parentheses ().
The following Sub procedure uses two intrinsic, or built-in, VBScript functions, MsgBox and InputBox, to prompt a user for information. It then displays the results of a calculation based on that information. The calculation is
performed in a Function procedure created using VBScript. The Function procedure is shown after the following discussion.
Sub ConvertTemp()
temp = InputBox("Please enter the temperature in degrees F.", 1)
MsgBox "The temperature is " & Celsius(temp) & " degrees C."
End Sub

Function Procedures
A Function procedure is a series of VBScript statements enclosed by the Function and End Function statements. A Function procedure is similar to a Sub procedure, but can also return a value. A Function procedure can take
arguments (constants, variables, or expressions that are passed to it by a calling procedure). If a Function procedure has no arguments, its Function statement must include an empty set of parentheses. A Function returns a
value by assigning a value to its name in one or more statements of the procedure. The return type of a Function is always a Variant.
In the following example, the Celsius function calculates degrees Celsius from degrees Fahrenheit. When the function is called from the ConvertTemp Sub procedure, a variable containing the argument value is passed to the
function. The result of the calculation is returned to the calling procedure and displayed in a message box.
Sub ConvertTemp()
temp = InputBox("Please enter the temperature in degrees F.", 1)
MsgBox "The temperature is " & Celsius(temp) & " degrees C."
End Sub
Function Celsius(fDegrees)
Celsius = (fDegrees - 32) * 5 / 9
End Function

Getting Data into and out of Procedures


Each piece of data is passed into your procedures using an argument . Arguments serve as placeholders for the data you want to pass into your procedure. You can name your arguments any valid variable name. When you create
a procedure using either the Sub statement or the Function statement, parentheses must be included after the name of the procedure. Any arguments are placed inside these parentheses, separated by commas. For example, in the
following example, fDegrees is a placeholder for the value being passed into the Celsius function for conversion.
Function Celsius(fDegrees)
Celsius = (fDegrees - 32) * 5 / 9
End Function

To get data out of a procedure, you must use a Function. Remember, a Function procedure can return a value; a Sub procedure can't.

Using Sub and Function Procedures in Code


A Function in your code must always be used on the right side of a variable assignment or in an expression. For example:
Temp = Celsius(fDegrees)

-orMsgBox "The Celsius temperature is " & Celsius(fDegrees) & " degrees."

To call a Sub procedure from another procedure, type the name of the procedure along with values for any required arguments, each separated by a comma. The Call statement is not required, but if you do use it, you must
enclose any arguments in parentheses.
The following example shows two calls to the MyProc procedure. One uses the Call statement in the code; the other doesn't. Both do exactly the same thing.
Call MyProc(firstarg, secondarg)
MyProc firstarg, secondarg

Notice that the parentheses are omitted in the call when the Call statement isn't used.

2001 Microsoft Corporation. All rights reserved.


Build: Topic Version 5.6.9309.1546
Visual Basic Scripting Edition

VBScript Coding Conventions


Coding conventions are suggestions are designed to help you write code using Microsoft Visual Basic Scripting Edition. Coding conventions can include the following:

Naming conventions for objects, variables, and procedures


Commenting conventions
Text formatting and indenting guidelines

The main reason for using a consistent set of coding conventions is to standardize the structure and coding style of a script or set of scripts so that you and others can easily read and understand the code. Using good coding
conventions results in clear, precise, and readable source code that is consistent with other language conventions and is intuitive.

Constant Naming Conventions


Earlier versions of VBScript had no mechanism for creating user-defined constants. Constants, if used, were implemented as variables and distinguished from other variables using all uppercase characters. Multiple words were
separated using the underscore (_) character. For example:
USER_LIST_MAX
NEW_LINE

While this is still an acceptable way to identify your constants, you may want to use an alternative naming scheme, now that you can create true constants using the Const statement. This convention uses a mixed-case format in
which constant names have a "con" prefix. For example:
conYourOwnConstant

Variable Naming Conventions


To enhance readability and consistency, use the following prefixes with descriptive names for variables in your VBScript code.
Subtype
Boolean
Byte
Date (Time)
Double
Error
Integer
Long
Object
Single
String

Prefix
bln
byt
dtm
dbl
err
int
lng
obj
sng
str

Example
blnFound
bytRasterData
dtmStart
dblTolerance
errOrderNum
intQuantity
lngDistance
objCurrent
sngAverage
strFirstName

Variable Scope
Variables should always be defined with the smallest scope possible. VBScript variables can have the following scope.
Scope
Procedure-level
Script-level

Where Variable Is Declared


Visibility
Event, Function, or Sub procedure.
Visible in the procedure in which it is declared.
HEAD section of an HTML page, outside any procedure. Visible in every procedure in the script.

Variable Scope Prefixes


As script size grows, so does the value of being able to quickly differentiate the scope of variables. A one-letter scope prefix preceding the type prefix provides this, without unduly increasing the size of variable names.
Scope
Procedure-level
Script-level

Prefix
None
s

Example
dblVelocity
sblnCalcInProgress

Descriptive Variable and Procedure Names


The body of a variable or procedure name should use mixed case and should be as descriptive as necessary. In addition, procedure names should begin with a verb, such as InitNameArray or CloseDialog.
For frequently used or long terms, standard abbreviations are recommended to help keep name length reasonable. In general, variable names greater than 32 characters can be difficult to read. When using abbreviations, make
sure they are consistent throughout the entire script. For example, randomly switching between Cnt and Count within a script or set of scripts may lead to confusion.

Object Naming Conventions


The following table lists recommended conventions for objects you may encounter while programming VBScript.
Object type
3D Panel
pnl
Animated button
ani
Check box
chk
Combo box, drop-down list box cbo
Command button
cmd
Common dialog
dlg
Frame
fra
Horizontal scroll bar
hsb
Image
img
Label
lbl
Line
lin
List Box
lst
Spin
spn
Text box
txt
Vertical scroll bar
vsb
Slider
sld

Prefix

Example
pnlGroup
aniMailBox
chkReadOnly
cboEnglish
cmdExit
dlgFileOpen
fraLanguage
hsbVolume
imgIcon
lblHelpMessage
linVertical
lstPolicyCodes
spnPages
txtLastName
vsbRate
sldScale

Code Commenting Conventions


All procedures should begin with a brief comment describing what they do. This description should not describe the implementation details (how it does it) because these often change over time, resulting in unnecessary
comment maintenance work, or worse, erroneous comments. The code itself and any necessary inline comments describe the implementation.
Arguments passed to a procedure should be described when their purpose is not obvious and when the procedure expects the arguments to be in a specific range. Return values for functions and variables that are changed by a
procedure, especially through reference arguments, should also be described at the beginning of each procedure.
Procedure header comments should include the following section headings. For examples, see the "Formatting Your Code" section that follows.

Section Heading
Purpose
Assumptions
Effects
Inputs
Return Values

Comment Contents
What the procedure does (not how).
List of any external variable, control, or other element whose state affects this procedure.
List of the procedure's effect on each external variable, control, or other element.
Explanation of each argument that is not obvious. Each argument should be on a separate line with inline comments.
Explanation of the value returned.

Remember the following points:

Every important variable declaration should include an inline comment describing the use of the variable being declared.
Variables, controls, and procedures should be named clearly to ensure that inline comments are only needed for complex implementation details.
At the beginning of your script, you should include an overview that describes the script, enumerating objects, procedures, algorithms, dialog boxes, and other system dependencies. Sometimes a piece of pseudocode
describing the algorithm can be helpful.

Formatting Your Code


Screen space should be conserved as much as possible, while still allowing code formatting to reflect logic structure and nesting. Here are a few suggestions:

Indent standard nested blocks four spaces.


Indent the overview comments of a procedure one space.
Indent the highest level statements that follow the overview comments four spaces, with each nested block indented an additional four spaces.

The following code adheres to VBScript coding conventions.


'*********************************************************
' Purpose: Locates the first occurrence of a specified user
'
in the UserList array.
' Inputs: strUserList(): the list of users to be searched.
'
strTargetUser: the name of the user to search for.
' Returns: The index of the first occurrence of the strTargetUser
'
in the strUserList array.
'
If the target user is not found, return -1.
'*********************************************************
Function intFindUser (strUserList(), strTargetUser)
Dim i
' Loop counter.
Dim blnFound
' Target found flag
intFindUser = -1
i = 0
' Initialize loop counter
Do While i <= Ubound(strUserList) and Not blnFound
If strUserList(i) = strTargetUser Then
blnFound = True
' Set flag to True
intFindUser = i
' Set return value to loop count
End If
i = i + 1
' Increment loop counter
Loop
End Function

2001 Microsoft Corporation. All rights reserved.


Build: Topic Version 5.6.9309.1546
Visual Basic Scripting Edition

VBScript and Forms


Simple Validation
You can use Visual Basic Scripting Edition to do much of the form processing that you'd usually have to do on a server. You can also do things that just can't be done on the server.
Here's an example of simple client-side validation. The HTML code is for a text box and a button. If you use Microsoft Internet Explorer to view the page produced by the following code, you'll see a small text box with a
button next to it.
<HTML>
<HEAD><TITLE>Simple Validation</TITLE>
<SCRIPT LANGUAGE="VBScript">
<!-Sub Validate
Dim TheForm
Set TheForm = Document.forms("ValidForm")
If IsNumeric(TheForm.Text1.Value) Then
If TheForm.Text1.Value < 1 Or TheForm.Text1.Value > 10 Then
MsgBox "Please enter a number between 1 and 10."
Else
MsgBox "Thank you."
End If
Else
MsgBox "Please enter a numeric value."
End If
End Sub-->
</SCRIPT>
</HEAD>
<BODY>
<H3>Simple Validation</H3><HR>
<form id="ValidForm" action="nothing.asp" onsubmit="Validate(); return false;" language="jscript">
Enter a value between 1 and 10:
<input name="Text1" TYPE="TEXT" SIZE="2">
<input name="Submit" TYPE="Submit" VALUE="Submit">
</form>
</BODY>
</HTML>

The difference between this text box and the examples on A Simple VBScript Page is that the Value property of the text box is used to check the entered value. To get the Value property, the code has to qualify the reference to
the name of the text box.
You can always write out the full reference Document.ValidForm.Text1 . However, where you have multiple references to form controls, you'll want to do what was done here. First declare a variable. Then use the Set
statement to assign the form to the variable TheForm. A regular assignment statement, such as Dim, doesn't work here; you must use Set to preserve the reference to an object.
Using Numeric Values
Notice that the example directly tests the value against a number: it uses the IsNumeric function to make sure the string in the text box is a number. Although VBScript automatically converts strings and numbers, it's always a
good practice to test a user-entered value for its data subtype and to use conversion functions as necessary. When doing addition with text box values, convert the values explicitly to numbers because the plus sign (+) operator
represents both addition and string concatenation. For example, if Text1 contains "1" and Text2 contains "2", you see the following results:
A = Text1.Value + Text2.Value
' A is "12"
A = CDbl(Text1.Value) + Text2.Value
' A is 3

Validating and Passing Data Back to the Server


The simple validation example uses a plain button control. If a Submit control was used, the example would never see the data to check it everything would go immediately to the server. Avoiding the Submit control lets you
check the data, but it doesn't submit the data to the server. That requires an additional line of code:

<SCRIPT LANGUAGE="VBScript">
<!-Sub Button1_OnClick
Dim TheForm
Set TheForm = Document.ValidForm
If IsNumeric(TheForm.Text1.Value) Then
If TheForm.Text1.Value < 1 Or TheForm.Text1.Value > 10 Then
MsgBox "Please enter a number between 1 and 10."
Else
MsgBox "Thank you."
TheForm.Submit
' Data correct; send to server.
End If
Else
MsgBox "Please enter a numeric value."
End If
End Sub
-->
</SCRIPT>

To send the data to the server, the code invokes the Submit method on the form object when the data is correct. From there, the server handles the data just as it otherwise would except that the data is correct before it gets
there. Find complete information about the Submit method and other methods in the Internet Explorer Scripting Object Model documentation, which can be found on the Microsoft Web site (http://www.microsoft.com).
So far, you've seen only the standard HTML <FORM> objects. Internet Explorer also lets you exploit the full power of ActiveX controls (formerly called OLE controls) and Java objects.

2001 Microsoft Corporation. All rights reserved.


Build: Topic Version 5.6.9309.1546
Visual Basic Scripting Edition

VBScript in Internet Explorer


A Simple VBScript Page
VBScript and Forms
Using VBScript with Objects

2001 Microsoft Corporation. All rights reserved.


Build: Topic Version 5.6.9309.1546
Visual Basic Scripting Edition

Using VBScript with Objects


Using Objects
Whether you use an ActiveX control (formerly called an OLE control) or a Java object, Microsoft Visual Basic Scripting Edition and Microsoft Internet Explorer handle it the same way. If you're using Internet Explorer and
have installed the Label control, you can see the page produced by the following code.
You include an object using the <OBJECT> tags and set its initial property values using <PARAM> tags. If you're a Visual Basic programmer, you'll recognize that using the <PARAM> tags is just like setting initial properties
for a control on a form. For example, the following set of <OBJECT> and <PARAM> tags adds the ActiveX Label control to a page:
<OBJECT
classid="clsid:99B42120-6EC7-11CF-A6C7-00AA00A47DD2"
id=lblActiveLbl
width=250
height=250
align=left
hspace=20
vspace=0
>
<PARAM NAME="Angle" VALUE="90">
<PARAM NAME="Alignment" VALUE="4">
<PARAM NAME="BackStyle" VALUE="0">
<PARAM NAME="Caption" VALUE="A Simple Desultory Label">
<PARAM NAME="FontName" VALUE="Verdana, Arial, Helvetica">
<PARAM NAME="FontSize" VALUE="20">
<PARAM NAME="FontBold" VALUE="1">
<PARAM NAME="FrColor" VALUE="0">
</OBJECT>

You can get properties, set properties, and invoke methods just as with any of the form controls. The following code, for example, includes <FORM> controls you can use to manipulate two properties of the Label control:
<FORM NAME="LabelControls">
<INPUT TYPE="TEXT" NAME="txtNewText" SIZE=25>
<INPUT TYPE="BUTTON" NAME="cmdChangeIt" VALUE="Change Text">
<INPUT TYPE="BUTTON" NAME="cmdRotate" VALUE="Rotate Label">
</FORM>

With the form defined, an event procedure for the cmdChangeIt button changes the label text:
<SCRIPT LANGUAGE="VBScript">
<!-Sub cmdChangeIt_onClick
Dim TheForm
Set TheForm = Document.LabelControls
lblActiveLbl.Caption = TheForm.txtNewText.Value
End Sub
-->
</SCRIPT>

The code qualifies references to controls and values inside the forms just as in the Simple Validation example.
Several ActiveX controls are available for use with Internet Explorer. You can find complete information about the properties, methods, and events there, as well as the class identifiers (CLSID) for the controls on the
Microsoft Web site (http://www.microsoft.com). You can find more information about the <OBJECT> tag on the Internet Explorer 4.0 Author's Guide and HTML Reference page.
Note Earlier releases of Internet Explorerrequired braces ({}) around the classid attribute and did not conform to the W3C specification. Using braces with the current release generates a "This page uses an
outdated version of the <OBJECT> tag" message.

2001 Microsoft Corporation. All rights reserved.


Build: Topic Version 5.6.9309.1546
Visual Basic Scripting Edition

Introduction to Regular Expressions


The information contained in these pages is intended to provide an introduction to regular expressions in general.
While an attempt has been made to make each topic stand on it's own, much of the information contained in these topics relies upon the understanding of a previously introduced feature or concept. Therefore, it's recommended
that you peruse these topics sequentially for the best overall understanding of the material.
The Introduction to Regular Expressions consists of the following individuals topics:
Regular Expressions
Early Beginnings
Uses for Regular Expressions
Regular Expression Syntax
Build a Regular Expression
Order of Precedence
Ordinary Characters
Special Characters
Non-Printable Characters
Character Matching
Quantifiers
Anchors
Alternation and Grouping
Backreferences

2001 Microsoft Corporation. All rights reserved.


Build: Topic Version 5.6.9309.1546
Visual Basic Scripting Edition

Regular Expressions
Unless you have worked with regular expressions before, the term and the concept may be unfamiliar to you. However, they may not be as unfamiliar as you think.
Think about how you search for files on your hard disk. You most likely use the ? and * characters to help find the files you're looking for. The ? character matches a single character in a file name, while the * matches zero or
more characters. A pattern such as 'data?.dat' would find the following files:
data1.dat
data2.dat
datax.dat
dataN.dat
Using the * character instead of the ? character expands the number of files found. 'data*.dat' matches all of the following:
data.dat
data1.dat
data2.dat
data12.dat
datax.dat
dataXYZ.dat
While this method of searching for files can certainly be useful, it is also very limited. The limited ability of the ? and * wildcard characters give you an idea of what regular expressions can do, but regular expressions are much
more powerful and flexible.

2001 Microsoft Corporation. All rights reserved.


Build: Topic Version 5.6.9309.1546
Visual Basic Scripting Edition

Early Beginnings
Regular expressions trace their ancestry back to early research on how the human nervous system works. Warren McCulloch and Walter Pitts, a pair of neuro-physiologists, developed a mathematical way of describing these
neural networks.
In 1956, an mathematician named Stephen Kleene, building on the earlier work of McCulloch and Pitts, published a paper entitled, Representation of Events in Nerve Nets that introduced the concept of regular expressions.
Regular expressions were expressions used to describe what he called "the algebra of regular sets". hence the term "regular expression."
Subsequently, his work found its way into some early efforts with computational search algorithms done by Ken Thompson, the principal inventor of Unix. The first practical application of regular expressions was in the Unix
editor called qed.
And the rest, as they say, is history. Regular expressions have been an important part of text-based editors and search tools ever since.

2001 Microsoft Corporation. All rights reserved.

Build: Topic Version 5.6.9309.1546


Visual Basic Scripting Edition

Uses for Regular Expressions


In a typical search and replace operation, you must provide the exact text you are looking for. That technique may be adequate for simple search and replace tasks in static text, but it lacks flexibility and makes searching
dynamic text difficult, if not impossible.
With regular expressions, you can:

Test for a pattern within a string. For example, you can test an input string to see if a telephone number pattern or a credit card number pattern occurs within the string. This is called data validation.
Replace text. You can use a regular expression to identify specific text in a document and either remove it completely or replace it with other text.
Extract a substring from a string based upon a pattern match. You can find specific text within a document or input field

For example, if you need to search an entire web site to remove some outdated material and replace some HTML formatting tags, you can use a regular expression to test each file to see if the material or the HTML formatting
tags you are looking for exists in that file. That way, you can narrow down the affected files to only those that contain the material that has to be removed or changed. You can then use a regular expression to remove the outdated
material, and finally, you can use regular expressions to search for and replace the tags that need replacing.
Another example of where a regular expression is useful occurs in a language that isn't known for its string-handling ability. VBScript, a subset of Visual Basic, has a rich set of string-handling functions. JScript, like C, does not.
Regular expressions provide a significant improvement in string-handling for JScript. However, regular expressions may also be more efficient to use in VBScript as well, allowing you do perform multiple string manipulations
in a single expression.

2001 Microsoft Corporation. All rights reserved.


Build: Topic Version 5.6.9309.1546
Visual Basic Scripting Edition

Regular Expression Syntax


A regular expression is a pattern of text that consists of ordinary characters (for example, letters a through z) and special characters, known as metacharacters. The pattern describes one or more strings to match when searching a
body of text. The regular expression serves as a template for matching a character pattern to the string being searched.
Here are some examples of regular expression you might encounter:
JScript
/^\[ \t]*$/
/\d{2}-\d{5}/
/<(.*)>.*<\/\1>/

VBScript
"^\[ \t]*$"
"\d{2}-\d{5}"
"<(.*)>.*<\/\1>"

Matches
Match a blank line.
Validate an ID number consisting of 2 digits, a hyphen, and another 5 digits.
Match an HTML tag.

The following table contains the complete list of metacharacters and their behavior in the context of regular expressions:
Character
\
^
$
*
+
?
{n}
{n,}
{n,m}
?

.
(pattern)
(?:pattern)
(?=pattern)

(?!pattern)

x|y
[xyz]
[^xyz]
[a-z]
[^a-z]
\b
\B
\cx
\d
\D
\f
\n
\r
\s
\S
\t
\v
\w
\W
\xn
\num
\n
\nm
\nml
\un

Description
Marks the next character as either a special character, a literal, a backreference, or an octal escape. For example, 'n' matches the character "n". '\n' matches a newline character. The sequence
'\\' matches "\" and "\(" matches "(".
Matches the position at the beginning of the input string. If the RegExp object's Multiline property is set, ^ also matches the position following '\n' or '\r'.
Matches the position at the end of the input string. If the RegExp object's Multiline property is set, $ also matches the position preceding '\n' or '\r'.
Matches the preceding subexpression zero or more times. For example, zo* matches "z" and "zoo". * is equivalent to {0,}.
Matches the preceding subexpression one or more times. For example, 'zo+' matches "zo" and "zoo", but not "z". + is equivalent to {1,}.
Matches the preceding subexpression zero or one time. For example, "do(es)?" matches the "do" in "do" or "does". ? is equivalent to {0,1}
n is a nonnegative integer. Matches exactly n times. For example, 'o{2}' does not match the 'o' in "Bob," but matches the two o's in "food".
n is a nonnegative integer. Matches at least n times. For example, 'o{2,}' does not match the "o" in "Bob" and matches all the o's in "foooood". 'o{1,}' is equivalent to 'o+'. 'o{0,}' is equivalent
to 'o*'.
m and n are nonnegative integers, where n <= m. Matches at least n and at most m times. For example, "o{1,3}" matches the first three o's in "fooooood". 'o{0,1}' is equivalent to 'o?'. Note
that you cannot put a space between the comma and the numbers.
When this character immediately follows any of the other quantifiers (*, +, ?, {n}, {n,}, {n,m}), the matching pattern is non-greedy. A non-greedy pattern matches as little of the searched
string as possible, whereas the default greedy pattern matches as much of the searched string as possible. For example, in the string "oooo", 'o+?' matches a single "o", while 'o+' matches all
'o's.
Matches any single character except "\n". To match any character including the '\n', use a pattern such as '[.\n]'.
Matches pattern and captures the match. The captured match can be retrieved from the resulting Matches collection, using the SubMatches collection in VBScript or the $0$9 properties in
JScript. To match parentheses characters ( ), use '\(' or '\)'.
Matches pattern but does not capture the match, that is, it is a non-capturing match that is not stored for possible later use. This is useful for combining parts of a pattern with the "or"
character (|). For example, 'industr(?:y|ies) is a more economical expression than 'industry|industries'.
Positive lookahead matches the search string at any point where a string matching pattern begins. This is a non-capturing match, that is, the match is not captured for possible later use. For
example 'Windows (?=95|98|NT|2000)' matches "Windows" in "Windows 2000" but not "Windows" in "Windows 3.1". Lookaheads do not consume characters, that is, after a match occurs,
the search for the next match begins immediately following the last match, not after the characters that comprised the lookahead.
Negative lookahead matches the search string at any point where a string not matching pattern begins. This is a non-capturing match, that is, the match is not captured for possible later use.
For example 'Windows (?!95|98|NT|2000)' matches "Windows" in "Windows 3.1" but does not match "Windows" in "Windows 2000". Lookaheads do not consume characters, that is, after a
match occurs, the search for the next match begins immediately following the last match, not after the characters that comprised the lookahead.
Matches either x or y. For example, 'z|food' matches "z" or "food". '(z|f)ood' matches "zood" or "food".
A character set. Matches any one of the enclosed characters. For example, '[abc]' matches the 'a' in "plain".
A negative character set. Matches any character not enclosed. For example, '[^abc]' matches the 'p' in "plain".
A range of characters. Matches any character in the specified range. For example, '[a-z]' matches any lowercase alphabetic character in the range 'a' through 'z'.
A negative range characters. Matches any character not in the specified range. For example, '[^a-z]' matches any character not in the range 'a' through 'z'.
Matches a word boundary, that is, the position between a word and a space. For example, 'er\b' matches the 'er' in "never" but not the 'er' in "verb".
Matches a nonword boundary. 'er\B' matches the 'er' in "verb" but not the 'er' in "never".
Matches the control character indicated by x. For example, \cM matches a Control-M or carriage return character. The value of x must be in the range of A-Z or a-z. If not, c is assumed to be a
literal 'c' character.
Matches a digit character. Equivalent to [0-9].
Matches a nondigit character. Equivalent to [^0-9].
Matches a form-feed character. Equivalent to \x0c and \cL.
Matches a newline character. Equivalent to \x0a and \cJ.
Matches a carriage return character. Equivalent to \x0d and \cM.
Matches any whitespace character including space, tab, form-feed, etc. Equivalent to [ \f\n\r\t\v].
Matches any non-white space character. Equivalent to [^ \f\n\r\t\v].
Matches a tab character. Equivalent to \x09 and \cI.
Matches a vertical tab character. Equivalent to \x0b and \cK.
Matches any word character including underscore. Equivalent to '[A-Za-z0-9_]'.
Matches any nonword character. Equivalent to '[^A-Za-z0-9_]'.
Matches n, where n is a hexadecimal escape value. Hexadecimal escape values must be exactly two digits long. For example, '\x41' matches "A". '\x041' is equivalent to '\x04' & "1". Allows
ASCII codes to be used in regular expressions.
Matches num, where num is a positive integer. A reference back to captured matches. For example, '(.)\1' matches two consecutive identical characters.
Identifies either an octal escape value or a backreference. If \n is preceded by at least n captured subexpressions, n is a backreference. Otherwise, n is an octal escape value if n is an octal digit
(0-7).
Identifies either an octal escape value or a backreference. If \nm is preceded by at least nm captured subexpressions, nm is a backreference. If \nm is preceded by at least n captures, n is a
backreference followed by literal m. If neither of the preceding conditions exists, \nm matches octal escape value nm when n and m are octal digits (0-7).
Matches octal escape value nml when n is an octal digit (0-3) and m and l are octal digits (0-7).
Matches n, where n is a Unicode character expressed as four hexadecimal digits. For example, \u00A9 matches the copyright symbol ().

2001 Microsoft Corporation. All rights reserved.


Build: Topic Version 5.6.9309.1546
Visual Basic Scripting Edition

Build a Regular Expression


Regular expressions are constructed in the same way that arithmetic expressions are created. That is, small expressions are combined using a variety of metacharacters and operators to create larger expressions.
You construct a regular expression by putting the various components of the expression pattern between a pair of delimiters. For JScript, the delimiters are a pair of forward slash (/) characters. For example:
/expression/

For VBScript, a pair of quotation marks ("") delimit regular expressions. For example:
"expression"

In both of the examples shown above, the regular expression pattern (expression) is stored in the Pattern property of the RegExp object.
The components of a regular expression can be individual characters, sets of characters, ranges of characters, choices between characters, or any combination of all of these components.

2001 Microsoft Corporation. All rights reserved.


Build: Topic Version 5.6.9309.1546
Visual Basic Scripting Edition

Order of Precedence
Once you have constructed a regular expression, it is evaluated much like an arithmetic expression, that is, it is evaluated from left to right and follows an order of precedence.
The following table illustrates, from highest to lowest, the order of precedence of the various regular expression operators:
Operator(s)
Description
\
Escape
(), (?:), (?=), []
Parentheses and Brackets
*, +, ?, {n}, {n,}, {n,m} Quantifiers
^, $, \anymetacharacter Anchors and Sequences
|
Alternation

2001 Microsoft Corporation. All rights reserved.


Build: Topic Version 5.6.9309.1546
Visual Basic Scripting Edition

Ordinary Characters
Ordinary characters consist of all those printable and non-printable characters that are not explicitly designated as metacharacters. This includes all upper- and lowercase alphabetic characters, all digits, all punctuation marks,
and some symbols.
The simplest form of a regular expression is a single, ordinary character that matches itself in a searched string. For example, the single-character pattern 'A' matches the letter 'A' wherever it appears in the searched string. Here
are some examples of single-character regular expression patterns:
/a/
/7/
/M/

The equivalent VBScript single-character regular expressions are:


"a"
"7"
"M"

You can combine a number of single characters together to form a larger expression. For example, the following JScript regular expression is nothing more than an expression created by combining the single-character
expressions 'a', '7', and 'M'.
/a7M/

The equivalent VBScript expression is:


"a7M"

Notice that there is no concatenation operator. All that is required is that you just put one character after another.

2001 Microsoft Corporation. All rights reserved.


Build: Topic Version 5.6.9309.1546
Visual Basic Scripting Edition

Special Characters
There are a number of metacharacters that require special treatment when trying to match them. To match these special characters, you must first escape those characters, that is, precede them with a backslash character (\). The
following table shows those special characters and their meanings:
Special Character
$
()
*
+
.
[

Comment
Matches the position at the end of an input string. If the RegExp object's Multiline property is set, $ also matches the position preceding '\n' or '\r'. To match the $ character itself, use \$.
Marks the beginning and end of a subexpression. Subexpressions can be captured for later use. To match these characters, use \( and \).
Matches the preceding subexpression zero or more times. To match the * character, use \*.
Matches the preceding subexpression one or more times. To match the + character, use \+.
Matches any single character except the newline character \n. To match ., use \.
Marks the beginning of a bracket expression. To match [, use \[.

?
\

Matches the preceding subexpression zero or one time, or indicates a non-greedy quantifier. To match the ? character, use \?.
Marks the next character as either a special character, a literal, a backreference, or an octal escape. For example, 'n' matches the character 'n'. '\n' matches a newline character. The sequence
'\\' matches "\" and '\(' matches "(".
Matches the position at the beginning of an input string except when used in a bracket expression where it negates the character set. To match the ^ character itself, use \^.
Marks the beginning of a quantifier expression. To match {, use \{.
Indicates a choice between two items. To match |, use \|.

^
{
|

2001 Microsoft Corporation. All rights reserved.


Build: Topic Version 5.6.9309.1546
Visual Basic Scripting Edition

Non-Printable Characters
There are a number of useful non-printing characters that must be used occasionally. The following table shows the escape sequences used to represent those non-printing characters:
Character
\cx
\f
\n
\r
\s
\S
\t
\v

Meaning
Matches the control character indicated by x. For example, \cM matches a Control-M or carriage return character. The value of x must be in the range of A-Z or a-z. If not, c is assumed to
be a literal 'c' character.
Matches a form-feed character. Equivalent to \x0c and \cL.
Matches a newline character. Equivalent to \x0a and \cJ.
Matches a carriage return character. Equivalent to \x0d and \cM.
Matches any whitespace character including space, tab, form-feed, etc. Equivalent to [\f\n\r\t\v].
Matches any non-whitespace character. Equivalent to [^ \f\n\r\t\v].
Matches a tab character. Equivalent to \x09 and \cI.
Matches a vertical tab character. Equivalent to \x0b and \cK.

2001 Microsoft Corporation. All rights reserved.


Build: Topic Version 5.6.9309.1546
Visual Basic Scripting Edition

Character Matching
The period (.) matches any single printing or non-printing character in a string, except a newline character (\n). The following JScript regular expression matches 'aac', 'abc', 'acc', 'adc', and so on, as well as 'a1c', 'a2c', a-c', and
a#c':
/a.c/

The equivalent VBScript regular expression is:


"a.c"

If you are trying to match a string containing a file name where a period (.) is part of the input string, you do so by preceding the period in the regular expression with a backslash (\) character. To illustrate, the following JScript
regular expression matches 'filename.ext':
/filename\.ext/

For VBScript, the equivalent expression appears as follows:


"filename\.ext"

These expressions are still pretty limited. They only let you match any single character. Many times, it's useful to match specified characters from a list. For example, if you have an input text that contains chapter headings that
are expressed numerically as Chapter 1, Chapter 2, etc, you might want to find those chapter headings.

Bracket Expressions
You can create a list of matching characters by placing one or more individual characters within square brackets ([ and ]). When characters are enclosed in brackets, the list is called a bracket expression. Within brackets, as
anywhere else, ordinary characters represent themselves, that is, they match an occurrence of themselves in the input text. Most special characters lose their meaning when they occur inside a bracket expression. Here are some
exceptions:

The ']' character ends a list if it's not the first item. To match the ']' character in a list, place it first, immediately following the opening '['.
The '\' character continues to be the escape character. To match the '\' character, use '\\'.

Characters enclosed in a bracket expression match only a single character for the position in the regular expression where the bracket expression appears. The following JScript regular expression matches 'Chapter 1', 'Chapter 2',
'Chapter 3', 'Chapter 4', and 'Chapter 5':
/Chapter [12345]/

To match those same chapter heading in VBScript, use the following:


"Chapter [12345]"

Notice that the word 'Chapter' and the space that follows are fixed in position relative to the characters within brackets. The bracket expression then, is used to specify only the set of characters that matches the single character
position immediately following the word 'Chapter' and a space. That is the ninth character position.
If you want to express the matching characters using a range instead of the characters themselves, you can separate the beginning and ending characters in the range using the hyphen (-) character. The character value of the
individual characters determines their relative order within a range. The following JScript regular expression contains a range expression that is equivalent to the bracketed list shown above.
/Chapter [1-5]/

The same expression for VBScript appears as follows:


"Chapter [1-5]"

When a range is specified in this manner, both the starting and ending values are included in the range. It is important to note that the starting value must precede the ending value in Unicode sort order.
If you want to include the hyphen character in your bracket expression, you must do one of the following:

Escape it with a backslash:


[\-]

Put the hyphen character at the beginning or the end of the bracketed list. The following expressions matches all lowercase letters and the hyphen:
[-a-z]
[a-z-]

Create a range where the beginning character value is lower than the hyphen character and the ending character value is equal to or greater than the hyphen. Both of the following regular expressions satisfy this
requirement:

[!--]
[!-~]

You can also find all the characters not in the list or range by placing the caret (^) character at the beginning of the list. If the caret character appears in any other position within the list, it matches itself, that is, it has no special
meaning. The following JScript regular expression matches chapter headings with numbers greater than 5':
/Chapter [^12345]/

For VBScript use:


"Chapter [^12345]"

In the examples shown above, the expression matches any digit character in the ninth position except 1, 2, 3, 4, or 5. So, for example, 'Chapter 7' is a match and so is 'Chapter 9'.
The same expressions above can be represented using the hyphen character (-). For JScript:
/Chapter [^1-5]/

or for VBScript:
"Chapter [^1-5]"

A typical use of a bracket expression is to specify matches of any upper- or lowercase alphabetic characters or any digits. The following JScript expression specifies such a match:
/[A-Za-z0-9]/

The equivalent expression for VBScript is:


"[A-Za-z0-9]"

2001 Microsoft Corporation. All rights reserved.


Build: Topic Version 5.6.9309.1546
Visual Basic Scripting Edition

Quantifiers
Sometimes, you don't know how many characters there are to match. In order to accommodate that kind of uncertainty, regular expressions support the concept of quantifiers. These quantifiers let you specify how many times a
given component of your regular expression must occur for your match to be true.
The following table illustrates the various quantifiers and their meanings:
Character
*
+
?
{n}
{n,}
{n,m}

Description
Matches the preceding subexpression zero or more times. For example, 'zo*' matches "z" and "zoo". * is equivalent to {0,}.
Matches the preceding subexpression one or more times. For example, 'zo+' matches "zo" and "zoo", but not "z". + is equivalent to {1,}.
Matches the preceding subexpression zero or one time. For example, 'do(es)?' matches the "do" in "do" or "does". ? is equivalent to {0,1}
n is a nonnegative integer. Matches exactly n times. For example, 'o{2}' does not match the 'o' in "Bob," but matches the two o's in "food".
n is a nonnegative integer. Matches at least n times. For example, 'o{2,}' does not match the 'o' in "Bob" and matches all the o's in "foooood". 'o{1,}' is equivalent to 'o+'. 'o{0,}' is
equivalent to 'o*'.
m and n are nonnegative integers, where n <= m. Matches at least n and at most m times. For example, 'o{1,3}' matches the first three o's in "fooooood". 'o{0,1}' is equivalent to 'o?'. Note
that you cannot put a space between the comma and the numbers.

With a large input document, chapter numbers could easily exceed nine, so you need a way to handle two or three digit chapter numbers. Quantifiers give you that capability. The following JScript regular expression matches
chapter headings with any number of digits:
/Chapter [1-9][0-9]*/

The following VBScript regular expression performs the identical match:


"Chapter [1-9][0-9]*"

Notice that the quantifier appears after the range expression. Therefore, it applies to the entire range expression that, in this case, specifies only digits from 0 through 9, inclusive.
The '+' quantifier is not used here because there does not necessarily need to be a digit in the second or subsequent position. The '?' character also is not used because it limits the chapter numbers to only two digits. You want to
match at least one digit following 'Chapter' and a space character.
If you know that your chapter numbers are limited to only 99 chapters, you can use the following JScript expression to specify at least one, but not more than 2 digits.
/Chapter [0-9]{1,2}/

For VBScript, use the following regular expression:


"Chapter [0-9]{1,2}"

The disadvantage to the expression shown above is that if there is a chapter number greater than 99, it will still only match the first two digits. Another disadvantage is that somebody could create a Chapter 0 and it would match.
Better JScript expressions for matching only two digits are the following:
/Chapter [1-9][0-9]?/

or
/Chapter [1-9][0-9]{0,1}/

For VBScript, the following expressions are equivalent:


"Chapter [1-9][0-9]?"

or
"Chapter [1-9][0-9]{0,1}"

The '*', '+', and '?' quantifiers are all what are referred to as greedy, that is, they match as much text as possible. Sometimes that's not at all what you want to happen. Sometimes, you just want a minimal match.
Say, for example, you are searching an HTML document for an occurrence of a chapter title enclosed in an H1 tag. That text appears in your document as:
<H1>Chapter 1 Introduction to Regular Expressions</H1>

The following expression matches everything from the opening less than symbol (<) to the greater than symbol at the end of the closing H1 tag.
/<.*>/

The VBScript regular expression is:


"<.*>"

If all you really wanted to match was the opening H1 tag, the following, non-greedy expression matches only <H1>.
/<.*?>/

or
"<.*?>"

By placing the '?' after a '*', '+', or '?' quantifier, the expression is transformed from a greedy to a non-greedy, or minimal, match.

2001 Microsoft Corporation. All rights reserved.


Build: Topic Version 5.6.9309.1546
Visual Basic Scripting Edition

Anchors
So far, the examples you've seen have been concerned only with finding chapter headings wherever they occur. Any occurrence of the string 'Chapter' followed by a space, followed by a number, could be an actual chapter
heading, or it could also be a cross-reference to another chapter. Since true chapter headings always appear at the beginning of a line, you'll need to devise a way to find only the headings and not find the cross-references.
Anchors provide that capability. Anchors allow you to fix a regular expression to either the beginning or end of a line. They also allow you to create regular expressions that occur either within a word or at the beginning or end
of a word. The following table contains the list of regular expression anchors and their meanings:
Character
^
$
\b
\B

Description
Matches the position at the beginning of the input string. If the RegExp object's Multiline property is set, ^ also matches the position following '\n' or '\r'.
Matches the position at the end of the input string. If the RegExp object's Multiline property is set, $ also matches the position preceding '\n' or '\r'.
Matches a word boundary, that is, the position between a word and a space.
Matches a nonword boundary.

You cannot use a quantifier with an anchor. Since you cannot have more than one position immediately before or after a newline or word boundary, expressions such as '^*' are not permitted.
To match text at the beginning of a line of text, use the '^' character at the beginning of the regular expression. Don't confuse this use of the '^' with the use within a bracket expression. They're definitely not the same.
To match text at the end of a line of text, use the '$' character at the end of the regular expression.
To use anchors when searching for chapter headings, the following JScript regular expression matches a chapter heading with up to two following digits that occurs at the beginning of a line:
/^Chapter [1-9][0-9]{0,1}/

For VBScript the same regular expressions appears as:


"^Chapter [1-9][0-9]{0,1}"

Not only does a true chapter heading occur at the beginning of a line, it's also the only thing on the line, so it also must be at the end of a line as well. The following expression ensures that the match you've specified only
matches chapters and not cross-references. It does so by creating a regular expression that matches only at the beginning and end of a line of text.
/^Chapter [1-9][0-9]{0,1}$/

For VBScript use:


"^Chapter [1-9][0-9]{0,1}$"

Matching word boundaries is a little different but adds a very important capability to regular expressions. A word boundary is the position between a word and a space. A non-word boundary is any other position. The following
JScript expression matches the first three characters of the word 'Chapter' because they appear following a word boundary:
/\bCha/

or for VBScript:
"\bCha"

The position of the '\b' operator is critical here. If it's positioned at the beginning of a string to be matched, it looks for the match at the beginning of the word; if it's positioned at the end of the string, it looks for the match at the
end of the word. For example, the following expressions match 'ter' in the word 'Chapter' because it appears before a word boundary:
/ter\b/

and
"ter\b"

The following expressions match 'apt' as it occurs in 'Chapter', but not as it occurs in 'aptitude':
/\Bapt/

and
"\Bapt"

That's because 'apt' occurs on a non-word boundary in the word 'Chapter' but on a word boundary in the word 'aptitude'. For the non-word boundary operator, position isn't important because the match isn't relative to the
beginning or end of a word.

2001 Microsoft Corporation. All rights reserved.


Build: Topic Version 5.6.9309.1546
Visual Basic Scripting Edition

Alternation and Grouping


Alternation allows use of the '|' character to allow a choice between two or more alternatives. Expanding the chapter heading regular expression, you can expand it to cover more than just chapter headings. However, it's not as
straightforward as you might think. When alternation is used, the largest possible expression on either side of the '|' character is matched. You might think that the following expressions for JScript and VBScript match either
'Chapter' or 'Section' followed by one or two digits occurring at the beginning and ending of a line:
/^Chapter|Section [1-9][0-9]{0,1}$/
"^Chapter|Section [1-9][0-9]{0,1}$"

Unfortunately, what happens is that the regular expressions shown above match either the word 'Chapter' at the beginning of a line, or 'Section' and whatever numbers follow that, at the end of the line. If the input string is
'Chapter 22', the expression shown above only matches the word 'Chapter'. If the input string is 'Section 22', the expression matches 'Section 22'. But that's not the intent here so there must be a way to make that regular
expression more responsive to what you're trying to do and there is.
You can use parentheses to limit the scope of the alternation, that is, make sure that it applies only to the two words, 'Chapter' and 'Section'. However, parentheses are tricky as well, because they are also used to create

subexpressions, something that's covered later in the section on subexpressions. By taking the regular expressions shown above and adding parentheses in the appropriate places, you can make the regular expression match either
'Chapter 1' or 'Section 3'.
The following regular expressions use parentheses to group 'Chapter' and 'Section' so the expression works properly. For JScript:
/^(Chapter|Section) [1-9][0-9]{0,1}$/

For VBScript:
"^(Chapter|Section) [1-9][0-9]{0,1}$"

These expressions work properly except that an interesting by-product occurs. Placing parentheses around 'Chapter|Section' establishes the proper grouping, but it also causes either of the two matching words to be captured for
future use. Since there's only one set of parentheses in the expression shown above, there is only one captured submatch. This submatch can be referred to using the Submatches collection in VBScript or the $1-$9 properties of
the RegExp object in JScript.
Sometimes capturing a submatch is desirable, sometimes it's not. In the examples shown above, all you really want to do is use the parentheses for grouping a choice between the words 'Chapter' or 'Section'. You don't
necessarily want to refer to that match later. In fact, unless you really need to capture submatches, don't use them. Your regular expressions will be more efficient since they won't have to take the time and memory to store those
submatches.
You can use '?:' before the regular expression pattern inside the parentheses to prevent the match from being saved for possible later use. The following modification of the regular expressions shown above provides the same
capability without saving the submatch. For JScript:
/^(?:Chapter|Section) [1-9][0-9]{0,1}$/

For VBScript:
"^(?:Chapter|Section) [1-9][0-9]{0,1}$"

In addition to the '?:' metacharacters, there are two other non-capturing metacharacters used for something called lookahead matches. A positive lookahead, specified using ?=, matches the search string at any point where a
matching regular expression pattern in parentheses begins. A negative lookahead, specified using '?!', matches the search string at any point where a string not matching the regular expression pattern begins.
For example, suppose you have a document containing references to Windows 3.1, Windows 95, Windows 98, and Windows NT. Suppose further that you need to update the document by finding all the references to Windows
95, Windows 98, and Windows NT and changing those reference to Windows 2000. You can use the following JScript regular expression, which is an example of a positive lookahead, to match Windows 95, Windows 98, and
Windows NT:
/Windows(?=95 |98 |NT )/

To make the same match in VBScript, use the following:


"Windows(?=95 |98 |NT )"

Once the match is found, the search for the next match begins immediately following the matched text, not including the characters included in the look-ahead. For example, if the expressions shown above matched 'Windows
98', the search resumes after 'Windows' not after '98'.

2001 Microsoft Corporation. All rights reserved.


Build: Topic Version 5.6.9309.1546
Visual Basic Scripting Edition

Backreferences
One of the most important features of regular expressions is the ability to store a part of a matched pattern for later reuse. As you'll recall, placing parentheses around a regular expression pattern or part of a pattern causes that
part of the expression to be stored into a temporary buffer. You can override the saving of that part of the regular expression using the non-capturing metacharacters '?:', '?=', or '?!'.
Each captured submatch is stored as it is encountered from left to right in a regular expressions pattern. The buffer numbers where the submatches are stored begin at 1 and continue up to a maximum of 99 subexpressions. Each
different buffer can be accessed using '\n' where n is one or two decimal digits identifying a specific buffer.
One of the simplest, most useful applications of back references provides the ability to locate the occurrence of two identical words together in a text. Take the following sentence:
Is is the cost of of gasoline going up up?

As written, the sentence shown above clearly has a problem with several duplicated words. It would be nice to devise a way to fix that sentence without having to look for duplicates of every single word. The following JScript
regular expression uses a single subexpression to do that.
/\b([a-z]+) \1\b/gi

The equivalent VBScript expression is:


"\b([a-z]+) \1\b"

The subexpression, in this case, is everything between parentheses. That captured expression includes one or more alphabetic characters, as specified by '[a-z]+'. The second part of the regular expression is the reference to the
previously captured submatch, that is, the second occurrence of the word just matched by the parenthetical expression. '\1' is used to specified the first submatch. The word boundary Meta characters ensure that only separate
words are detected. If they weren't, a phrase such as "is issued" or "this is" would be incorrectly identified by this expression.
In the JScript expression the global flag ('g') following the regular expression indicates that the expression is applied to as many matches as it can find in the input string. The case insensitivity ('i') flag at the end of the expression
specifies the case insensitivity. The multiline flag specifies that potential matches may occur on either side of a newline character. For VBScript, the various flags cannot be set in the expression but must be explicitly set using
properties of the RegExp object.
Using the regular expression shown above, the following JScript code can use the submatch information to replace an occurrence of two consecutive identical words in a string of text with a single occurrence of the same word:
var ss = "Is is the cost of of gasoline going up up?.\n";
var re = /\b([a-z]+) \1\b/gim;
//Create regular expression pattern.
var rv = ss.replace(re,"$1");
//Replace two occurrences with one.

The closest equivalent VBScript code appears as follows:


Dim ss, re, rv
ss = "Is is the cost of of gasoline going up up?." & vbNewLine
Set re = New RegExp
re.Pattern = "\b([a-z]+) \1\b"
re.Global = True
re.IgnoreCase = True
re.MultiLine = True
rv = re.Replace(ss,"$1")

In the VBScript code, notice that the global, case-insensitivity, and multiline flags are set using the appropriately named properties of the RegExp object.
The use of the $1 within the replace method refers to the first saved submatch. If you had more than one submatch, you'd refer to them consecutively by $2, $3, and so on.
Another way that backreferences can be used is to break down a Universal Resource Indicator (URI) into its component parts. Assume that you want to break down the following URI down to the protocol (ftp, http, etc), the
domain address, and the page/path:
http://msdn.microsoft.com:80/scripting/default.htm

The following regular expressions provide that functionality. For JScript:


/(\w+):\/\/([^/:]+)(:\d*)?([^# ]*)/

For VBScript:
"(\w+):\/\/([^/:]+)(:\d*)?([^# ]*)"

The first parenthetical subexpression is designed to capture the protocol part of the web address. That subexpression matches any word that precedes a colon and two forward slashes. The second parenthetical subexpression
captures the domain address part of the address. That subexpression matches any sequence of characters that does not include '^', '/', or ':' characters. The third parenthetical subexpression captures a website port number, if one is
specified. That subexpression matches zero or more digits following a colon. And finally, the fourth parenthetical subexpression captures the path and/or page information specified by the web address. That subexpression
matches one or more characters other than '#' or the space character.
Applying the regular expression to the URI shown above, the submatches contain the following:

RegExp.$1 contains "http"


RegExp.$2 contains "msdn.microsoft.com"
RegExp.$3 contains ":80"
RegExp.$4 contains "/scripting/default.htm"

2001 Microsoft Corporation. All rights reserved.


Build: Topic Version 5.6.9309.1546
Visual Basic Scripting Edition

VBScript Language Reference


Constants
Errors
Events
Functions
Methods
Miscellaneous
Objects and Collections
Operators
Properties
Statements

2001 Microsoft Corporation. All rights reserved.


Build: Topic Version 5.6.9309.1546
Visual Basic Scripting Edition

Version Information
The following table lists the version of Microsoft Visual Basic Scripting Edition implemented by host applications.
Host Application
1.0
2.0
3.0
4.0
5.0
5.5
5.6
Microsoft Internet Explorer 3.0
x
Microsoft Internet Information Server 3.0
x
Microsoft Internet Explorer 4.0
x
Microsoft Internet Information Server 4.0
x
Microsoft Windows Scripting Host 1.0
x
Microsoft Outlook 98
x
Microsoft Visual Studio 6.0
x
Microsoft Internet Explorer 5.0
x
Microsoft Internet Information Services 5.0
x
Microsoft Internet Explorer 5.5
x
Microsoft Visual Studio .NET
x
The following table lists VBScript language features and the version when first introduced.
Language Element
Abs Function
Addition Operator (+)
And Operator
Array Function
Asc Function
Assignment Operator (=)
Atn Function
Call Statement
CBool Function
CByte Function
CCur Function
CDate Function
CDbl Function
Chr Function
CInt Function
Class Object
Class Statement
Clear Method
CLng Function
Color Constants
Comparison Constants
Concatenation Operator (&)
Const Statement
Cos Function
CreateObject Function
CSng Function
CStr Function

1.0

2.0

3.0

4.0

5.0

x
x
x
x
x
x
x
x
x
x
x
x
x
x
x
x
x
x
x
x
x
x
x
x
x
x
x

5.5

5.6

Date and Time Constants


Date Format Constants
Date Function
DateAdd Function
DateDiff Function
DatePart Function
DateSerial Function
DateValue Function
Day Function
Description Property
Dim Statement
Division Operator (/)
Do...Loop Statement
Empty
Eqv Operator
Erase Statement
Err Object
Eval Function
Execute Method
Execute Statement
ExecuteGlobal Statement
Exit Statement
Exp Function
Exponentiation Operator (^)
False
Filter Function
FirstIndex Property
Fix Function
For...Next Statement
For Each...Next Statement
FormatCurrency Function
FormatDateTime Function
FormatNumber Function
FormatPercent Function
Function Statement
GetLocale Function
GetObject Function
GetRef Function
Global Property
Hex Function
HelpContext Property
HelpFile Property
Hour Function
If...Then...Else Statement
IgnoreCase Property
Imp Operator
Initialize Event
InputBox Function
InStr Function
InStrRev Function
Int Function
Integer Division Operator (\)
Is Operator
IsArray Function
IsDate Function
IsEmpty Function
IsNull Function
IsNumeric Function
IsObject Function
Join Function
LBound Function
LCase Function
Left Function
Len Function
Length Property
LoadPicture Function
Log Function
LTrim Function
Match Object
Matches Collection
Mid Function
Minute Function
Miscellaneous Constants
Mod Operator
Month Function
MonthName Function
MsgBox Constants
MsgBox Function
Multiplication Operator (*)
Negation Operator (-)
Not Operator
Now Function
Nothing
Null
Number Property
Oct Function
On Error Statement
Option Explicit Statement
Or Operator
Pattern Property
Private Statement
PropertyGet Statement
PropertyLet Statement
PropertySet Statement
Public Statement
Raise Method
Randomize Statement
ReDim Statement
RegExp Object
Rem Statement

x
x
x
x
x
x
x
x
x
x
x
x
x
x
x
x
x
x
x
x
x
x
x
x
x
x
x
x
x
x
x
x
x
x
x
x
x
x
x
x
x
x
x
x
x
x
x
x
x
x
x
x
x
x
x
x
x
x
x
x
x
x
x
x
x
x
x
x
x
x
x
x
x
x
x
x
x
x
x
x
x
x
x
x
x
x
x
x
x
x
x
x
x
x
x
x
x
x
x
x

Replace Function
Replace Method
RGB Function
Right Function
x
Rnd Function
x
Round Function
RTrim Function
x
ScriptEngine Function
ScriptEngineBuildVersion Function
ScriptEngineMajorVersion Function
ScriptEngineMinorVersion Function
Second Function
x
Select Case Statement
x
Set Statement
x
SetLocale Function
Sgn Function
x
Sin Function
x
Source Property
x
Space Function
x
Split Function
Sqr Function
x
StrComp Function
x
String Constants
String Function
x
StrReverse Function
Sub Statement
x
Subtraction Operator (-)
x
Tan Function
x
Terminate Event
Test Method
Time Function
x
Timer Function
TimeSerial Function
x
TimeValue Function
x
Trim Function
x
Tristate Constants
True
x
TypeName Function
UBound Function
x
UCase Function
x
Value Property
VarType Constants
VarType Function
x
VBScript Constants
Weekday Function
x
WeekdayName Function
While...Wend Statement
x
With Statement
Xor Operator
x
Year Function
x

x
x
x

x
x
x
x
x

x
x

x
x
x

x
x

x
x
x
x
x

2001 Microsoft Corporation. All rights reserved.


Build: Topic Version 5.6.9309.1546
Visual Basic Scripting Edition

VBScript Constants
A number of useful constants you can use in your code are built into VBScript. Constants provide a convenient way to use specific values without actually having to remember the value itself. Using constants also makes your
code more maintainable should the value of any constant ever change. Because these constants are already defined in VBScript, you don't need to explicitly declare them in your code. Simply use them in place of the values they
represent.
Here are the various categories of constants provided in VBScript and a brief description of each:

Color Constants
Defines eight basiccolors that can be used in scripting.
Date and Time Constants Defines date and time constants used byvarious date and time functions.
Date Format Constants Defines constants used to format dates andtimes.
Miscellaneous Constants Defines constants that don't conveniently fitinto any other category.
MsgBox Constants Defines constants used in theMsgBox function to describe button visibility, labeling, behavior, and return values.
String Constants
Defines variety
a
of non-printable characters used in string manipulation.
Tristate Constants
Defines
constants used with functions that format numbers.
VarType Constants
Defines thevarious Variant subtypes.

Requirements
Version 2

2001 Microsoft Corporation. All rights reserved.


Build: Topic Version 5.6.9309.1546
Visual Basic Scripting Edition

Color Constants
Since these constants are built into VBScript, you don't have to define them before using them. Use them anywhere in your code to represent the values shown for each.
Constant
vbBlack
vbRed
vbGreen
vbYellow
vbBlue
vbMagenta
vbCyan
vbWhite

Value
&h00
Black
&hFF
Red
&hFF00 Green
&hFFFF Yellow
&hFF0000 Blue
&hFF00FF Magenta
&hFFFF00 Cyan
&hFFFFFF White

Description

Requirements
Version 2
See Also
Comparison Constants | Date and Time Constants | Date Format Constants | Miscellaneous Constants | MsgBox Constants | String Constants | Tristate Constants | VarType Constants

2001 Microsoft Corporation. All rights reserved.


Build: Topic Version 5.6.9309.1546
Visual Basic Scripting Edition

Comparison Constants
Since these constants are built into VBScript, you don't have to define them before using them. Use them anywhere in your code to represent the values shown for each.
Constant
Value
Description
vbBinaryCompare 0
Perform a binary comparison.
vbTextCompare 1
Perform a textual comparison.
Requirements
Version 2
See Also
Color Constants | Date and Time Constants | Date Format Constants | Miscellaneous Constants | MsgBox Constants | String Constants | Tristate Constants | VarType Constants

2001 Microsoft Corporation. All rights reserved.


Build: Topic Version 5.6.9309.1546
Visual Basic Scripting Edition

Date and Time Constants


Since these constants are built into VBScript, you don't have to define them before using them. Use them anywhere in your code to represent the values shown for each.
Constant

Value

vbSunday
vbMonday
vbTuesday
vbWednesday
vbThursday
vbFriday
vbSaturday
vbUseSystemDayOfWeek
vbFirstJan1
vbFirstFourDays
vbFirstFullWeek

1
2
3
4
5
6
7
0
1
2
3

Description
Sunday
Monday
Tuesday
Wednesday
Thursday
Friday
Saturday
Use the day of the week specified in your system settings for the first day of the week.
Use the week in which January 1 occurs (default).
Use the first week that has at least four days in the new year.
Use the first full week of the year.

Requirements
Version 2
See Also
Color Constants | Comparison Constants | Date Format Constants | Miscellaneous Constants | MsgBox Constants | String Constants | Tristate Constants | VarType Constants

2001 Microsoft Corporation. All rights reserved.


Build: Topic Version 5.6.9309.1546
Visual Basic Scripting Edition

Date Format Constants


Since these constants are built into VBScript, you don't have to define them before using them. Use them anywhere in your code to represent the values shown for each.
Constant

Value

vbGeneralDate

vbLongDate
vbShortDate
vbLongTime
vbShortTime

1
2
3
4

Description
Display a date and/or time. For real numbers, display a date and time. If there is no fractional part, display only a date. If there is no integer
part, display time only. Date and time display is determined by your system settings.
Display a date using the long date format specified in your computer's regional settings.
Display a date using the short date format specified in your computer's regional settings.
Display a time using the long time format specified in your computer's regional settings.
Display a time using the short time format specified in your computer's regional settings.

Requirements
Version 2
See Also
Color Constants | Comparison Constants | Date and Time Constants | Miscellaneous Constants | MsgBox Constants | String Constants | Tristate Constants | VarType Constants

2001 Microsoft Corporation. All rights reserved.


Build: Topic Version 5.6.9309.1546

Visual Basic Scripting Edition

Miscellaneous Constants
Since this constant is built into VBScript, you don't have to define it before using it. Use it anywhere in your code to represent the values shown.
Constant
vbObjectError

Value
-2147221504

Description
User-defined error numbers should be greater than this value, for example,
Err.Raise Number = vbObjectError + 1000

Requirements
Version 2
See Also
Color Constants | Comparison Constants | Date and Time Constants | Date Format Constants | MsgBox Constants | String Constants | Tristate Constants | VarType Constants

2001 Microsoft Corporation. All rights reserved.


Build: Topic Version 5.6.9309.1546
Visual Basic Scripting Edition

MsgBox Constants
The following constants are used with the MsgBox function to identify what buttons and icons appear on a message box and which button is the default. In addition, the modality of the MsgBox can be specified. Since these
constants are built into VBScript, you don't have to define them before using them. Use them anywhere in your code to represent the values shown for each.
Constant

Value

vbOKOnly
vbOKCancel
vbAbortRetryIgnore
vbYesNoCancel
vbYesNo
vbRetryCancel
vbCritical
vbQuestion
vbExclamation
vbInformation
vbDefaultButton1
vbDefaultButton2
vbDefaultButton3
vbDefaultButton4
vbApplicationModal
vbSystemModal

0
1
2
3
4
5
16
32
48
64
0
256
512
768
0
4096

Description
Display OK button only.
Display OK and Cancel buttons.
Display Abort, Retry, and Ignore buttons.
Display Yes, No, and Cancel buttons.
Display Yes and No buttons.
Display Retry and Cancel buttons.
Display Critical Message icon.
Display Warning Query icon.
Display Warning Message icon.
Display Information Message icon.
First button is the default.
Second button is the default.
Third button is the default.
Fourth button is the default.
Application modal. The user must respond to the message box before continuing work in the current application.
System modal. On Win16 systems, all applications are suspended until the user responds to the message box. On Win32
systems, this constant provides an application modal message box that always remains on top of any other programs you may
have running.

The following constants are used with the MsgBox function to identify which button a user has selected. These constants are only available when your project has an explicit reference to the appropriate type library containing
these constant definitions. For VBScript, you must explicitly declare these constants in your code.
Constant
vbOK
vbCancel
vbAbort
vbRetry
vbIgnore
vbYes
vbNo

Value
Description
1
OK button was clicked.
2
Cancel button was clicked.
3
Abort button was clicked.
4
Retry button was clicked.
5
Ignore button was clicked.
6
Yes button was clicked.
7
No button was clicked.

Requirements
Version 2
See Also
Color Constants | Comparison Constants | Date and Time Constants | Date Format Constants | Miscellaneous Constants | String Constants | Tristate Constants | VarType Constants

2001 Microsoft Corporation. All rights reserved.


Build: Topic Version 5.6.9309.1546
Visual Basic Scripting Edition

String Constants
Since these constants are built into VBScript, you don't have to define them before using them. Use them anywhere in your code to represent the values shown for each.
Constant
vbCr
VbCrLf
vbFormFeed
vbLf
vbNewLine
vbNullChar
vbNullString
vbTab
vbVerticalTab
Requirements
Version 2
See Also

Value
Description
Chr(13)
Carriage return.
Chr(13) & Chr(10)
Carriage returnlinefeed combination.
Chr(12)
Form feed; not useful in Microsoft Windows.
Chr(10)
Line feed.
Chr(13) & Chr(10) or Chr(10) Platform-specific newline character; whatever is appropriate for the platform.
Chr(0)
Character having the value 0.
String having value 0
Not the same as a zero-length string (""); used for calling external procedures.
Chr(9)
Horizontal tab.
Chr(11)
Vertical tab; not useful in Microsoft Windows.

Color Constants | Comparison Constants | Date and Time Constants | Date Format Constants | Miscellaneous Constants | MsgBox Constants | Tristate Constants | VarType Constants

2001 Microsoft Corporation. All rights reserved.


Build: Topic Version 5.6.9309.1546
Visual Basic Scripting Edition

Tristate Constants
Since these constants are built into VBScript, you don't have to define them before using them. Use them anywhere in your code to represent the values shown for each.
Constant
vbUseDefault
vbTrue
vbFalse

Value
Description
-2
Use default from computer's regional settings.
-1
True
0
False

Requirements
Version 2
See Also
Color Constants | Comparison Constants | Date and Time Constants | Date Format Constants | Miscellaneous Constants | MsgBox Constants | String Constants | VarType Constants

2001 Microsoft Corporation. All rights reserved.


Build: Topic Version 5.6.9309.1546
Visual Basic Scripting Edition

VarType Constants
These constants are only available when your project has an explicit reference to the appropriate type library containing these constant definitions. For VBScript, you must explicitly declare these constants in your code.
Constant
vbEmpty
vbNull
vbInteger
vbLong
vbSingle
vbSingle
vbCurrency
vbDate
vbString
vbObject
vbError
vbBoolean
vbVariant
vbDataObject
vbDecimal
vbByte
vbArray

Value
Description
0 Uninitialized (default)
1 Contains no valid data
2 Integer subtype
3 Long subtype
4 Single subtype
5 Double subtype
6 Currency subtype
7 Date subtype
8 String subtype
9 Object
10
Error subtype
11
Boolean subtype
12
Variant (used only for arrays of variants)
13
Data access object
14
Decimal subtype
17
Byte subtype
8192 Array

Requirements
Version 2
See Also
Color Constants | Comparison Constants | Date and Time Constants | Date Format Constants | Miscellaneous Constants | MsgBox Constants | String Constants | Tristate Constants

2001 Microsoft Corporation. All rights reserved.


Build: Topic Version 5.6.9309.1546
Visual Basic Scripting Edition

Errors
In This Section
VBScript Run-time Errors
VBScript Syntax Errors
Related Sections

2001 Microsoft Corporation. All rights reserved.


Build: Topic Version 5.6.9309.1546
Visual Basic Scripting Edition

VBScript Run-time Errors


VBScript run-time errors are errors that result when your VBScript script attempts to perform an action that the system cannot execute. VBScript run-time errors occur while your script is being executed; when variable
expressions are being evaluated, and memory is being dynamic allocated.
Error Number

Description

429
507
449
17
430
506
11
48
5020
5019
432
92
5008
51
505
481
5
5021
94
448
447
445
438
451
504
503
502
424
91
7
28
14
6
35
9
5017
462
10
13
5018
500
458
450

ActiveX component can't create object


An exception occurred
Argument not optional
Can't perform requested operation
Class doesn't support Automation
Class not defined
Division by zero
Error in loading DLL
Expected ')' in regular expression
Expected ']' in regular expression
File name or class name not found during Automation operation
For loop not initialized
Illegal assignment
Internal error
Invalid or unqualified reference
Invalid picture
Invalid procedure call or argument
Invalid range in character set
Invalid use of Null
Named argument not found
Object doesn't support current locale setting
Object doesn't support this action
Object doesn't support this property or method
Object not a collection
Object not safe for creating
Object not safe for initializing
Object not safe for scripting
Object required
Object variable not set
Out of Memory
Out of stack space
Out of string space
Overflow
Sub or function not defined
Subscript out of range
Syntax error in regular expression
The remote server machine does not exist or is unavailable
This array is fixed or temporarily locked
Type mismatch
Unexpected quantifier
Variable is undefined
Variable uses an Automation type not supported in VBScript
Wrong number of arguments or invalid property assignment

See Also
VBScript Syntax Errors

2001 Microsoft Corporation. All rights reserved.


Build: Topic Version 5.6.9309.1546
Visual Basic Scripting Edition

VBScript Syntax Errors


VBScript syntax errors are errors that result when the structure of one of your VBScript statements violates one or more of the grammatical rules of the VBScript scripting language. VBScript syntax errors occur during the
program compilation stage, before the program has begun to be executed.
Error Number
1052
1044
1053
1058
1057
1005
1006
1011
1021
1047
1025
1014
1023
1015
1010
1012
1046
1026
1049
1045
1019
1020
1050
1022
1024
1016
1017
1013
1018
1027
1028
1029
1030
1014
1039
1040
1013

Description
Cannot have multiple default property/method in a Class
Cannot use parentheses when calling a Sub
Class initialize or terminate do not have arguments
'Default' specification can only be on Property Get
'Default' specification must also specify 'Public'
Expected '('
Expected ')'
Expected '='
Expected 'Case'
Expected 'Class'
Expected end of statement
Expected 'End'
Expected expression
Expected 'Function'
Expected identifier
Expected 'If'
Expected 'In'
Expected integer constant
Expected Let or Set or Get in property declaration
Expected literal constant
Expected 'Loop'
Expected 'Next'
Expected 'Property'
Expected 'Select'
Expected statement
Expected 'Sub'
Expected 'Then'
Expected 'To'
Expected 'Wend'
Expected 'While' or 'Until'
Expected 'While,' 'Until,' or end of statement
Expected 'With'
Identifier too long
Invalid character
Invalid 'exit' statement
Invalid 'for' loop control variable
Invalid number

1037
1038
1048
1042
1041
1051
1001
1054
1002
1055
1015

Invalid use of 'Me' keyword


'loop' without 'do'
Must be defined inside a Class
Must be first statement on the line
Name redefined
Number of arguments must be consistent across properties specification
Out of Memory
Property Set or Let must have at least one argument
Syntax error
Unexpected 'Next'
Unterminated string constant

See Also
VBScript Run-time Errors

2001 Microsoft Corporation. All rights reserved.


Build: Topic Version 5.6.9309.1546
Visual Basic Scripting Edition

Events
In This Section
Initialize Event
Terminate Event
Related Sections
VBScript Langauge Reference

2001 Microsoft Corporation. All rights reserved.


Build: Topic Version 5.6.9309.1546
Visual Basic Scripting Edition

Initialize Event
Occurs when an instance of the associated class is created.
Private Sub Class_Initialize()
statements
End Sub

The statements part consists of zero or more code statements to be run when the class is initialized.
Remarks
The following example illustrates the use of the Initialize event.
Class TestClass
Private Sub Class_Initialize
' Setup Initialize event.
MsgBox("TestClass started")
End Sub
Private Sub Class_Terminate
' Setup Terminate event.
MsgBox("TestClass terminated")
End Sub
End Class
Set X = New TestClass
' Create an instance of TestClass.
Set X = Nothing
' Destroy the instance.

Requirements
Version 5
See Also
Class Object | Class Statement | Terminate Event
Applies To: Class Object

2001 Microsoft Corporation. All rights reserved.


Build: Topic Version 5.6.9309.1546
Visual Basic Scripting Edition

Terminate Event
Occurs when an instance of the associated class is terminated.
Private Sub Class_Terminate()
statements
End Sub

The statements part consists of zero or more code statements to be run when the class is initialized.
Remarks
The following example illustrates the use of the Terminate event.
Class TestClass
Private Sub Class_Initialize

' Setup Initialize event.

MsgBox("TestClass started")
End Sub
Private Sub Class_Terminate
' Setup Terminate event.
MsgBox("TestClass terminated")
End Sub
End Class
Set X = New TestClass
' Create an instance of TestClass.
Set X = Nothing
' Destroy the instance.

Requirements
Version 5
See Also
Class Object | Class Statement | Initialize Event
Applies To: Class Object

2001 Microsoft Corporation. All rights reserved.


Build: Topic Version 5.6.9309.1546
Visual Basic Scripting Edition

Functions
The following table contains the VBScript functions.
Abs
CBool
CDbl
Conversions
Date
DateSerial
Eval
FormatDateTime
GetObject
InputBox
IsArray
IsNumeric
LCase
Log
Minute
Now
Right
ScriptEngineBuildVersion
SetLocale
Split
Tan
TimeValue
VarType

Array
Asc
Atn
CByte
CCur
CDate
Chr
CInt
CLng
Cos
CreateObject
CSng
DateAdd
DateDiff
DatePart
DateValue
Day
Derived Maths
Exp
Filter
FormatCurrency
FormatNumber
FormatPercent
GetLocale
GetRef
Hex
Hour
InStr
InStrRev
Int, Fixs
IsDate
IsEmpty
IsNull
IsObject
Join
LBound
Left
Len
LoadPicture
LTrim; RTrim; and Trims Maths
Mid
Month
MonthName
MsgBox
Oct
Replace
RGB
Rnd
Round
ScriptEngine
ScriptEngineMajorVersion ScriptEngineMinorVersion Second
Sgn
Sin
Space
Sqr
StrComp
String
Time
Timer
TimeSerial
TypeName
UBound
UCase
Weekday
WeekdayName
Year

Related Sections
VBScript Langauge Reference

2001 Microsoft Corporation. All rights reserved.


Build: Topic Version 5.6.9309.1546
Visual Basic Scripting Edition

Abs Function
Returns the absolute value of a number.
Abs(number)

The number argument can be any valid numeric expression. If number contains Null, Null is returned; if it is an uninitialized variable, zero is returned.
Remarks
The absolute value of a number is its unsigned magnitude. For example, Abs(-1) and Abs(1) both return 1.
The following example uses the Abs function to compute the absolute value of a number:
Dim MyNumber
MyNumber = Abs(50.3) ' Returns 50.3.
MyNumber = Abs(-50.3) ' Returns 50.3.

Requirements
Version 1
See Also
Sgn Function

2001 Microsoft Corporation. All rights reserved.


Build: Topic Version 5.6.9309.1546
Visual Basic Scripting Edition

Array Function

Returns a Variant containing an array.


Array(arglist)

The required arglist argument is a comma-delimited list of values that are assigned to the elements of an array contained with the Variant. If no arguments are specified, an array of zero length is created.
Remarks
The notation used to refer to an element of an array consists of the variable name followed by parentheses containing an index number indicating the desired element. In the following example, the first statement creates a
variable named A. The second statement assigns an array to variable A. The last statement assigns the value contained in the second array element to another variable.
Dim A
A = Array(10,20,30)
B = A(2)
' B is now 30.

Note A variable that is not declared as an array can still contain an array. Although a Variant variable containing an array is conceptually different from an array variable containing Variant elements, the array
elements are accessed in the same way.
Requirements
Version 2
See Also
Dim Statement

2001 Microsoft Corporation. All rights reserved.


Build: Topic Version 5.6.9309.1546
Visual Basic Scripting Edition

Asc Function
Returns the ANSI character code corresponding to the first letter in a string.
Asc(string)

The string argument is any valid string expression. If the string contains no characters, a run-time error occurs.
Remarks
In the following example, Asc returns the ANSI character code of the first letter of each string:
Dim MyNumber
MyNumber = Asc("A")
MyNumber = Asc("a")
MyNumber = Asc("Apple")

' Returns 65.


' Returns 97.
' Returns 65.

Note The AscB function is used with byte data contained in a string. Instead of returning the character code for the first character, AscB returns the first byte. AscW is provided for 32-bit platforms that use Unicode
characters. It returns the Unicode (wide) character code, thereby avoiding the conversion from Unicode to ANSI.
Requirements
Version 1
See Also
Chr Function

2001 Microsoft Corporation. All rights reserved.


Build: Topic Version 5.6.9309.1546
Visual Basic Scripting Edition

Atn Function
Returns the arctangent of a number.
Atn(number)

The number argument can be any valid numeric expression.


Remarks
The Atn function takes the ratio of two sides of a right triangle (number) and returns the corresponding angle in radians. The ratio is the length of the side opposite the angle divided by the length of the side adjacent to the angle.
The range of the result is -pi /2 to pi/2 radians.
To convert degrees to radians, multiply degrees by pi/180. To convert radians to degrees, multiply radians by 180/pi.
The following example uses Atn to calculate the value of pi:
Dim pi
pi = 4 * Atn(1)

' Calculate the value of pi.

Note Atnis the inverse trigonometric function of Tan, which takes an angle as its argument and returns the ratio of two sides of a right triangle. Do not confuse Atn with the cotangent, which is the simple inverse
of a tangent (1/tangent).
Requirements
Version 1
See Also
Cos Function | Derived Math Functions | Sin Function | Tan Function

2001 Microsoft Corporation. All rights reserved.

Build: Topic Version 5.6.9309.1546


Visual Basic Scripting Edition

CBool Function
Returns an expression that has been converted to a Variant of subtype Boolean.
CBool(expression)

The expression argument is any valid expression.


Remarks
If expression is zero, False is returned; otherwise, True is returned. If expression can't be interpreted as a numeric value, a run-time error occurs.
The following example uses the CBool function to convert an expression to a Boolean. If the expression evaluates to a nonzero value, CBool returns True; otherwise, it returns False.
Dim A, B, Check
A = 5: B = 5
Check = CBool(A = B)
A = 0
Check = CBool(A)

'
'
'
'

Initialize variables.
Check contains True.
Define variable.
Check contains False.

Requirements
Version 1
See Also
CByte Function | CCur Function | CDate Function | CDbl Function | CInt Function | CLng Function | CSng Function | CStr Function

2001 Microsoft Corporation. All rights reserved.


Build: Topic Version 5.6.9309.1546
Visual Basic Scripting Edition

CByte Function
Returns an expression that has been converted to a Variant of subtype Byte.
CByte(expression)

The expression argument is any valid expression.


Remarks
In general, you can document your code using the subtype conversion functions to show that the result of some operation should be expressed as a particular data type rather than the default data type. For example, use CByte to
force byte arithmetic in cases where currency, single-precision, double-precision, or integer arithmetic normally would occur.
Use the CByte function to provide internationally aware conversions from any other data type to a Byte subtype. For example, different decimal separators are properly recognized depending on the locale setting of your system,
as are different thousand separators.
If expression lies outside the acceptable range for the byte subtype, an error occurs. The following example uses the CByte function to convert an expression to a byte:
Dim MyDouble, MyByte
MyDouble = 125.5678
MyByte = CByte(MyDouble)

' MyDouble is a Double.


' MyByte contains 126.

Requirements
Version 1
See Also
CBool Function | CCur Function | CDate Function | CDbl Function | CInt Function | CLng Function | CSng Function | CStr Function

2001 Microsoft Corporation. All rights reserved.


Build: Topic Version 5.6.9309.1546
Visual Basic Scripting Edition

CCur Function
Returns an expression that has been converted to a Variant of subtype Currency.
CCur(expression)

The expression argument is any valid expression.


Remarks
In general, you can document your code using the subtype conversion functions to show that the result of some operation should be expressed as a particular data type rather than the default data type. For example, use CCur to
force currency arithmetic in cases where integer arithmetic normally would occur.
You should use the CCur function to provide internationally aware conversions from any other data type to a Currency subtype. For example, different decimal separators and thousands separators are properly recognized
depending on the locale setting of your system.
The following example uses the CCur function to convert an expression to a Currency:
Dim MyDouble, MyCurr
MyDouble = 543.214588
MyCurr = CCur(MyDouble * 2)

Requirements
Version 1
See Also

' MyDouble is a Double.


' Convert result of MyDouble * 2 (1086.429176) to a Currency (1086.4292).

CBool Function | CByte Function | CDate Function | CDbl Function | CInt Function | CLng Function | CSng Function | CStr Function

2001 Microsoft Corporation. All rights reserved.


Build: Topic Version 5.6.9309.1546
Visual Basic Scripting Edition

CDate Function
Returns an expression that has been converted to a Variant of subtype Date.
CDate(date)

The date argument is any valid date expression.


Remarks
Use the IsDate function to determine if date can be converted to a date or time. CDate recognizes date literals and time literals as well as some numbers that fall within the range of acceptable dates. When converting a number
to a date, the whole number portion is converted to a date. Any fractional part of the number is converted to a time of day, starting at midnight.
CDate recognizes date formats according to the locale setting of your system. The correct order of day, month, and year may not be determined if it is provided in a format other than one of the recognized date settings. In
addition, a long date format is not recognized if it also contains the day-of-the-week string.
The following example uses the CDate function to convert a string to a date. In general, hard coding dates and times as strings (as shown in this example) is not recommended. Use date and time literals (such as #10/19/1962#,
#4:45:23 PM#) instead.
MyDate = "October 19, 1962"
MyShortDate = CDate(MyDate)
MyTime = "4:35:47 PM"
MyShortTime = CDate(MyTime)

'
'
'
'

Define date.
Convert to Date data type.
Define time.
Convert to Date data type.

Requirements
Version 1
See Also
IsDate Function

2001 Microsoft Corporation. All rights reserved.


Build: Topic Version 5.6.9309.1546
Visual Basic Scripting Edition

CDbl Function
Returns an expression that has been converted to a Variant of subtype Double.
CDbl(expression)

The expression argument is any valid expression.


Remarks
In general, you can document your code using the subtype conversion functions to show that the result of some operation should be expressed as a particular data type rather than the default data type. For example, use CDbl or
CSng to force double-precision or single-precision arithmetic in cases where currency or integer arithmetic normally would occur.
Use the CDbl function to provide internationally aware conversions from any other data type to a Double subtype. For example, different decimal separators and thousands separators are properly recognized depending on the
locale setting of your system.
This example uses the CDbl function to convert an expression to a Double.
Dim MyCurr, MyDouble
MyCurr = CCur(234.456784)
MyDouble = CDbl(MyCurr * 8.2 * 0.01)

' MyCurr is a Currency (234.4567).


' Convert result to a Double (19.2254576).

Requirements
Version 1
See Also
CBool Function | CByte Function | CCur Function | CDate Function | CInt Function | CLng Function | CSng Function | CStr Function

2001 Microsoft Corporation. All rights reserved.


Build: Topic Version 5.6.9309.1546
Visual Basic Scripting Edition

Chr Function
Returns the character associated with the specified ANSI character code.
Chr(charcode)

The charcode argument is a number that identifies a character.


Remarks
Numbers from 0 to 31 are the same as standard, nonprintable ASCII codes. For example, Chr(10) returns a linefeed character.
The following example uses the Chr function to return the character associated with the specified character code:
Dim MyChar
MyChar = Chr(65)

' Returns A.

MyChar = Chr(97)
MyChar = Chr(62)
MyChar = Chr(37)

' Returns a.
' Returns >.
' Returns %.

Note The ChrB function is used with byte data contained in a string. Instead of returning a character, which may be one or two bytes, ChrB always returns a single byte. ChrW is provided for 32-bit platforms that
use Unicode characters. Its argument is a Unicode (wide) character code, thereby avoiding the conversion from ANSI to Unicode.
Requirements
Version 1
See Also
Asc Function

2001 Microsoft Corporation. All rights reserved.


Build: Topic Version 5.6.9309.1546
Visual Basic Scripting Edition

CInt Function
Returns an expression that has been converted to a Variant of subtype Integer.
CInt(expression)

The expression argument is any valid expression.


Remarks
In general, you can document your code using the subtype conversion functions to show that the result of some operation should be expressed as a particular data type rather than the default data type. For example, use CInt or
CLng to force integer arithmetic in cases where currency, single-precision, or double-precision arithmetic normally would occur.
Use the CInt function to provide internationally aware conversions from any other data type to an Integer subtype. For example, different decimal separators are properly recognized depending on the locale setting of your
system, as are different thousand separators.
If expression lies outside the acceptable range for the Integer subtype, an error occurs.
The following example uses the CInt function to convert a value to an Integer:
Dim MyDouble, MyInt
MyDouble = 2345.5678
MyInt = CInt(MyDouble)

' MyDouble is a Double.


' MyInt contains 2346.

Note CIntdiffers from the Fix and Int functions, which truncate, rather than round, the fractional part of a number. When the fractional part is exactly 0.5, the CInt function always rounds it to the nearest even
number. For example, 0.5 rounds to 0, and 1.5 rounds to 2.
Requirements
Version 1
See Also
CBool Function | CByte Function | CCur Function | CDate Function | CDbl Function | CLng Function | CSng Function | CStr Function | Int, Fix Functions

2001 Microsoft Corporation. All rights reserved.


Build: Topic Version 5.6.9309.1546
Visual Basic Scripting Edition

CLng Function
Returns an expression that has been converted to a Variant of subtype Long.
CLng(expression)

The expression argument is any valid expression.


Remarks
In general, you can document your code using the subtype conversion functions to show that the result of some operation should be expressed as a particular data type rather than the default data type. For example, use CInt or
CLng to force integer arithmetic in cases where currency, single-precision, or double-precision arithmetic normally would occur.
Use the CLng function to provide internationally aware conversions from any other data type to a Long subtype. For example, different decimal separators are properly recognized depending on the locale setting of your system,
as are different thousand separators.
If expression lies outside the acceptable range for the Long subtype, an error occurs.
The following example uses the CLng function to convert a value to a Long:
Dim MyVal1, MyVal2, MyLong1, MyLong2
MyVal1 = 25427.45: MyVal2 = 25427.55
' MyVal1, MyVal2 are Doubles.
MyLong1 = CLng(MyVal1)
' MyLong1 contains 25427.
MyLong2 = CLng(MyVal2)
' MyLong2 contains 25428.

Note CLng
differs from the Fix and Int functions, which truncate, rather than round, the fractional part of a number. When the fractional part is exactly 0.5, the CLng function always rounds it to the nearest even
number. For example, 0.5 rounds to 0, and 1.5 rounds to 2.
Requirements
Version 1
See Also
CBool Function | CByte Function | CCur Function | CDate Function | CDbl Function | CInt Function | CSng Function | CStr Function | Int, Fix Functions

2001 Microsoft Corporation. All rights reserved.

Build: Topic Version 5.6.9309.1546


Visual Basic Scripting Edition

Conversion Functions
Asc Function
CBool Function
CByte Function
CCur Function
CDate Function
CDbl Function
Chr Function
CInt Function
CLng Function
CSng Function
CStr Function
Hex Function
Oct Function

2001 Microsoft Corporation. All rights reserved.


Build: Topic Version 5.6.9309.1546
Visual Basic Scripting Edition

Cos Function
Returns the cosine of an angle.
Cos(number)

The number argument can be any valid numeric expression that expresses an angle in radians.
Remarks
The Cos function takes an angle and returns the ratio of two sides of a right triangle. The ratio is the length of the side adjacent to the angle divided by the length of the hypotenuse. The result lies in the range -1 to 1.
To convert degrees to radians, multiply degrees by pi /180. To convert radians to degrees, multiply radians by 180/pi.
The following example uses the Cos function to return the cosine of an angle:
Dim MyAngle, MySecant
MyAngle = 1.3
MySecant = 1 / Cos(MyAngle)

' Define angle in radians.


' Calculate secant.

Requirements
Version 1
See Also
Atn Function | Derived Math Functions | Sin Function | Tan Function

2001 Microsoft Corporation. All rights reserved.


Build: Topic Version 5.6.9309.1546
Visual Basic Scripting Edition

CreateObject Function
Creates and returns a reference to an Automation object.
CreateObject(servername.typename [, location])

Arguments
servername
Required. The name of the application providing the object.
typename
Required. The type or class of the object to create.
location
Optional. The name of the network server where the object is to be created.
Remarks
Automation servers provide at least one type of object. For example, a word-processing application may provide an application object, a document object, and a toolbar object.
To create an Automation object, assign the object returned by CreateObject to an object variable:
Dim ExcelSheet
Set ExcelSheet = CreateObject("Excel.Sheet")

This code starts the application that creates the object (in this case, a Microsoft Excel spreadsheet). Once an object is created, refer to it in code using the object variable you defined. As shown in the following example, you can
access properties and methods of the new object using the object variable, ExcelSheet, and other Excel objects, including the Application object and the ActiveSheet.Cells collection:
' Make Excel visible through the Application object.

ExcelSheet.Application.Visible = True
' Place some text in the first cell of the sheet.
ExcelSheet.ActiveSheet.Cells(1,1).Value = "This is column A, row 1"
' Save the sheet.
ExcelSheet.SaveAs "C:\DOCS\TEST.XLS"
' Close Excel with the Quit method on the Application object.
ExcelSheet.Application.Quit
' Release the object variable.
Set ExcelSheet = Nothing

Creating an object on a remote server can only be accomplished when Internet security is turned off. You can create an object on a remote networked computer by passing the name of the computer to the servername argument of
CreateObject. That name is the same as the machine name portion of a share name. For a network share named "\\myserver\public", the servername is "myserver". In addition, you can specify servername using DNS format or
an IP address.
The following code returns the version number of an instance of Excel running on a remote network computer named "myserver":
Function GetVersion
Dim XLApp
Set XLApp = CreateObject("Excel.Application", "MyServer")
GetVersion = XLApp.Version
End Function

An error occurs if the specified remote server does not exist or cannot be found.
Requirements
Version 2
See Also
GetObject Function

2001 Microsoft Corporation. All rights reserved.


Build: Topic Version 5.6.9309.1546
Visual Basic Scripting Edition

CSng Function
Returns an expression that has been converted to a Variant of subtype Single.
CSng(expression)

The expression argument is any valid expression.


Remarks
In general, you can document your code using the data type conversion functions to show that the result of some operation should be expressed as a particular data type rather than the default data type. For example, use CDbl or
CSng to force double-precision or single-precision arithmetic in cases where currency or integer arithmetic normally would occur.
Use the CSng function to provide internationally aware conversions from any other data type to a Single subtype. For example, different decimal separators are properly recognized depending on the locale setting of your
system, as are different thousand separators.
If expression lies outside the acceptable range for the Single subtype, an error occurs.
The following example uses the CSng function to convert a value to a Single:
Dim MyDouble1, MyDouble2, MySingle1, MySingle2
' MyDouble1, MyDouble2 are Doubles.
MyDouble1 = 75.3421115: MyDouble2 = 75.3421555
MySingle1 = CSng(MyDouble1)
' MySingle1 contains 75.34211.
MySingle2 = CSng(MyDouble2)
' MySingle2 contains 75.34216.

Requirements
Version 1
See Also
CBool Function | CByte Function | CCur Function | CDate Function | CDbl Function | CInt Function | CLng Function | CStr Function

2001 Microsoft Corporation. All rights reserved.


Build: Topic Version 5.6.9309.1546
Visual Basic Scripting Edition

CStr Function
Returns an expression that has been converted to a Variant of subtype String.
CStr(expression)

The expression argument is any valid expression.


Remarks
In general, you can document your code using the data type conversion functions to show that the result of some operation should be expressed as a particular data type rather than the default data type. For example, use CStr to
force the result to be expressed as a String.
You should use the CStr function instead of Str to provide internationally aware conversions from any other data type to a String subtype. For example, different decimal separators are properly recognized depending on the
locale setting of your system.
The data in expression determines what is returned according to the following table:
If expression is
Boolean
Date
Null
Empty
Error
Other numeric

CStr returns
A String containing True or False.
A String containing a date in the short-date format of your system.
A run-time error.
A zero-length String ("").
A String containing the word Error followed by the error number.
A String containing the number.

The following example uses the CStr function to convert a numeric value to a String:
Dim MyDouble, MyString
MyDouble = 437.324
MyString = CStr(MyDouble)

' MyDouble is a Double.


' MyString contains "437.324".

Requirements
Version 1
See Also
CBool Function | CByte Function | CCur Function | CDate Function | CDbl Function | CInt Function | CLng Function | CSng Function

2001 Microsoft Corporation. All rights reserved.


Build: Topic Version 5.6.9309.1546
Visual Basic Scripting Edition

Date Function
Returns the current system date.
Date

Remarks
The following example uses the Date function to return the current system date:
Dim MyDate
MyDate = Date

' MyDate contains the current system date.

Requirements
Version 1
See Also
CDate Function | Now Function | Time Function

2001 Microsoft Corporation. All rights reserved.


Build: Topic Version 5.6.9309.1546
Visual Basic Scripting Edition

DateAdd Function
Returns a date to which a specified time interval has been added.
DateAdd(interval, number, date)

Arguments
interval
Required. String expression that is the interval you want to add. See Settings section for values.
number
Required. Numeric expression that is the number of interval you want to add. The numeric expression can either be positive, for dates in the future, or negative, for dates in the past.
date
Required. Variant or literal representing the date to which interval is added.
Settings
The interval argument can have the following values:
Setting
Description
yyyy Year
q
Quarter
m
Month
y
Day of year
d
Day
w
Weekday
ww
Week of year
h
Hour
n
Minute
s
Second
Remarks
You can use the DateAdd function to add or subtract a specified time interval from a date. For example, you can use DateAdd to calculate a date 30 days from today or a time 45 minutes from now. To add days to date, you can
use Day of Year ("y"), Day ("d"), or Weekday ("w").
The DateAdd function won't return an invalid date. The following example adds one month to January 31:
NewDate = DateAdd("m", 1, "31-Jan-95")

In this case, DateAdd returns 28-Feb-95, not 31-Feb-95. If date is 31-Jan-96, it returns 29-Feb-96 because 1996 is a leap year.
If the calculated date would precede the year 100, an error occurs.
If number isn't a Long value, it is rounded to the nearest whole number before being evaluated.
Requirements
Version 2
See Also
DateDiff Function | DatePart Function

2001 Microsoft Corporation. All rights reserved.


Build: Topic Version 5.6.9309.1546
Visual Basic Scripting Edition

DateDiff Function
Returns the number of intervals between two dates.
DateDiff(interval, date1, date2 [,firstdayofweek[, firstweekofyear]])

The DateDiff function syntax has these parts:


Arguments
interval
Required. String expression that is the interval you want to use to calculate the differences between date1 and date2. See Settings section for values.
date1, date2
Required. Date expressions. Two dates you want to use in the calculation.
firstdayofweek
Optional. Constant that specifies the day of the week. If not specified, Sunday is assumed. See Settings section for values.
firstweekofyear
Optional. Constant that specifies the first week of the year. If not specified, the first week is assumed to be the week in which January 1 occurs. See Settings section for values.
Settings
The interval argument can have the following values:
Setting
Description
yyyy Year
q
Quarter
m
Month
y
Day of year
d
Day
w
Weekday
ww
Week of year
h
Hour
n
Minute
s
Second
The firstdayofweek argument can have the following values:
Constant
Value
vbUseSystemDayOfWeek 0
vbSunday
1
vbMonday
2
vbTuesday
3
vbWednesday
4
vbThursday
5
vbFriday
6
vbSaturday
7

Description
Use National Language Support (NLS) API setting.
Sunday (default)
Monday
Tuesday
Wednesday
Thursday
Friday
Saturday

The firstweekofyear argument can have the following values:


Constant
vbUseSystem
vbFirstJan1
vbFirstFourDays
vbFirstFullWeek

Value
0
1
2
3

Description
Use National Language Support (NLS) API setting.
Start with the week in which January 1 occurs (default).
Start with the week that has at least four days in the new year.
Start with the first full week of the new year.

Remarks
You can use the DateDiff function to determine how many specified time intervals exist between two dates. For example, you might use DateDiff to calculate the number of days between two dates, or the number of weeks
between today and the end of the year.
To calculate the number of days between date1 and date2, you can use either Day of year ("y") or Day ("d"). When interval is Weekday ("w"), DateDiff returns the number of weeks between the two dates. If date1 falls on a
Monday, DateDiff counts the number of Mondays until date2. It counts date2 but not date1. If interval is Week ("ww"), however, the DateDiff function returns the number of calendar weeks between the two dates. It counts the
number of Sundays between date1 and date2. DateDiff counts date2 if it falls on a Sunday; but it doesn't count date1, even if it does fall on a Sunday.
If date1 refers to a later point in time than date2, the DateDiff function returns a negative number.
The firstdayofweek argument affects calculations that use the "w" and "ww" interval symbols.
If date1 or date2 is a date literal, the specified year becomes a permanent part of that date. However, if date1 or date2 is enclosed in quotation marks (" ") and you omit the year, the current year is inserted in your code each time
the date1 or date2 expression is evaluated. This makes it possible to write code that can be used in different years.
When comparing December 31 to January 1 of the immediately succeeding year, DateDiff for Year ("yyyy") returns 1 even though only a day has elapsed.
The following example uses the DateDiff function to display the number of days between a given date and today:
Function DiffADate(theDate)
DiffADate = "Days from today: " & DateDiff("d", Now, theDate)
End Function

Requirements
Version 2
See Also
DateAdd Function | DatePart Function

2001 Microsoft Corporation. All rights reserved.


Build: Topic Version 5.6.9309.1546
Visual Basic Scripting Edition

DatePart Function
Returns the specified part of a given date.
DatePart(interval, date[, firstdayofweek[, firstweekofyear]])

Arguments
interval
Required. String expression that is the interval of time you want to return. See Settings section for values.
date
Required. Date expression you want to evaluate.
firstdayof week
Optional. Constant that specifies the day of the week. If not specified, Sunday is assumed. See Settings section for values.
firstweekofyear
Optional. Constant that specifies the first week of the year. If not specified, the first week is assumed to be the week in which January 1 occurs. See Settings section for values.
Settings
The interval argument can have the following values:
Setting
Description
yyyy Year
q
Quarter
m
Month
y
Day of year
d
Day
w
Weekday
ww
Week of year
h
Hour
n
Minute
s
Second
The firstdayofweek argument can have the following values:
Constant
Value
vbUseSystemDayOfWeek 0
vbSunday
1
vbMonday
2
vbTuesday
3
vbWednesday
4
vbThursday
5
vbFriday
6
vbSaturday
7

Description
Use National Language Support (NLS) API setting.
Sunday (default)
Monday
Tuesday
Wednesday
Thursday
Friday
Saturday

The firstweekofyear argument can have the following values:


Constant
vbUseSystem
vbFirstJan1
vbFirstFourDays
vbFirstFullWeek

Value
0
1
2
3

Description
Use National Language Support (NLS) API setting.
Start with the week in which January 1 occurs (default).
Start with the week that has at least four days in the new year.
Start with the first full week of the new year.

Remarks
You can use the DatePart function to evaluate a date and return a specific interval of time. For example, you might use DatePart to calculate the day of the week or the current hour.
The firstdayofweek argument affects calculations that use the "w" and "ww" interval symbols.
If date is a date literal, the specified year becomes a permanent part of that date. However, if date is enclosed in quotation marks (" "), and you omit the year, the current year is inserted in your code each time the date expression
is evaluated. This makes it possible to write code that can be used in different years.
This example takes a date and, using the DatePart function, displays the quarter of the year in which it occurs.
Function GetQuarter(TheDate)
GetQuarter = DatePart("q", TheDate)
End Function

Requirements
Version 2
See Also
DateAdd Function | DateDiff Function

2001 Microsoft Corporation. All rights reserved.


Build: Topic Version 5.6.9309.1546
Visual Basic Scripting Edition

DateSerial Function
Returns a Variant of subtype Date for a specified year, month, and day.
DateSerial(year, month, day)

Arguments
year
Number between 100 and 9999, inclusive, or a numeric expression.
month
Any numeric expression.
day
Any numeric expression.
Remarks
To specify a date, such as December 31, 1991, the range of numbers for each DateSerial argument should be in the accepted range for the unit; that is, 131 for days and 112 for months. However, you can also specify relative
dates for each argument using any numeric expression that represents some number of days, months, or years before or after a certain date.

The following example uses numeric expressions instead of absolute date numbers. Here the DateSerial function returns a date that is the day before the first day (1 1) of two months before August (8 2) of 10 years before
1990 (1990 10); in other words, May 31, 1980.
Dim MyDate1, MyDate2
MyDate1 = DateSerial(1970, 1, 1)
' Returns January 1, 1970.
MyDate2 = DateSerial(1990 - 10, 8 - 2, 1 - 1)
' Returns May 31, 1980.

For the year argument, values between 0 and 99, inclusive, are interpreted as the years 19001999. For all other year arguments, use a complete four-digit year (for example, 1800).
When any argument exceeds the accepted range for that argument, it increments to the next larger unit as appropriate. For example, if you specify 35 days, it is evaluated as one month and some number of days, depending on
where in the year it is applied. However, if any single argument is outside the range -32,768 to 32,767, or if the date specified by the three arguments, either directly or by expression, falls outside the acceptable range of dates, an
error occurs.
Requirements
Version 1
See Also
Date Function | DateValue Function | Day Function | Month Function | Now Function | TimeSerial Function | TimeValue Function | Weekday Function | Year Function

2001 Microsoft Corporation. All rights reserved.


Build: Topic Version 5.6.9309.1546
Visual Basic Scripting Edition

DateValue Function
Returns a Variant of subtype Date.
DateValue(date)

The date argument is normally a string expression representing a date from January 1, 100 through December 31, 9999. However, date can also be any expression that can represent a date, a time, or both a date and time, in that
range.
Remarks
If the date argument includes time information, DateValue doesn't return it. However, if date includes invalid time information (such as "89:98"), an error occurs.
If date is a string that includes only numbers separated by valid date separators, DateValue recognizes the order for month, day, and year according to the short date format you specified for your system. DateValue also
recognizes unambiguous dates that contain month names, either in long or abbreviated form. For example, in addition to recognizing 12/30/1991 and 12/30/91, DateValue also recognizes December 30, 1991 and Dec 30, 1991.
If the year part of date is omitted, DateValue uses the current year from your computer's system date.
The following example uses the DateValue function to convert a string to a date. You can also use date literals to directly assign a date to a Variant variable, for example, MyDate = #9/11/63#.
Dim MyDate
MyDate = DateValue("September 11, 1963")

' Return a date.

Requirements
Version 1
See Also
CDate Function | DateSerial Function | Day Function | Month Function | Now Function | TimeSerial Function | TimeValue Function | Weekday Function | Year Function

2001 Microsoft Corporation. All rights reserved.


Build: Topic Version 5.6.9309.1546
Visual Basic Scripting Edition

Day Function
Returns a whole number between 1 and 31, inclusive, representing the day of the month.
Day(date)

The date argument is any expression that can represent a date. If date contains Null, Null is returned.
The following example uses the Day function to obtain the day of the month from a specified date:
Dim MyDay
MyDay = Day("October 19, 1962")

' MyDay contains 19.

Requirements
Version 1
See Also
Date Function | Hour Function | Minute Function | Month Function | Now Function | Second Function | Weekday Function | Year Function

2001 Microsoft Corporation. All rights reserved.


Build: Topic Version 5.6.9309.1546
Visual Basic Scripting Edition

Derived Math Functions


The following non-intrinsic math functions can be derived from the intrinsic math functions:
Function
Secant

Derived equivalents
Sec(X) = 1 / Cos(X)

Cosecant
Cotangent
Inverse Sine
Inverse Cosine
Inverse Secant
Inverse Cosecant
Inverse Cotangent
Hyperbolic Sine
Hyperbolic Cosine
Hyperbolic Tangent
Hyperbolic Secant
Hyperbolic Cosecant
Hyperbolic Cotangent
Inverse Hyperbolic Sine
Inverse Hyperbolic Cosine
Inverse Hyperbolic Tangent
Inverse Hyperbolic Secant
Inverse Hyperbolic Cosecant
Inverse Hyperbolic Cotangent
Logarithm to base N

Cosec(X) = 1 / Sin(X)
Cotan(X) = 1 / Tan(X)
Arcsin(X) = Atn(X / Sqr(-X * X + 1))
Arccos(X) = Atn(-X / Sqr(-X * X + 1)) + 2 * Atn(1)
Arcsec(X) = Atn(X / Sqr(X * X - 1)) + Sgn((X) -1) * (2 * Atn(1))
Arccosec(X) = Atn(X / Sqr(X * X - 1)) + (Sgn(X) - 1) * (2 * Atn(1))
Arccotan(X) = Atn(X) + 2 * Atn(1)
HSin(X) = (Exp(X) - Exp(-X)) / 2
HCos(X) = (Exp(X) + Exp(-X)) / 2
HTan(X) = (Exp(X) - Exp(-X)) / (Exp(X) + Exp(-X))
HSec(X) = 2 / (Exp(X) + Exp(-X))
HCosec(X) = 2 / (Exp(X) - Exp(-X))
HCotan(X) = (Exp(X) + Exp(-X)) / (Exp(X) - Exp(-X))
HArcsin(X) = Log(X + Sqr(X * X + 1))
HArccos(X) = Log(X + Sqr(X * X - 1))
HArctan(X) = Log((1 + X) / (1 - X)) / 2
HArcsec(X) = Log((Sqr(-X * X + 1) + 1) / X)
HArccosec(X) = Log((Sgn(X) * Sqr(X * X + 1) +1) / X)
HArccotan(X) = Log((X + 1) / (X - 1)) / 2
LogN(X) = Log(X) / Log(N)

See Also
Atn Function | Cos Function | Exp Function | Log Function | Sin Function | Sqr Function | Tan Function

2001 Microsoft Corporation. All rights reserved.


Build: Topic Version 5.6.9309.1546
Visual Basic Scripting Edition

Eval
Evaluates an expression and returns the result.
[result = ]Eval(expression)

Arguments
result
Optional. Variable to which return value assignment is made. If result is not specified, consider using the Execute statement instead.
expression
Required. String containing any legal VBScript expression.
Remarks
In VBScript, x = y can be interpreted two ways. The first is as an assignment statement, where the value of y is assigned to x. The second interpretation is as an expression that tests if x and y have the same value. If they do,
result is True; if they are not, result is False. The Eval method always uses the second interpretation, whereas the Execute statement always uses the first.
Note In Microsoft JScript, no confusion exists between assignment and comparison, because the assignment operator (=) is different from the comparison operator (==).
The following example illustrates the use of the Eval function:
Sub GuessANumber
Dim Guess, RndNum
RndNum = Int((100) * Rnd(1) + 1)
Guess = CInt(InputBox("Enter your guess:",,0))
Do
If Eval("Guess = RndNum") Then
MsgBox "Congratulations! You guessed it!"
Exit Sub
Else
Guess = CInt(InputBox("Sorry! Try again.",,0))
End If
Loop Until Guess = 0
End Sub

Requirements
Version 5
See Also
Execute Statement

2001 Microsoft Corporation. All rights reserved.


Build: Topic Version 5.6.9309.1546
Visual Basic Scripting Edition

Exp Function
Returns e (the base of natural logarithms) raised to a power.
Exp(number)

The number argument can be any valid numeric expression.


Remarks
If the value of number exceeds 709.782712893, an error occurs. The constant e is approximately 2.718282.
Note The Exp function complements the action of the Log function and is sometimes referred to as the antilogarithm.
The following example uses the Exp function to return e raised to a power:
Dim MyAngle, MyHSin
' Define angle in radians.
MyAngle = 1.3
' Calculate hyperbolic sine.
MyHSin = (Exp(MyAngle) - Exp(-1 * MyAngle)) / 2

Requirements
Version 1
See Also
Derived Math Functions | Log Function

2001 Microsoft Corporation. All rights reserved.


Build: Topic Version 5.6.9309.1546
Visual Basic Scripting Edition

Filter Function
Returns a zero-based array containing a subset of a string array based on a specified filter criteria.
Filter(InputStrings, Value[, Include[, Compare]])

Arguments
InputStrings
Required. One-dimensional array of strings to be searched.
Value
Required. String to search for.
Include
Optional. Boolean value indicating whether to return substrings that include or exclude Value. If Include is True, Filter returns the subset of the array that contains Value as a substring. If Include is False, Filter returns
the subset of the array that does not contain Value as a substring.
Compare
Optional. Numeric value indicating the kind of string comparison to use. See Settings section for values.
Settings
The Compare argument can have the following values:
Constant
Value
Description
vbBinaryCompare 0
Perform a binary comparison.
vbTextCompare 1
Perform a textual comparison.
Remarks
If no matches of Value are found within InputStrings, Filter returns an empty array. An error occurs if InputStrings is Null or is not a one-dimensional array.
The array returned by the Filter function contains only enough elements to contain the number of matched items.
The following example uses the Filter function to return the array containing the search criteria "Mon":
Dim MyIndex
Dim MyArray (3)
MyArray(0) = "Sunday"
MyArray(1) = "Monday"
MyArray(2) = "Tuesday"
MyIndex = Filter(MyArray, "Mon") ' MyIndex(0) contains "Monday".

Requirements
Version 2
See Also
Replace Function

2001 Microsoft Corporation. All rights reserved.


Build: Topic Version 5.6.9309.1546
Visual Basic Scripting Edition

FormatCurrency Function
Returns an expression formatted as a currency value using the currency symbol defined in the system control panel.
FormatCurrency(Expression[,NumDigitsAfterDecimal [,IncludeLeadingDigit [,UseParensForNegativeNumbers [,GroupDigits]]]])

Arguments
Expression
Required. Expression to be formatted.
NumDigitsAfterDecimal
Optional. Numeric value indicating how many places to the right of the decimal are displayed. Default value is -1, which indicates that the computer's regional settings are used.
IncludeLeadingDigit
Optional. Tristate constant that indicates whether or not a leading zero is displayed for fractional values. See Settings section for values.
UseParensForNegativeNumbers
Optional. Tristate constant that indicates whether or not to place negative values within parentheses. See Settings section for values.
GroupDigits
Optional. Tristate constant that indicates whether or not numbers are grouped using the group delimiter specified in the computer's regional settings. See Settings section for values.
Settings
The IncludeLeadingDigit, UseParensForNegativeNumbers, and GroupDigits arguments have the following settings:
Constant
TristateTrue
TristateFalse
TristateUseDefault

Value
-1
0
-2

Description
True
False
Use the setting from the computer's regional settings.

Remarks
When one or more optional arguments are omitted, values for omitted arguments are provided by the computer's regional settings. The position of the currency symbol relative to the currency value is determined by the system's
regional settings.

Note All settings information comes from the Regional Settings Currency tab, except leading zero, which comes from the Number tab.
The following example uses the FormatCurrency function to format the expression as a currency and assign it to MyCurrency:
Dim MyCurrency
MyCurrency = FormatCurrency(1000)

' MyCurrency contains $1000.00.

Requirements
Version 2
See Also
FormatDateTime Function | FormatNumber Function | FormatPercent Function

2001 Microsoft Corporation. All rights reserved.


Build: Topic Version 5.6.9309.1546
Visual Basic Scripting Edition

FormatDateTime Function
Returns an expression formatted as a date or time.
FormatDateTime(Date[, NamedFormat])

Arguments
Date
Required. Date expression to be formatted.
NamedFormat
Optional. Numeric value that indicates the date/time format used. If omitted, vbGeneralDate is used.
Settings
The NamedFormat argument has the following settings:
Constant

Value

vbGeneralDate

vbLongDate
vbShortDate
vbLongTime
vbShortTime

1
2
3
4

Description
Display a date and/or time. If there is a date part, display it as a short date. If there is a time part, display it as a long time. If present, both parts
are displayed.
Display a date using the long date format specified in your computer's regional settings.
Display a date using the short date format specified in your computer's regional settings.
Display a time using the time format specified in your computer's regional settings.
Display a time using the 24-hour format (hh:mm).

Remarks
The following example uses the FormatDateTime function to format the expression as a long date and assign it to MyDateTime:
Function GetCurrentDate
' FormatDateTime formats Date in long date.
GetCurrentDate = FormatDateTime(Date, 1)
End Function

Requirements
Version 2
See Also
FormatCurrency Function | FormatNumber Function | FormatPercent Function

2001 Microsoft Corporation. All rights reserved.


Build: Topic Version 5.6.9309.1546
Visual Basic Scripting Edition

FormatNumber Function
Returns an expression formatted as a number.
FormatNumber(Expression [,NumDigitsAfterDecimal [,IncludeLeadingDigit [,UseParensForNegativeNumbers [,GroupDigits]]]])

Arguments
Expression
Required. Expression to be formatted.
NumDigitsAfterDecimal
Optional. Numeric value indicating how many places to the right of the decimal are displayed. Default value is -1, which indicates that the computer's regional settings are used.
IncludeLeadingDigit
Optional. Tristate constant that indicates whether or not a leading zero is displayed for fractional values. See Settings section for values.
UseParensForNegativeNumbers
Optional. Tristate constant that indicates whether or not to place negative values within parentheses. See Settings section for values.
GroupDigits
Optional. Tristate constant that indicates whether or not numbers are grouped using the group delimiter specified in the control panel. See Settings section for values.
Settings
The IncludeLeadingDigit, UseParensForNegativeNumbers, and GroupDigits arguments have the following settings:
Constant
TristateTrue
TristateFalse
TristateUseDefault

Value
-1
0
-2

Description
True
False
Use the setting from the computer's regional settings.

Remarks
When one or more of the optional arguments are omitted, the values for omitted arguments are provided by the computer's regional settings.

Note All settings information comes from the Regional Settings Number tab.
The following example uses the FormatNumber function to format a number to have four decimal places:
Function FormatNumberDemo
Dim MyAngle, MySecant, MyNumber
MyAngle = 1.3
' Define angle in radians.
MySecant = 1 / Cos(MyAngle)
' Calculate secant.
FormatNumberDemo = FormatNumber(MySecant,4) ' Format MySecant to four decimal places.
End Function

Requirements
Version 2
See Also
FormatCurrency Function | FormatDateTime Function | FormatPercent Function

2001 Microsoft Corporation. All rights reserved.


Build: Topic Version 5.6.9309.1546
Visual Basic Scripting Edition

FormatPercent Function
Returns an expression formatted as a percentage (multiplied by 100) with a trailing % character.
FormatPercent(Expression[,NumDigitsAfterDecimal [,IncludeLeadingDigit [,UseParensForNegativeNumbers [,GroupDigits]]]])

The FormatPercent function syntax has these parts:


Arguments
Expression
Required. Expression to be formatted.
NumDigitsAfterDecimal
Optional. Numeric value indicating how many places to the right of the decimal are displayed. Default value is -1, which indicates that the computer's regional settings are used.
IncludeLeadingDigit
Optional. Tristate constant that indicates whether or not a leading zero is displayed for fractional values. See Settings section for values.
UseParensForNegativeNumbers
Optional. Tristate constant that indicates whether or not to place negative values within parentheses. See Settings section for values.
GroupDigits
Optional. Tristate constant that indicates whether or not numbers are grouped using the group delimiter specified in the control panel. See Settings section for values.
Settings
The IncludeLeadingDigit, UseParensForNegativeNumbers, and GroupDigits arguments have the following settings:
Constant
TristateTrue
TristateFalse
TristateUseDefault

Value
-1
0
-2

Description
True
False
Use the setting from the computer's regional settings.

Remarks
When one or more optional arguments are omitted, the values for the omitted arguments are provided by the computer's regional settings.
Note All settings information comes from the Regional Settings Number tab.
The following example uses the FormatPercent function to format an expression as a percent:
Dim MyPercent
MyPercent = FormatPercent(2/32) ' MyPercent contains 6.25%.

Requirements
Version 2
See Also
FormatCurrency Function | FormatDateTime Function | FormatNumber Function

2001 Microsoft Corporation. All rights reserved.


Build: Topic Version 5.6.9309.1546
Visual Basic Scripting Edition

GetLocale Function
Returns the current locale ID value.
GetLocale()

Remarks
A locale is a set of user preference information related to the user's language, country/region, and cultural conventions. The locale determines such things as keyboard layout, alphabetic sort order, as well as date, time, number,
and currency formats.
The return value can be any of the 32-bit values shown in the Locale ID chart:
The following example illustrates the use of the GetLocale function. To use this code, paste the entire example between the <BODY> tags of a standard HTML page.
Enter Date in UK format: <input type="text" id="UKDate" size="20"><p>
Here's the US equivalent: <input type="text" id="USdate" size="20"><p>
<input type="button" value="Convert" id="button1"><p>
Enter a price in German: &nbsp; <input type="text" id="GermanNumber" size="20">
<p>
Here's the UK equivalent: <input type="text" id="USNumber" size="20"><p>
<input type="button" value="Convert" id="button2"><p>

<script language="vbscript">
Dim currentLocale
' Get the current locale
currentLocale = GetLocale
Sub Button1_onclick
Dim original
original = SetLocale("en-gb")
mydate = CDate(UKDate.value)
' IE always sets the locale to US English so use the
' currentLocale variable to set the locale to US English
original = SetLocale(currentLocale)
USDate.value = FormatDateTime(mydate,vbShortDate)
End Sub
Sub button2_onclick
Dim original
original = SetLocale("de")
myvalue = CCur(GermanNumber.value)
original = SetLocale("en-gb")
USNumber.value = FormatCurrency(myvalue)
End Sub
</script>

See Also
SetLocale Function | Locale ID (LCID) Chart

2001 Microsoft Corporation. All rights reserved.


Build: Topic Version 5.6.9309.1546
Visual Basic Scripting Edition

GetObject Function
Returns a reference to an Automation object from a file.
GetObject([pathname] [, class])

Arguments
pathname
Optional; String. Full path and name of the file containing the object to retrieve. If pathname is omitted, class is required.
class
Optional; String. Class of the object.
The class argument uses the syntax appname.objectype and has these parts:
Arguments
appname
Required; String. Name of the application providing the object.
objectype
Required; String. Type or class of object to create.
Remarks
Use the GetObject function to access an Automation object from a file and assign the object to an object variable. Use the Set statement to assign the object returned by GetObject to the object variable. For example:
Dim CADObject
Set CADObject = GetObject("C:\CAD\SCHEMA.CAD")

When this code is executed, the application associated with the specified pathname is started and the object in the specified file is activated. If pathname is a zero-length string (""), GetObject returns a new object instance of the
specified type. If the pathname argument is omitted, GetObject returns a currently active object of the specified type. If no object of the specified type exists, an error occurs.
Some applications allow you to activate part of a file. Add an exclamation point (!) to the end of the file name and follow it with a string that identifies the part of the file you want to activate. For information on how to create
this string, see the documentation for the application that created the object.
For example, in a drawing application you might have multiple layers to a drawing stored in a file. You could use the following code to activate a layer within a drawing called SCHEMA.CAD :
Set LayerObject = GetObject("C:\CAD\SCHEMA.CAD!Layer3")

If you don't specify the object's class, Automation determines the application to start and the object to activate, based on the file name you provide. Some files, however, may support more than one class of object. For example, a
drawing might support three different types of objects: an Application object, a Drawing object, and a Toolbar object, all of which are part of the same file. To specify which object in a file you want to activate, use the optional
class argument. For example:
Dim MyObject
Set MyObject = GetObject("C:\DRAWINGS\SAMPLE.DRW", "FIGMENT.DRAWING")

In the preceding example, FIGMENT is the name of a drawing application and DRAWING is one of the object types it supports. Once an object is activated, you reference it in code using the object variable you defined. In the
preceding example, you access properties and methods of the new object using the object variable MyObject. For example:
MyObject.Line 9, 90
MyObject.InsertText 9, 100, "Hello, world."
MyObject.SaveAs "C:\DRAWINGS\SAMPLE.DRW"

Note Use the GetObject function when there is a current instance of the object or if you want to create the object with a file already loaded. If there is no current instance, and you don't want the object started with
a file loaded, use the CreateObject function.
If an object has registered itself as a single-instance object, only one instance of the object is created, no matter how many times CreateObject is executed. With a single-instance object, GetObject always returns the same
instance when called with the zero-length string ("") syntax, and it causes an error if the pathname argument is omitted.
Requirements
Version 5
See Also
CreateObject Function

2001 Microsoft Corporation. All rights reserved.


Build: Topic Version 5.6.9309.1546
Visual Basic Scripting Edition

GetRef Function
Returns a reference to a procedure that can be bound to an event.
Set object.eventname = GetRef(procname)

Arguments
object
Required. Name of the object with which event is associated.
event
Required. Name of the event to which the function is to be bound.
procname
Required. String containing the name of the Sub or Function procedure being associated with the event.
Remarks
The GetRef function allows you to connect a VBScript procedure (Function or Sub) to any available event on your DHTML (Dynamic HTML) pages. The DHTML object model provides information about what events are
available for its various objects.
In other scripting and programming languages, the functionality provided by GetRef is referred to as a function pointer, that is, it points to the address of a procedure to be executed when the specified event occurs.
The following example illustrates the use of the GetRef function.
<SCRIPT LANGUAGE="VBScript">
Function GetRefTest()
Dim Splash
Splash = "GetRefTest Version 1.0"
& vbCrLf
Splash = Splash & Chr(169) & " YourCompany 1999 "
MsgBox Splash
End Function
Set Window.Onload = GetRef("GetRefTest")
</SCRIPT>

Requirements
Version 5
See Also
Function Statement | Set Statement | Sub Statement

2001 Microsoft Corporation. All rights reserved.


Build: Topic Version 5.6.9309.1546
Visual Basic Scripting Edition

Hex Function
Returns a string representing the hexadecimal value of a number.
Hex(number)

The number argument is any valid expression.


Remarks
If number is not already a whole number, it is rounded to the nearest whole number before being evaluated.
If number is
Null
Empty
Any other number

Hex returns
Null.
Zero (0).
Up to eight hexadecimal characters.

You can represent hexadecimal numbers directly by preceding numbers in the proper range with &H. For example, &H10 represents decimal 16 in hexadecimal notation.
The following example uses the Hex function to return the hexadecimal value of a number:
Dim MyHex
MyHex = Hex(5)
' Returns 5.
MyHex = Hex(10)
' Returns A.
MyHex = Hex(459)
' Returns 1CB.

Requirements
Version 1
See Also
Oct Function

2001 Microsoft Corporation. All rights reserved.


Build: Topic Version 5.6.9309.1546
Visual Basic Scripting Edition

Hour Function
Returns a whole number between 0 and 23, inclusive, representing the hour of the day.
Hour(time)

The time argument is any expression that can represent a time. If time contains Null, Null is returned.
The following example uses the Hour function to obtain the hour from the current time:
Dim MyTime, MyHour
MyTime = Now

MyHour = Hour(MyTime) ' MyHour contains the number representing


' the current hour.

Requirements
Version 1
See Also
Day Function | Minute Function | Now Function | Second Function | Time Function

2001 Microsoft Corporation. All rights reserved.


Build: Topic Version 5.6.9309.1546
Visual Basic Scripting Edition

InputBox Function
Displays a prompt in a dialog box, waits for the user to input text or click a button, and returns the contents of the text box.
InputBox(prompt[, title][, default][, xpos][, ypos][, helpfile, context])

Arguments
prompt
String expression displayed as the message in the dialog box. The maximum length of prompt is approximately 1024 characters, depending on the width of the characters used. If prompt consists of more than one line, you
can separate the lines using a carriage return character (Chr(13)), a linefeed character (Chr(10)), or carriage returnlinefeed character combination (Chr(13) & Chr(10)) between each line.
title
String expression displayed in the title bar of the dialog box. If you omit title, the application name is placed in the title bar.
default
String expression displayed in the text box as the default response if no other input is provided. If you omit default, the text box is displayed empty.
xpos
Numeric expression that specifies, in twips, the horizontal distance of the left edge of the dialog box from the left edge of the screen. If xpos is omitted, the dialog box is horizontally centered.
ypos
Numeric expression that specifies, in twips, the vertical distance of the upper edge of the dialog box from the top of the screen. If ypos is omitted, the dialog box is vertically positioned approximately one-third of the way
down the screen.
helpfile
String expression that identifies the Help file to use to provide context-sensitive Help for the dialog box. If helpfile is provided, context must also be provided.
context
Numeric expression that identifies the Help context number assigned by the Help author to the appropriate Help topic. If context is provided, helpfile must also be provided.
Remarks
When both helpfile and context are supplied, a Help button is automatically added to the dialog box.
If the user clicks OK or presses ENTER, the InputBox function returns whatever is in the text box. If the user clicks Cancel, the function returns a zero-length string ("").
The following example uses the InputBox function to display an input box and assign the string to the variable Input:
Dim Input
Input = InputBox("Enter your name")
MsgBox ("You entered: " & Input)

Requirements
Version 1
See Also
MsgBox Function

2001 Microsoft Corporation. All rights reserved.


Build: Topic Version 5.6.9309.1546
Visual Basic Scripting Edition

InStr Function
Returns the position of the first occurrence of one string within another.
InStr([start, ]string1, string2[, compare])

Arguments
start
Optional. Numeric expression that sets the starting position for each search. If omitted, search begins at the first character position. If start contains Null, an error occurs. The start argument is required if compare is
specified.
string1
Required. String expression being searched.
string2
Required. String expression searched for.
compare
Optional. Numeric value indicating the kind of comparison to use when evaluating substrings. See Settings section for values. If omitted, a binary comparison is performed.
Settings
The compare argument can have the following values:
Constant
Value
Description
vbBinaryCompare 0
Perform a binary comparison.
vbTextCompare
1
Perform a textual comparison.
Return Values
The InStr function returns the following values:
If
string1 is zero-length
string1 is Null

InStr returns
0
Null

string2 is zero-length
string2 is Null
string2 is not found
string2 is found within string1
start > Len(string2)

start
Null
0
Position at which match is found
0

Remarks
The following examples use InStr to search a string:
Dim SearchString, SearchChar, MyPos
SearchString ="XXpXXpXXPXXP"
' String to search in.
SearchChar = "P"
' Search for "P".
MyPos = Instr(4, SearchString, SearchChar, 1)
' A textual comparison starting at position 4. Returns 6.
MyPos = Instr(1, SearchString, SearchChar, 0)
' A binary comparison starting at position 1. Returns 9.
MyPos = Instr(SearchString, SearchChar)
' Comparison is binary by default (last argument is omitted). Returns 9.
MyPos = Instr(1, SearchString, "W")
' A binary comparison starting at position 1. Returns 0 ("W" is not found).

Note The InStrB function is used with byte data contained in a string. Instead of returning the character position of the first occurrence of one string within another, InStrB returns the byte position.
Requirements
Version 1
See Also
InStrRev Function

2001 Microsoft Corporation. All rights reserved.


Build: Topic Version 5.6.9309.1546
Visual Basic Scripting Edition

InStrRev Function
Returns the position of an occurrence of one string within another, from the end of string.
InStrRev(string1, string2[, start[, compare]])

Arguments
string1
Required. String expression being searched.
string2
Required. String expression being searched for.
start
Optional. Numeric expression that sets the starting position for each search. If omitted, -1 is used, which means that the search begins at the last character position. If start contains Null, an error occurs.
compare
Optional. Numeric value indicating the kind of comparison to use when evaluating substrings. If omitted, a binary comparison is performed. See Settings section for values.
Settings
The compare argument can have the following values:
Constant
Value
Description
vbBinaryCompare 0
Perform a binary comparison.
vbTextCompare 1
Perform a textual comparison.
Return Values
InStrRev returns the following values:
If
string1 is zero-length
string1 is Null
string2 is zero-length
string2 is Null
string2 is not found
string2 is found within string1
start > Len(string2)

InStrRev returns
0
Null
start
Null
0
Position at which match is found
0

Remarks
The following examples use the InStrRev function to search a string:
Dim SearchString, SearchChar, MyPos
SearchString ="XXpXXpXXPXXP"
' String to
SearchChar = "P"
' Search for "P".
MyPos = InstrRev(SearchString, SearchChar,
MyPos = InstrRev(SearchString, SearchChar,
MyPos = InstrRev(SearchString, SearchChar,

search in.
10, 0)
' A binary comparison starting at position 10. Returns 9.
-1, 1)
' A textual comparison starting at the last position. Returns 12.
8)
' Comparison is binary by default (last argument is omitted). Returns 0.

Note The syntax for the InStrRev function is not the same as the syntax for the InStr function.
Requirements
Version 2
See Also
InStr Function

2001 Microsoft Corporation. All rights reserved.


Build: Topic Version 5.6.9309.1546
Visual Basic Scripting Edition

Int, Fix Functions

Returns the integer portion of a number.


Int(number)
Fix(number)

The number argument can be any valid numeric expression. If number contains Null, Null is returned.
Remarks
Both Int and Fix remove the fractional part of number and return the resulting integer value.
The difference between Int and Fix is that if number is negative, Int returns the first negative integer less than or equal to number, whereas Fix returns the first negative integer greater than or equal to number. For example, Int
converts -8.4 to -9, and Fix converts -8.4 to -8.
Fix(number) is equivalent to:
Sgn(number) * Int(Abs(number))

The following examples illustrate how the Int and Fix functions return integer portions of numbers:
MyNumber
MyNumber
MyNumber
MyNumber
MyNumber
MyNumber

=
=
=
=
=
=

Int(99.8)
Fix(99.2)
Int(-99.8)
Fix(-99.8)
Int(-99.2)
Fix(-99.2)

'
'
'
'
'
'

Returns
Returns
Returns
Returns
Returns
Returns

99.
99.
-100.
-99.
-100.
-99.

Requirements
Version 1
See Also
CInt Function | Round Function

2001 Microsoft Corporation. All rights reserved.


Build: Topic Version 5.6.9309.1546
Visual Basic Scripting Edition

IsArray Function
Returns a Boolean value indicating whether a variable is an array.
IsArray(varname)

The varname argument can be any variable.


Remarks
IsArray returns True if the variable is an array; otherwise, it returns False. IsArray is especially useful with variants containing arrays.
The following example uses the IsArray function to test whether MyVariable is an array:
Dim MyVariable
Dim MyArray(3)
MyArray(0) = "Sunday"
MyArray(1) = "Monday"
MyArray(2) = "Tuesday"
MyVariable = IsArray(MyArray) ' MyVariable contains "True".

Requirements
Version 1
See Also
IsDate Function | IsEmpty Function | IsNull Function | IsNumeric Function | IsObject Function | VarType Function

2001 Microsoft Corporation. All rights reserved.


Build: Topic Version 5.6.9309.1546
Visual Basic Scripting Edition

IsDate Function
Returns a Boolean value indicating whether an expression can be converted to a date.
IsDate(expression)

The expression argument can be any date expression or string expression recognizable as a date or time.
Remarks
IsDate returns True if the expression is a date or can be converted to a valid date; otherwise, it returns False. In Microsoft Windows, the range of valid dates is January 1, 100 A.D. through December 31, 9999 A.D.; the ranges
vary among operating systems.
The following example uses the IsDate function to determine whether an expression can be converted to a date:
Dim MyDate, YourDate, NoDate, MyCheck
MyDate = "October 19, 1962": YourDate = #10/19/62#: NoDate = "Hello"
MyCheck = IsDate(MyDate)
' Returns True.
MyCheck = IsDate(YourDate)
' Returns True.
MyCheck = IsDate(NoDate)
' Returns False.

Requirements
Version 1
See Also

CDate Function | IsArray Function | IsEmpty Function | IsNull Function | IsNumeric Function | IsObject Function | VarType Function

2001 Microsoft Corporation. All rights reserved.


Build: Topic Version 5.6.9309.1546
Visual Basic Scripting Edition

IsEmpty Function
Returns a Boolean value indicating whether a variable has been initialized.
IsEmpty(expression)

The expression argument can be any expression. However, because IsEmpty is used to determine if individual variables are initialized, the expression argument is most often a single variable name.
Remarks
IsEmpty returns True if the variable is uninitialized, or is explicitly set to Empty; otherwise, it returns False. False is always returned if expression contains more than one variable.
The following example uses the IsEmpty function to determine whether a variable has been initialized:
Dim MyVar, MyCheck
MyCheck = IsEmpty(MyVar)
' Returns True.
MyVar = Null
' Assign Null.
MyCheck = IsEmpty(MyVar)
' Returns False.
MyVar = Empty
' Assign Empty.
MyCheck = IsEmpty(MyVar)
' Returns True.

Requirements
Version 1
See Also
IsArray Function | IsDate Function | IsNull Function | IsNumeric Function | IsObject Function | VarType Function

2001 Microsoft Corporation. All rights reserved.


Build: Topic Version 5.6.9309.1546
Visual Basic Scripting Edition

IsNull Function
Returns a Boolean value that indicates whether an expression contains no valid data (Null).
IsNull(expression)

The expression argument can be any expression.


Remarks
IsNull returns True if expression is Null, that is, it contains no valid data; otherwise, IsNull returns False. If expression consists of more than one variable, Null in any constituent variable causes True to be returned for the
entire expression.
The Null value indicates that the variable contains no valid data. Null is not the same as Empty, which indicates that a variable has not yet been initialized. It is also not the same as a zero-length string (""), which is sometimes
referred to as a null string.
Caution Use the IsNull function to determine whether an expression contains a Null value. Expressions that you might expect to evaluate to True under some circumstances, such as If Var = Null and If Var <>
Null, are always False. This is because any expression containing a Null is itself Null, and therefore, False.
The following example uses the IsNull function to determine whether a variable contains a Null:
Dim MyVar, MyCheck
MyCheck = IsNull(MyVar)
' Returns False.
MyVar = Null
' Assign Null.
MyCheck = IsNull(MyVar)
' Returns True.
MyVar = Empty
' Assign Empty.
MyCheck = IsNull(MyVar)
' Returns False.

Requirements
Version 1
See Also
IsArray Function | IsDate Function | IsEmpty Function | IsNumeric Function | IsObject Function | VarType Function

2001 Microsoft Corporation. All rights reserved.


Build: Topic Version 5.6.9309.1546
Visual Basic Scripting Edition

IsNumeric Function
Returns a Boolean value indicating whether an expression can be evaluated as a number.
IsNumeric(expression)

The expression argument can be any expression.


Remarks
IsNumeric returns True if the entire expression is recognized as a number; otherwise, it returns False. IsNumeric returns False if expression is a date expression.
The following example uses the IsNumeric function to determine whether a variable can be evaluated as a number:

Dim MyVar, MyCheck


MyVar = 53
' Assign a value.
MyCheck = IsNumeric(MyVar)
' Returns True.
MyVar = "459.95"
' Assign a value.
MyCheck = IsNumeric(MyVar)
' Returns True.
MyVar = "45 Help"
' Assign a value.
MyCheck = IsNumeric(MyVar)
' Returns False.

Requirements
Version 1
See Also
IsArray Function | IsDate Function | IsEmpty Function | IsNull Function | IsObject Function | VarType Function

2001 Microsoft Corporation. All rights reserved.


Build: Topic Version 5.6.9309.1546
Visual Basic Scripting Edition

IsObject Function
Returns a Boolean value indicating whether an expression references a valid Automation object.
IsObject(expression)

The expression argument can be any expression.


Remarks
IsObject returns True if expression is a variable of Object subtype or a user-defined object; otherwise, it returns False.
The following example uses the IsObject function to determine if an identifier represents an object variable:
Dim MyInt, MyCheck, MyObject
Set MyObject = Me
MyCheck = IsObject(MyObject)
' Returns True.
MyCheck = IsObject(MyInt)
' Returns False.

Requirements
Version 1
See Also
IsArray Function | IsDate Function | IsEmpty Function | IsNull Function | IsNumeric Function | Set Statement | VarType Function

2001 Microsoft Corporation. All rights reserved.


Build: Topic Version 5.6.9309.1546
Visual Basic Scripting Edition

Join Function
Returns a string created by joining a number of substrings contained in an array.
Join(list[, delimiter])

Arguments
list
Required. One-dimensional array containing substrings to be joined.
delimiter
Optional. String character used to separate the substrings in the returned string. If omitted, the space character (" ") is used. If delimiter is a zero-length string, all items in the list are concatenated with no delimiters.
Remarks
The following example uses the Join function to join the substrings of MyArray:
Dim MyString
Dim MyArray(3)
MyArray(0) = "Mr."
MyArray(1) = "John "
MyArray(2) = "Doe "
MyArray(3) = "III"
MyString = Join(MyArray) ' MyString contains "Mr. John Doe III".

Requirements
Version 2
See Also
Split Function

2001 Microsoft Corporation. All rights reserved.


Build: Topic Version 5.6.9309.1546
Visual Basic Scripting Edition

LBound Function
Returns the smallest available subscript for the indicated dimension of an array.
LBound(arrayname[, dimension])

Arguments
arrayname
Name of the array variable; follows standard variable naming conventions.
dimension
Whole number indicating which dimension's lower bound is returned. Use 1 for the first dimension, 2 for the second, and so on. If dimension is omitted, 1 is assumed.
Remarks
The LBound function is used with the UBound function to determine the size of an array. Use the UBound function to find the upper limit of an array dimension.
The lower bound for any dimension is always 0.
Requirements
Version 1
See Also
Dim Statement | ReDim Statement | UBound Function

2001 Microsoft Corporation. All rights reserved.


Build: Topic Version 5.6.9309.1546
Visual Basic Scripting Edition

LCase Function
Returns a string that has been converted to lowercase.
LCase(string)

The string argument is any valid string expression. If string contains Null, Null is returned.
Remarks
Only uppercase letters are converted to lowercase; all lowercase letters and non-letter characters remain unchanged.
The following example uses the LCase function to convert uppercase letters to lowercase:
Dim MyString
Dim LCaseString
MyString = "VBSCript"
LCaseString = LCase(MyString)

' LCaseString contains "vbscript".

Requirements
Version 1
See Also
UCase Function

2001 Microsoft Corporation. All rights reserved.


Build: Topic Version 5.6.9309.1546
Visual Basic Scripting Edition

Left Function
Returns a specified number of characters from the left side of a string.
Left(string, length)

Arguments
string
String expression from which the leftmost characters are returned. If string contains Null, Null is returned.
length
Numeric expression indicating how many characters to return. If 0, a zero-length string("") is returned. If greater than or equal to the number of characters in string, the entire string is returned.
Remarks
To determine the number of characters in string, use the Len function.
The following example uses the Left function to return the first three characters of MyString:
Dim MyString, LeftString
MyString = "VBSCript"
LeftString = Left(MyString, 3) ' LeftString contains "VBS".

Note The LeftB function is used with byte data contained in a string. Instead of specifying the number of characters to return, length specifies the number of bytes.
Requirements
Version 1
See Also
Len Function | Mid Function | Right Function

2001 Microsoft Corporation. All rights reserved.


Build: Topic Version 5.6.9309.1546
Visual Basic Scripting Edition

Len Function
Returns the number of characters in a string or the number of bytes required to store a variable.
Len(string | varname)

Arguments
string
Any valid string expression. If string contains Null, Null is returned.
varname
Any valid variable name. If varname contains Null, Null is returned.
Remarks
The following example uses the Len function to return the number of characters in a string:
Dim MyString
MyString = Len("VBSCRIPT") ' MyString contains 8.

Note The LenB function is used with byte data contained in a string. Instead of returning the number of characters in a string, LenB returns the number of bytes used to represent that string.
Requirements
Version 1
See Also
InStr Function

2001 Microsoft Corporation. All rights reserved.


Build: Topic Version 5.6.9309.1546
Visual Basic Scripting Edition

LoadPicture Function
Returns a picture object. Available only on 32-bit platforms.
LoadPicture(picturename)

The picturename argument is a string expression that indicates the name of the picture file to be loaded.
Remarks
Graphics formats recognized by LoadPicture include bitmap (.bmp) files, icon (.ico) files, run-length encoded (.rle) files, metafile (.wmf) files, enhanced metafiles (.emf), GIF (.gif) files, and JPEG (.jpg) files.
Requirements
Version 2

2001 Microsoft Corporation. All rights reserved.


Build: Topic Version 5.6.9309.1546
Visual Basic Scripting Edition

Log Function
Returns the natural logarithm of a number.
Log(number)

The number argument can be any valid numeric expression greater than 0.
Remarks
The natural logarithm is the logarithm to the base e. The constant e is approximately 2.718282.
You can calculate base-n logarithms for any number x by dividing the natural logarithm of x by the natural logarithm of n as follows:
Logn(x) = Log(x) / Log(n)

The following example illustrates a custom Function that calculates base-10 logarithms:
Function Log10(X)
Log10 = Log(X) / Log(10)
End Function

Requirements
Version 1
See Also
Derived Math Functions | Exp Function

2001 Microsoft Corporation. All rights reserved.


Build: Topic Version 5.6.9309.1546
Visual Basic Scripting Edition

LTrim; RTrim; and Trim Functions

Returns a copy of a string without leading spaces (LTrim), trailing spaces (RTrim), or both leading and trailing spaces (Trim).
LTrim(string)
RTrim(string)
Trim(string)

The string argument is any valid string expression. If string contains Null, Null is returned.
Remarks
The following example uses the LTrim, RTrim, and Trim functions to trim leading spaces, trailing spaces, and both leading and trailing spaces, respectively:
Dim MyVar
MyVar = LTrim("
MyVar = RTrim("
MyVar = Trim("

vbscript ")
vbscript ")
vbscript ")

' MyVar contains "vbscript ".


' MyVar contains "
vbscript".
' MyVar contains "vbscript".

Requirements
Version 1
See Also
Left Function | Right Function

2001 Microsoft Corporation. All rights reserved.


Build: Topic Version 5.6.9309.1546
Visual Basic Scripting Edition

Math Functions
Abs Function
Atn Function
Cos Function
Exp Function
Fix Function
Int Function
Log Function
Rnd Function
Sgn Function
Sin Function
Sqr Function
Tan Function
Derived Math Functions

2001 Microsoft Corporation. All rights reserved.


Build: Topic Version 5.6.9309.1546
Visual Basic Scripting Edition

Mid Function
Returns a specified number of characters from a string.
Mid(string, start[, length])

Arguments
string
String expression from which characters are returned. If string contains Null, Null is returned.
start
Character position in string at which the part to be taken begins. If start is greater than the number of characters in string, Mid returns a zero-length string ("").
length
Number of characters to return. If omitted or if there are fewer than length characters in the text (including the character at start), all characters from the start position to the end of the string are returned.
Remarks
To determine the number of characters in string, use the Len function.
The following example uses the Mid function to return six characters, beginning with the fourth character, in a string:
Dim MyVar
MyVar = Mid("VB Script is fun!", 4, 6) ' MyVar contains "Script".

Note The MidB function is used with byte data contained in a string. Instead of specifying the number of characters, the arguments specify numbers of bytes.
Requirements
Version 1
See Also
Left Function | Len Function | LTrim, RTrim, and Trim Functions | Right Function

2001 Microsoft Corporation. All rights reserved.


Build: Topic Version 5.6.9309.1546
Visual Basic Scripting Edition

Minute
Returns a whole number between 0 and 59, inclusive, representing the minute of the hour.
Minute(time)

The time argument is any expression that can represent a time. If time contains Null, Null is returned.
Remarks
The following example uses the Minute function to return the minute of the hour:
Dim MyVar
MyVar = Minute(Now)

Requirements
Version 1
See Also
Day Function | Hour Function | Now Function | Second Function | Time Function

2001 Microsoft Corporation. All rights reserved.


Build: Topic Version 5.6.9309.1546
Visual Basic Scripting Edition

Month Function
Returns a whole number between 1 and 12, inclusive, representing the month of the year.
Month(date)

The date argument is any expression that can represent a date. If date contains Null, Null is returned.
Remarks
The following example uses the Month function to return the current month:
Dim MyVar
MyVar = Month(Now) ' MyVar contains the number corresponding to
' the current month.

Requirements
Version 1
See Also
Date Function | Day Function | Now Function | Weekday Function | Year Function

2001 Microsoft Corporation. All rights reserved.


Build: Topic Version 5.6.9309.1546
Visual Basic Scripting Edition

MonthName Function
Returns a string indicating the specified month.
MonthName(month[, abbreviate])

Arguments
month
Required. The numeric designation of the month. For example, January is 1, February is 2, and so on.
abbreviate
Optional. Boolean value that indicates if the month name is to be abbreviated. If omitted, the default is False, which means that the month name is not abbreviated.
Remarks
The following example uses the MonthName function to return an abbreviated month name for a date expression:
Dim MyVar
MyVar = MonthName(10, True) ' MyVar contains "Oct".

Requirements
Version 2
See Also
WeekdayName Function

2001 Microsoft Corporation. All rights reserved.


Build: Topic Version 5.6.9309.1546

Visual Basic Scripting Edition

MsgBox Function
Displays a message in a dialog box, waits for the user to click a button, and returns a value indicating which button the user clicked.
MsgBox(prompt[, buttons][, title][, helpfile, context])

Arguments
prompt
String expression displayed as the message in the dialog box. The maximum length of prompt is approximately 1024 characters, depending on the width of the characters used. If prompt consists of more than one line, you
can separate the lines using a carriage return character (Chr(13)), a linefeed character (Chr(10)), or carriage returnlinefeed character combination (Chr(13) & Chr(10)) between each line.
buttons
Numeric expression that is the sum of values specifying the number and type of buttons to display, the icon style to use, the identity of the default button, and the modality of the message box. See Settings section for
values. If omitted, the default value for buttons is 0.
title
String expression displayed in the title bar of the dialog box. If you omit title, the application name is placed in the title bar.
helpfile
String expression that identifies the Help file to use to provide context-sensitive Help for the dialog box. If helpfile is provided, context must also be provided. Not available on 16-bit platforms.
context
Numeric expression that identifies the Help context number assigned by the Help author to the appropriate Help topic. If context is provided, helpfile must also be provided. Not available on 16-bit platforms.
Settings
The buttons argument settings are:
Constant
vbOKOnly
vbOKCancel
vbAbortRetryIgnore
vbYesNoCancel
vbYesNo
vbRetryCancel
vbCritical
vbQuestion
vbExclamation
vbInformation
vbDefaultButton1
vbDefaultButton2
vbDefaultButton3
vbDefaultButton4
vbApplicationModal
vbSystemModal

Value
0
1
2
3
4
5
16
32
48
64
0
256
512
768
0
4096

Description
Display OK button only.
Display OK and Cancel buttons.
Display Abort, Retry, and Ignore buttons.
Display Yes, No, and Cancel buttons.
Display Yes and No buttons.
Display Retry and Cancel buttons.
Display Critical Message icon.
Display Warning Query icon.
Display Warning Message icon.
Display Information Message icon.
First button is default.
Second button is default.
Third button is default.
Fourth button is default.
Application modal; the user must respond to the message box before continuing work in the current application.
System modal; all applications are suspended until the user responds to the message box.

The first group of values (05) describes the number and type of buttons displayed in the dialog box; the second group (16, 32, 48, 64) describes the icon style; the third group (0, 256, 512, 768) determines which button is the
default; and the fourth group (0, 4096) determines the modality of the message box. When adding numbers to create a final value for the argument buttons, use only one number from each group.
Return Values
The MsgBox function has the following return values:
Constant
vbOK
vbCancel
vbAbort
vbRetry
vbIgnore
vbYes
vbNo

Value
1
OK
2
Cancel
3
Abort
4
Retry
5
Ignore
6
Yes
7
No

Button

Remarks
When both helpfile and context are provided, the user can press F1 to view the Help topic corresponding to the context.
If the dialog box displays a Cancel button, pressing the ESC key has the same effect as clicking Cancel. If the dialog box contains a Help button, context-sensitive Help is provided for the dialog box. However, no value is
returned until one of the other buttons is clicked.
When the MsgBox function is used with Microsoft Internet Explorer, the title of any dialog presented always contains "VBScript:" to differentiate it from standard system dialogs.
The following example uses the MsgBox function to display a message box and return a value describing which button was clicked:
Dim MyVar
MyVar = MsgBox ("Hello World!", 65, "MsgBox Example")
' MyVar contains either 1 or 2, depending on which button is clicked.

Requirements
Version 1
See Also
InputBox Function

2001 Microsoft Corporation. All rights reserved.


Build: Topic Version 5.6.9309.1546
Visual Basic Scripting Edition

Now
Returns the current date and time according to the setting of your computer's system date and time.
Now

Remarks
The following example uses the Now function to return the current date and time:
Dim MyVar
MyVar = Now ' MyVar contains the current date and time.

Requirements
Version 1
See Also
Date Function | Day Function | Hour Function | Minute Function | Month Function | Second Function | Time Function | Weekday Function | Year Function

2001 Microsoft Corporation. All rights reserved.


Build: Topic Version 5.6.9309.1546
Visual Basic Scripting Edition

Oct
Returns a string representing the octal value of a number.
Oct(number)

The number argument is any valid expression.


Remarks
If number is not already a whole number, it is rounded to the nearest whole number before being evaluated.
If number is
Null
Empty
Any other number

Oct returns
Null.
Zero (0).
Up to 11 octal characters,

You can represent octal numbers directly by preceding numbers in the proper range with &O. For example, &O10 is the octal notation for decimal 8.
The following example uses the Oct function to return the octal value of a number:
Dim MyOct
MyOct = Oct(4)
MyOct = Oct(8)
MyOct = Oct(459)

' Returns 4.
' Returns 10.
' Returns 713.

Requirements
Version 1
See Also
Hex Function

2001 Microsoft Corporation. All rights reserved.


Build: Topic Version 5.6.9309.1546
Visual Basic Scripting Edition

Replace Function
Returns a string in which a specified substring has been replaced with another substring a specified number of times.
Replace(expression, find, replacewith[, start[, count[, compare]]])

Arguments
expression
Required. String expression containing substring to replace.
find
Required. Substring being searched for.
replacewith
Required. Replacement substring.
start
Optional. Position within expression where substring search is to begin. If omitted, 1 is assumed. Must be used in conjunction with count.
count
Optional. Number of substring substitutions to perform. If omitted, the default value is -1, which means make all possible substitutions. Must be used in conjunction with start.
compare
Optional. Numeric value indicating the kind of comparison to use when evaluating substrings. See Settings section for values. If omitted, the default value is 0, which means perform a binary comparison.
Settings
The compare argument can have the following values:
Constant
Value
Description
vbBinaryCompare 0
Perform a binary comparison.
vbTextCompare 1
Perform a textual comparison.
Return Values
Replace returns the following values:
If
expression is zero-length
expression is Null
find is zero-length
replacewith is zero-length
start > Len(expression)
count is 0

Replace returns
Zero-length string ("").
An error.
Copy of expression.
Copy of expression with all occurences of find removed.
Zero-length string.
Copy of expression.

Remarks
The return value of the Replace function is a string, with substitutions made, that begins at the position specified by start and and concludes at the end of the expression string. It is not a copy of the original string from start to
finish.

The following example uses the Replace function to return a string:


Dim MyString
MyString = Replace("XXpXXPXXp", "p", "Y")
MyString = Replace("XXpXXPXXp", "p", "Y",

' A binary comparison starting at the beginning of the string. Returns "XXYXXPXXY".
' A textual comparison starting at position 3. Returns "YXXYXXY". 3, -1, 1)

Requirements
Version 2
See Also
Filter Function

2001 Microsoft Corporation. All rights reserved.


Build: Topic Version 5.6.9309.1546
Visual Basic Scripting Edition

RGB Function
Returns a whole number representing an RGB color value.
RGB(red, green, blue)

Arguments
red
Required. Number in the range 0-255 representing the red component of the color.
green
Required. Number in the range 0-255 representing the green component of the color.
blue
Required. Number in the range 0-255 representing the blue component of the color.
Remarks
Application methods and properties that accept a color specification expect that specification to be a number representing an RGB color value. An RGB color value specifies the relative intensity of red, green, and blue to cause a
specific color to be displayed.
The low-order byte contains the value for red, the middle byte contains the value for green, and the high-order byte contains the value for blue.
For applications that require the byte order to be reversed, the following function will provide the same information with the bytes reversed:
Function RevRGB(red, green, blue)
RevRGB= CLng(blue + (green * 256) + (red * 65536))
End Function

The value for any argument to RGB that exceeds 255 is assumed to be 255.
Requirements
Version 2

2001 Microsoft Corporation. All rights reserved.


Build: Topic Version 5.6.9309.1546
Visual Basic Scripting Edition

Right Function
Returns a specified number of characters from the right side of a string.
Right(string, length)

Arguments
string
String expression from which the rightmost characters are returned. If string contains Null, Null is returned.
length
Numeric expression indicating how many characters to return. If 0, a zero-length string is returned. If greater than or equal to the number of characters in string, the entire string is returned.
Remarks
To determine the number of characters in string, use the Len function.
The following example uses the Right function to return a specified number of characters from the right side of a string:
Dim AnyString, MyStr
AnyString = "Hello World"
MyStr = Right(AnyString, 1)
MyStr = Right(AnyString, 6)
MyStr = Right(AnyString, 20)

'
'
'
'

Define string.
Returns "d".
Returns " World".
Returns "Hello World".

Note The RightB function is used with byte data contained in a string. Instead of specifying the number of characters to return, length specifies the number of bytes.
Requirements
Version 1
See Also
Left Function | Len Function | Mid Function

2001 Microsoft Corporation. All rights reserved.


Build: Topic Version 5.6.9309.1546

Visual Basic Scripting Edition

Rnd Function
Returns a random number.
Rnd[(number)]

The number argument can be any valid numeric expression.


Remarks
The Rnd function returns a value less than 1 but greater than or equal to 0. The value of number determines how Rnd generates a random number:
If number is
Less than zero
Greater than zero
Equal to zero
Not supplied

Rnd generates
The same number every time, using number as the seed.
The next random number in the sequence.
The most recently generated number.
The next random number in the sequence.

For any given initial seed, the same number sequence is generated because each successive call to the Rnd function uses the previous number as a seed for the next number in the sequence.
Before calling Rnd, use the Randomize statement without an argument to initialize the random-number generator with a seed based on the system timer.
To produce random integers in a given range, use this formula:
Int((upperbound - lowerbound + 1) * Rnd + lowerbound)

Here, upperbound is the highest number in the range, and lowerbound is the lowest number in the range.
Note To repeat sequences of random numbers, call Rnd with a negative argument immediately before using Randomize with a numeric argument. Using Randomize with the same value for number does not
repeat the previous sequence.
Requirements
Version 1
See Also
Randomize Statement

2001 Microsoft Corporation. All rights reserved.


Build: Topic Version 5.6.9309.1546
Visual Basic Scripting Edition

Round Function
Returns a number rounded to a specified number of decimal places.
Round(expression[, numdecimalplaces])

Arguments
expression
Required. Numeric expression being rounded.
numdecimalplaces
Optional. Number indicating how many places to the right of the decimal are included in the rounding. If omitted, integers are returned by the Round function.
Remarks
The following example uses the Round function to round a number to two decimal places:
Dim MyVar, pi
pi = 3.14159
MyVar = Round(pi, 2) ' MyVar contains 3.14.

Requirements
Version 2
See Also
Int, Fix Functions

2001 Microsoft Corporation. All rights reserved.


Build: Topic Version 5.6.9309.1546
Visual Basic Scripting Edition

ScriptEngine Function
Returns a string representing the scripting language in use.
ScriptEngine

Return Values
The ScriptEngine function can return any of the following strings:
String
VBScript
JScript
VBA
Remarks

Description
Indicates that Microsoft Visual Basic Scripting Edition is the current scripting engine.
Indicates that Microsoft JScript is the current scripting engine.
Indicates that Microsoft Visual Basic for Applications is the current scripting engine.

The following example uses the ScriptEngine function to return a string describing the scripting language in use:
Function GetScriptEngineInfo
Dim s
s = ""
' Build string with necessary info.
s = ScriptEngine & " Version "
s = s & ScriptEngineMajorVersion & "."
s = s & ScriptEngineMinorVersion & "."
s = s & ScriptEngineBuildVersion
GetScriptEngineInfo = s
' Return the results.
End Function

Requirements
Version 2
See Also
ScriptEngineBuildVersion Function | ScriptEngineMajorVersion Function | ScriptEngineMinorVersion Function

2001 Microsoft Corporation. All rights reserved.


Build: Topic Version 5.6.9309.1546
Visual Basic Scripting Edition

ScriptEngineBuildVersion Function
Returns the build version number of the scripting engine in use.
ScriptEngineBuildVersion

Remarks
The return value corresponds directly to the version information contained in the DLL for the scripting language in use.
The following example uses the ScriptEngineBuildVersion function to return the build version number of the scripting engine:
Function GetScriptEngineInfo
Dim s
s = ""
' Build string with necessary info.
s = ScriptEngine & " Version "
s = s & ScriptEngineMajorVersion & "."
s = s & ScriptEngineMinorVersion & "."
s = s & ScriptEngineBuildVersion
GetScriptEngineInfo = s
' Return the results.
End Function

Requirements
Version 2
See Also
ScriptEngine Function | ScriptEngineMajorVersion Function | ScriptEngineMinorVersion Function

2001 Microsoft Corporation. All rights reserved.


Build: Topic Version 5.6.9309.1546
Visual Basic Scripting Edition

ScriptEngineMajorVersion Function
Returns the major version number of the scripting engine in use.
ScriptEngineMajorVersion

Remarks
The return value corresponds directly to the version information contained in the DLL for the scripting language in use.
The following example uses the ScriptEngineMajorVersion function to return the version number of the scripting engine:
Function GetScriptEngineInfo
Dim s
s = ""
' Build string with necessary info.
s = ScriptEngine & " Version "
s = s & ScriptEngineMajorVersion & "."
s = s & ScriptEngineMinorVersion & "."
s = s & ScriptEngineBuildVersion
GetScriptEngineInfo = s
' Return the results.
End Function

Requirements
Version 2
See Also
ScriptEngine Function | ScriptEngineBuildVersion Function | ScriptEngineMinorVersion Function

2001 Microsoft Corporation. All rights reserved.


Build: Topic Version 5.6.9309.1546
Visual Basic Scripting Edition

ScriptEngineMinorVersion Function
Returns the minor version number of the scripting engine in use.

ScriptEngineMinorVersion

Remarks
The return value corresponds directly to the version information contained in the DLL for the scripting language in use.
The following example uses the ScriptEngineMinorVersion function to return the minor version number of the scripting engine:
Function GetScriptEngineInfo
Dim s
s = ""
' Build string with necessary info.
s = ScriptEngine & " Version "
s = s & ScriptEngineMajorVersion & "."
s = s & ScriptEngineMinorVersion & "."
s = s & ScriptEngineBuildVersion
GetScriptEngineInfo = s
' Return the results.
End Function

Requirements
Version 2
See Also
ScriptEngine Function | ScriptEngineBuildVersion Function | ScriptEngineMajorVersion Function

2001 Microsoft Corporation. All rights reserved.


Build: Topic Version 5.6.9309.1546
Visual Basic Scripting Edition

Second Function
Returns a whole number between 0 and 59, inclusive, representing the second of the minute.
Second(time)

The time argument is any expression that can represent a time. If time contains Null, Null is returned.
Remarks
The following example uses the Second function to return the current second:
Dim MySec
MySec = Second(Now)
' MySec contains the number representing the current second.

Requirements
Version 1
See Also
Day Function | Hour Function | Minute Function | Now Function | Time Function

2001 Microsoft Corporation. All rights reserved.


Build: Topic Version 5.6.9309.1546
Visual Basic Scripting Edition

SetLocale Function
Sets the global locale and returns the previous locale.
SetLocale(lcid)

The lcid argument can be any valid 32-bit value or short string that uniquely identifies a geographical locale. Recognized values can be found in the Locale ID chart.
Remarks
If lcid is zero, the locale is set to match the current system setting.
A locale is a set of user preference information related to the user's language, country/region, and cultural conventions. The locale determines such things as keyboard layout, alphabetic sort order, as well as date, time, number,
and currency formats.
The following example illustrates the use of the SetLocale function. To use this code, paste the entire example between the <BODY> tags of a standard HTML page.
Enter Date in UK format: <input type="text" id="UKDate" size="20"><p>
Here's the US equivalent: <input type="text" id="USdate" size="20"><p>
<input type="button" value="Convert" id="button1"><p>
Enter a price in German: &nbsp; <input type="text" id="GermanNumber" size="20">
<p>
Here's the UK equivalent: <input type="text" id="USNumber" size="20"><p>
<input type="button" value="Convert" id="button2"><p>
<script language="vbscript">
Dim currentLocale
' Get the current locale
currentLocale = GetLocale
Sub Button1_onclick
Dim original
original = SetLocale("en-gb")
mydate = CDate(UKDate.value)
' IE always sets the locale to US English so use the
' currentLocale variable to set the locale to US English
original = SetLocale(currentLocale)
USDate.value = FormatDateTime(mydate,vbShortDate)
End Sub
Sub button2_onclick
Dim original
original = SetLocale("de")
myvalue = CCur(GermanNumber.value)
original = SetLocale("en-gb")

USNumber.value = FormatCurrency(myvalue)
End Sub
</script>

See Also
GetLocale Function | Locale ID (LCID) Chart

2001 Microsoft Corporation. All rights reserved.


Build: Topic Version 5.6.9309.1546
Visual Basic Scripting Edition

Sgn Function
Returns an integer indicating the sign of a number.
Sgn(number)

The number argument can be any valid numeric expression.


Return Values
The Sgn function has the following return values:
If number is
Sgn returns
Greater than zero 1
Equal to zero
0
Less than zero -1
Remarks
The sign of the number argument determines the return value of the Sgn function.
The following example uses the Sgn function to determine the sign of a number:
Dim MyVar1, MyVar2, MyVar3, MySign
MyVar1 = 12: MyVar2 = -2.4: MyVar3 = 0
MySign = Sgn(MyVar1)
' Returns 1.
MySign = Sgn(MyVar2)
' Returns -1.
MySign = Sgn(MyVar3)
' Returns 0.

Requirements
Version 1
See Also
Abs Function

2001 Microsoft Corporation. All rights reserved.


Build: Topic Version 5.6.9309.1546
Visual Basic Scripting Edition

Sin Function
Returns the sine of an angle.
Sin(number)

The number argument can be any valid numeric expression that expresses an angle in radians.
Remarks
The Sin function takes an angle and returns the ratio of two sides of a right triangle. The ratio is the length of the side opposite the angle divided by the length of the hypotenuse. The result lies in the range -1 to 1.
To convert degrees to radians, multiply degrees by pi /180. To convert radians to degrees, multiply radians by 180/pi.
The following example uses the Sin function to return the sine of an angle:
Dim MyAngle, MyCosecant
MyAngle = 1.3
' Define angle in radians.
MyCosecant = 1 / Sin(MyAngle)
' Calculate cosecant.

Requirements
Version 1
See Also
Atn Function | Cos Function | Derived Math Functions | Tan Function

2001 Microsoft Corporation. All rights reserved.


Build: Topic Version 5.6.9309.1546
Visual Basic Scripting Edition

Space Function
Returns a string consisting of the specified number of spaces.
Space(number)

The number argument is the number of spaces you want in the string.
Remarks
The following example uses the Space function to return a string consisting of a specified number of spaces:
Dim MyString
MyString = Space(10)
' Returns a string with 10 spaces.
MyString = "Hello" & Space(10) & "World" ' Insert 10 spaces between two strings.

Requirements
Version 1
See Also
String Function

2001 Microsoft Corporation. All rights reserved.


Build: Topic Version 5.6.9309.1546
Visual Basic Scripting Edition

Split Function
Returns a zero-based, one-dimensional array containing a specified number of substrings.
Split(expression[, delimiter[, count[, compare]]])

Arguments
expression
Required. String expression containing substrings and delimiters. If expression is a zero-length string, Split returns an empty array, that is, an array with no elements and no data.
delimiter
Optional. String character used to identify substring limits. If omitted, the space character (" ") is assumed to be the delimiter. If delimiter is a zero-length string, a single-element array containing the entire expression
string is returned.
count
Optional. Number of substrings to be returned; -1 indicates that all substrings are returned.
compare
Optional. Numeric value indicating the kind of comparison to use when evaluating substrings. See Settings section for values.
Settings
The compare argument can have the following values:
Constant
Value
Description
vbBinaryCompare 0
Perform a binary comparison.
vbTextCompare 1
Perform a textual comparison.
Remarks
The following example uses the Split function to return an array from a string. The function performs a textual comparison of the delimiter, and returns all of the substrings.
Dim MyString, MyArray, Msg
MyString = "VBScriptXisXfun!"
MyArray = Split(MyString, "x", -1, 1)
' MyArray(0) contains "VBScript".
' MyArray(1) contains "is".
' MyArray(2) contains "fun!".
Msg = MyArray(0) & " " & MyArray(1)
Msg = Msg
& " " & MyArray(2)
MsgBox Msg

Requirements
Version 2
See Also
Join Function

2001 Microsoft Corporation. All rights reserved.


Build: Topic Version 5.6.9309.1546
Visual Basic Scripting Edition

Sqr Function
Returns the square root of a number.
Sqr(number)

The number argument can be any valid numeric expression greater than or equal to 0.
Remarks
The following example uses the Sqr function to calculate the square root of a number:
Dim MySqr
MySqr = Sqr(4)
MySqr = Sqr(23)
MySqr = Sqr(0)
MySqr = Sqr(-4)

Requirements
Version 1

' Returns 2.
' Returns 4.79583152331272.
' Returns 0.
' Generates a run-time error.

2001 Microsoft Corporation. All rights reserved.


Build: Topic Version 5.6.9309.1546
Visual Basic Scripting Edition

StrComp Function
Returns a value indicating the result of a string comparison.
StrComp(string1, string2[, compare])

Arguments
string1
Required. Any valid string expression.
string2
Required. Any valid string expression.
compare
Optional. Numeric value indicating the kind of comparison to use when evaluating strings. If omitted, a binary comparison is performed. See Settings section for values.
Settings
The compare argument can have the following values:
Constant
Value
Description
vbBinaryCompare 0
Perform a binary comparison.
vbTextCompare 1
Perform a textual comparison.
Return Values
The StrComp function has the following return values:
If
string1 is less than string2
string1 is equal to string2
string1 is greater than string2
string1 or string2 is Null

StrComp returns
-1
0
1
Null

Remarks
The following example uses the StrComp function to return the results of a string comparison. If the third argument is 1, a textual comparison is performed; if the third argument is 0 or omitted, a binary comparison is
performed.
Dim MyStr1, MyStr2, MyComp
MyStr1 = "ABCD": MyStr2 = "abcd"
' Define variables.
MyComp = StrComp(MyStr1, MyStr2, 1)
' Returns 0.
MyComp = StrComp(MyStr1, MyStr2, 0)
' Returns -1.
MyComp = StrComp(MyStr2, MyStr1)
' Returns 1.

Requirements
Version 1

2001 Microsoft Corporation. All rights reserved.


Build: Topic Version 5.6.9309.1546
Visual Basic Scripting Edition

String Function
Returns a repeating character string of the length specified.
String(number, character)

Arguments
number
Length of the returned string. If number contains Null, Null is returned.
character
Character code specifying the character or string expression whose first character is used to build the return string. If character contains Null, Null is returned.
Remarks
If you specify a number for character greater than 255, String converts the number to a valid character code using the formula:
character Mod 256

The following example uses the String function to return repeating character strings of the length specified:
Dim MyString
MyString = String(5, "*")
' Returns "*****".
MyString = String(5, 42)
' Returns "*****".
MyString = String(10, "ABC")
' Returns "AAAAAAAAAA".

Requirements
Version 1
See Also
Space Function

2001 Microsoft Corporation. All rights reserved.


Build: Topic Version 5.6.9309.1546
Visual Basic Scripting Edition

StrReverse Function
Returns a string in which the character order of a specified string is reversed.
StrReverse(string1)

The string1 argument is the string whose characters are to be reversed. If string1 is a zero-length string (""), a zero-length string is returned. If string1 is Null, an error occurs.
Remarks
The following example uses the StrReverse function to return a string in reverse order:
Dim MyStr
MyStr = StrReverse("VBScript") ' MyStr contains "tpircSBV".

Requirements
Version 2

2001 Microsoft Corporation. All rights reserved.


Build: Topic Version 5.6.9309.1546
Visual Basic Scripting Edition

Tan Function
Returns the tangent of an angle.
Tan(number)

The number argument can be any valid numeric expression that expresses an angle in radians.
Remarks
Tan takes an angle and returns the ratio of two sides of a right triangle. The ratio is the length of the side opposite the angle divided by the length of the side adjacent to the angle.
To convert degrees to radians, multiply degrees by pi /180. To convert radians to degrees, multiply radians by 180/pi.
The following example uses the Tan function to return the tangent of an angle:
Dim MyAngle, MyCotangent
MyAngle = 1.3
' Define angle in radians.
MyCotangent = 1 / Tan(MyAngle)
' Calculate cotangent.

Requirements
Version 1
See Also
Atn Function | Cos Function | Derived Math Functions | Sin Function

2001 Microsoft Corporation. All rights reserved.


Build: Topic Version 5.6.9309.1546
Visual Basic Scripting Edition

Time Function
Returns a Variant of subtype Date indicating the current system time.
Time

Remarks
The following example uses the Time function to return the current system time:
Dim MyTime
MyTime = Time

' Return current system time.

Requirements
Version 1
See Also
Date Function

2001 Microsoft Corporation. All rights reserved.


Build: Topic Version 5.6.9309.1546
Visual Basic Scripting Edition

Timer Function
Returns the number of seconds that have elapsed since 12:00 AM (midnight).
Timer

Remarks
The following example uses the Timer function to determine the time it takes to iterate a For...Next loop N times:
Function TimeIt(N)

Dim StartTime, EndTime


StartTime = Timer
For I = 1 To N
Next
EndTime = Timer
TimeIt = EndTime - StartTime
End Function

Requirements
Version 5
See Also
Randomize Statement

2001 Microsoft Corporation. All rights reserved.


Build: Topic Version 5.6.9309.1546
Visual Basic Scripting Edition

TimeSerial Function
Returns a Variant of subtype Date containing the time for a specific hour, minute, and second.
TimeSerial(hour, minute, second)

Arguments
hour
Number between 0 (12:00 A.M.) and 23 (11:00 P.M.), inclusive, or a numeric expression.
minute
Any numeric expression.
second
Any numeric expression.
Remarks
To specify a time, such as 11:59:59, the range of numbers for each TimeSerial argument should be in the accepted range for the unit; that is, 023 for hours and 059 for minutes and seconds. However, you can also specify
relative times for each argument using any numeric expression that represents some number of hours, minutes, or seconds before or after a certain time.
The following example uses expressions instead of absolute time numbers. The TimeSerial function returns a time for 15 minutes before (-15) six hours before noon (12 - 6), or 5:45:00 A.M.
Dim MyTime1
MyTime1 = TimeSerial(12 - 6, -15, 0) ' Returns 5:45:00 AM.

When any argument exceeds the accepted range for that argument, it increments to the next larger unit as appropriate. For example, if you specify 75 minutes, it is evaluated as one hour and 15 minutes. However, if any single
argument is outside the range -32,768 to 32,767, or if the time specified by the three arguments, either directly or by expression, causes the date to fall outside the acceptable range of dates, an error occurs.
Requirements
Version 1
See Also
DateSerial Function | DateValue Function | Hour Function | Minute Function | Now Function | Second Function | TimeValue Function

2001 Microsoft Corporation. All rights reserved.


Build: Topic Version 5.6.9309.1546
Visual Basic Scripting Edition

TimeValue
Returns a Variant of subtype Date containing the time.
TimeValue(time)

The time argument is usually a string expression representing a time from 0:00:00 (12:00:00 A.M.) to 23:59:59 (11:59:59 P.M.), inclusive. However, time can also be any expression that represents a time in that range. If time
contains Null, Null is returned.
Remarks
You can enter valid times using a 12-hour or 24-hour clock. For example, "2:24PM" and "14:24" are both valid time arguments. If the time argument contains date information, TimeValue doesn't return the date information.
However, if time includes invalid date information, an error occurs.
The following example uses the TimeValue function to convert a string to a time. You can also use date literals to directly assign a time to a Variant (for example, MyTime = #4:35:17 PM#).
Dim MyTime
MyTime = TimeValue("4:35:17 PM")

' MyTime contains 4:35:17 PM.

Requirements
Version 1
See Also
DateSerial Function | DateValue Function | Hour Function | Minute Function | Now Function | Second Function | TimeSerial Function

2001 Microsoft Corporation. All rights reserved.


Build: Topic Version 5.6.9309.1546
Visual Basic Scripting Edition

TypeName Function

Returns a string that provides Variant subtype information about a variable.


TypeName(varname)

The required varname argument can be any variable.


Return Values
The TypeName function has the following return values:
Value
Byte
Integer
Long
Single
Double
Currency
Decimal
Date
String
Boolean
Empty
Null
<object type>
Object
Unknown
Nothing
Error

Description
Byte value
Integer value
Long integer value
Single-precision floating-point value
Double-precision floating-point value
Currency value
Decimal value
Date or time value
Character string value
Boolean value; True or False
Unitialized
No valid data
Actual type name of an object
Generic object
Unknown object type
Object variable that doesn't yet refer to an object instance
Error

Remarks
The following example uses the TypeName function to return information about a variable:
Dim ArrayVar(4), MyType
NullVar = Null
' Assign Null value.
MyType
MyType
MyType
MyType
MyType

=
=
=
=
=

TypeName("VBScript")
TypeName(4)
TypeName(37.50)
TypeName(NullVar)
TypeName(ArrayVar)

'
'
'
'
'

Returns
Returns
Returns
Returns
Returns

"String".
"Integer".
"Double".
"Null".
"Variant()".

Requirements
Version 2
See Also
IsArray Function | IsDate Function | IsEmpty Function | IsNull Function | IsNumeric Function | IsObject Function | VarType Function

2001 Microsoft Corporation. All rights reserved.


Build: Topic Version 5.6.9309.1546
Visual Basic Scripting Edition

UBound Function
Returns the largest available subscript for the indicated dimension of an array.
UBound(arrayname[, dimension])

Arguments
arrayname
Required. Name of the array variable; follows standard variable naming conventions.
dimension
Optional. Whole number indicating which dimension's upper bound is returned. Use 1 for the first dimension, 2 for the second, and so on. If dimension is omitted, 1 is assumed.
Remarks
The UBound function is used with the LBound function to determine the size of an array. Use the LBound function to find the lower limit of an array dimension.
The lower bound for any dimension is always 0. As a result, UBound returns the following values for an array with these dimensions:
Dim A(100,3,4)

Statement
UBound(A, 1)
UBound(A, 2)
UBound(A, 3)

Return Value
100
3
4

Requirements
Version 1
See Also
Dim Statement | LBound Function | ReDim Statement

2001 Microsoft Corporation. All rights reserved.


Build: Topic Version 5.6.9309.1546
Visual Basic Scripting Edition

UCase Function
Returns a string that has been converted to uppercase.

UCase(string)

The string argument is any valid string expression. If string contains Null, Null is returned.
Remarks
Only lowercase letters are converted to uppercase; all uppercase letters and non-letter characters remain unchanged.
The following example uses the UCase function to return an uppercase version of a string:
Dim MyWord
MyWord = UCase("Hello World")

' Returns "HELLO WORLD".

Requirements
Version 1
See Also
LCase Function

2001 Microsoft Corporation. All rights reserved.


Build: Topic Version 5.6.9309.1546
Visual Basic Scripting Edition

VarType Function
Returns a value indicating the subtype of a variable.
VarType(varname)

The varname argument can be any variable.


Return Values
The VarType function returns the following values:
Constant
vbEmpty
vbNull
vbInteger
vbLong
vbSingle
vbDouble
vbCurrency
vbDate
vbString
vbObject
vbError
vbBoolean
vbVariant
vbDataObject
vbByte
vbArray

Value
Description
0
Empty (uninitialized)
1
Null (no valid data)
2
Integer
3
Long integer
4
Single-precision floating-point number
5
Double-precision floating-point number
6
Currency
7
Date
8
String
9
Automation object
10
Error
11
Boolean
12
Variant (used only with arrays of Variants)
13
A data-access object
17
Byte
8192 Array

Note These constants are specified by VBScript. As a result, the names can be used anywhere in your code in place of the actual values.
Remarks
The VarType function never returns the value for Array by itself. It is always added to some other value to indicate an array of a particular type. The value for Variant is only returned when it has been added to the value for
Array to indicate that the argument to the VarType function is an array. For example, the value returned for an array of integers is calculated as 2 + 8192, or 8194. If an object has a default property, VarType (object) returns the
type of its default property.
The following example uses the VarType function to determine the subtype of a variable.
Dim MyCheck
MyCheck = VarType(300)
MyCheck = VarType(#10/19/62#)
MyCheck = VarType("VBScript")

' Returns 2.
' Returns 7.
' Returns 8.

Requirements
Version 1
See Also
IsArray Function | IsDate Function | IsEmpty Function | IsNull Function | IsNumeric Function | IsObject Function | TypeName Function

2001 Microsoft Corporation. All rights reserved.


Build: Topic Version 5.6.9309.1546
Visual Basic Scripting Edition

Weekday Function
Returns a whole number representing the day of the week.
Weekday(date, [firstdayofweek])

Arguments
date
Any expression that can represent a date. If date contains Null, Null is returned.
firstdayofweek
A constant that specifies the first day of the week. If omitted, vbSunday is assumed.
Settings

The firstdayofweek argument has these settings:


Constant
Value
vbUseSystemDayOfWeek 0
vbSunday
1
vbMonday
2
vbTuesday
3
vbWednesday
4
vbThursday
5
vbFriday
6
vbSaturday
7

Description
Use National Language Support (NLS) API setting.
Sunday
Monday
Tuesday
Wednesday
Thursday
Friday
Saturday

Return Values
The Weekday function can return any of these values:
Constant
vbSunday
vbMonday
vbTuesday
vbWednesday
vbThursday
vbFriday
vbSaturday

Value
Description
1
Sunday
2
Monday
3
Tuesday
4
Wednesday
5
Thursday
6
Friday
7
Saturday

Remarks
The following example uses the Weekday function to obtain the day of the week from a specified date:
Dim MyDate, MyWeekDay
MyDate = #October 19, 1962#
MyWeekDay = Weekday(MyDate)

' Assign a date.


' MyWeekDay contains 6 because MyDate represents a Friday.

Requirements
Version 1
See Also
Date Function | Day Function | Month Function | Now Function | Year Function

2001 Microsoft Corporation. All rights reserved.


Build: Topic Version 5.6.9309.1546
Visual Basic Scripting Edition

WeekdayName Function
Returns a string indicating the specified day of the week.
WeekdayName(weekday, abbreviate, firstdayofweek)

Arguments
weekday
Required. The numeric designation for the day of the week. Numeric value of each day depends on setting of the firstdayofweek setting.
abbreviate
Optional. Boolean value that indicates if the weekday name is to be abbreviated. If omitted, the default is False, which means that the weekday name is not abbreviated.
firstdayofweek
Optional. Numeric value indicating the first day of the week. See Settings section for values.
Settings
The firstdayofweek argument can have the following values:
Constant
Value
vbUseSystemDayOfWeek 0
vbSunday
1
vbMonday
2
vbTuesday
3
vbWednesday
4
vbThursday
5
vbFriday
6
vbSaturday
7

Description
Use National Language Support (NLS) API setting.
Sunday (default)
Monday
Tuesday
Wednesday
Thursday
Friday
Saturday

Remarks
The following example uses the WeekDayName function to return the specified day:
Dim MyDate
MyDate = WeekDayName(6, True)

' MyDate contains Fri.

Requirements
Version 2
See Also
MonthName Function

2001 Microsoft Corporation. All rights reserved.


Build: Topic Version 5.6.9309.1546
Visual Basic Scripting Edition

Year Function

Returns a whole number representing the year.


Year(date)

The date argument is any expression that can represent a date. If date contains Null, Null is returned.
Remarks
The following example uses the Year function to obtain the year from a specified date:
Dim MyDate, MyYear
MyDate = #October 19, 1962#
MyYear = Year(MyDate)

' Assign a date.


' MyYear contains 1962.

Requirements
Version 1
See Also
Date Function | Day Function | Month Function | Now Function | Weekday Function

2001 Microsoft Corporation. All rights reserved.


Build: Topic Version 5.6.9309.1546
Visual Basic Scripting Edition

VBScript Keywords
Empty
False
Nothing
Null
True
Related Sections
VBScript Langauge Reference

2001 Microsoft Corporation. All rights reserved.


Build: Topic Version 5.6.9309.1546
Visual Basic Scripting Edition

Empty
The Empty keyword is used to indicate an uninitialized variable value. This is not the same thing as Null.
See Also
Null

2001 Microsoft Corporation. All rights reserved.


Build: Topic Version 5.6.9309.1546
Visual Basic Scripting Edition

False
The False keyword has a value equal to 0.
See Also
True

2001 Microsoft Corporation. All rights reserved.


Build: Topic Version 5.6.9309.1546
Visual Basic Scripting Edition

Nothing
The Nothing keyword in VBScript is used to disassociate an object variable from any actual object. Use the Set statement to assign Nothing to an object variable. For example:
Set MyObject = Nothing

Several object variables can refer to the same actual object. When Nothing is assigned to an object variable, that variable no longer refers to any actual object. When several object variables refer to the same object, memory and
system resources associated with the object to which the variables refer are released only after all of them have been set to Nothing, either explicitly using Set, or implicitly after the last object variable set to Nothing goes out of
scope.
See Also
Dim Statement | Set Statement

2001 Microsoft Corporation. All rights reserved.


Build: Topic Version 5.6.9309.1546
Visual Basic Scripting Edition

Null
The Null keyword is used to indicate that a variable contains no valid data. This is not the same thing as Empty.
See Also
Empty

2001 Microsoft Corporation. All rights reserved.


Build: Topic Version 5.6.9309.1546
Visual Basic Scripting Edition

True
The True keyword has a value equal to -1.
See Also
False

2001 Microsoft Corporation. All rights reserved.


Build: Topic Version 5.6.9309.1546
Visual Basic Scripting Edition

Methods
In This Section
Clear Method
Execute Method
Raise Method
Replace Method
Test Method
Related Sections
VBScript Langauge Reference

2001 Microsoft Corporation. All rights reserved.


Build: Topic Version 5.6.9309.1546
Visual Basic Scripting Edition

Clear Method
Clears all property settings of the Err object.
object.Clear

The object is always the Err object.


Remarks
Use Clear to explicitly clear the Err object after an error has been handled. This is necessary, for example, when you use deferred error handling with On Error Resume Next. VBScript calls the Clear method automatically
whenever any of the following statements is executed:

On Error Resume Next


Exit Sub
Exit Function

The following example illustrates use of the Clear method.


On Error Resume Next
Err.Raise 6 ' Raise an overflow error.
MsgBox ("Error # " & CStr(Err.Number) & " " & Err.Description)
Err.Clear
' Clear the error.

Requirements
Version 1
See Also
Description Property | Err Object | Number Property | OnError Statement | Raise Method | Source Property
Applies To: Err Object

2001 Microsoft Corporation. All rights reserved.


Build: Topic Version 5.6.9309.1546
Visual Basic Scripting Edition

Execute Method
Executes a regular expression search against a specified string.
object.Execute(string)

Arguments
object
Required. Always the name of a RegExp object.
string
Required. The text string upon which the regular expression is executed.
Remarks
The actual pattern for the regular expression search is set using the Pattern property of the RegExp object.
The Execute method returns a Matches collection containing a Match object for each match found in string. Execute returns an empty Matches collection if no match is found.
The following code illustrates the use of the Execute method.
Function RegExpTest(patrn, strng)
Dim regEx, Match, Matches
' Create variable.
Set regEx = New RegExp
' Create a regular expression.
regEx.Pattern = patrn
' Set pattern.
regEx.IgnoreCase = True
' Set case insensitivity.
regEx.Global = True
' Set global applicability.
Set Matches = regEx.Execute(strng)
' Execute search.
For Each Match in Matches
' Iterate Matches collection.
RetStr = RetStr & "Match found at position "
RetStr = RetStr & Match.FirstIndex & ". Match Value is '"
RetStr = RetStr & Match.Value & "'." & vbCRLF
Next
RegExpTest = RetStr
End Function
MsgBox(RegExpTest("is.", "IS1 is2 IS3 is4"))

Requirements
Version 5
See Also
Replace Method | Test Method
Applies To: RegExp Object

2001 Microsoft Corporation. All rights reserved.


Build: Topic Version 5.6.9309.1546
Visual Basic Scripting Edition

Raise Method
Generates a run-time error.
object.Raise(number, source, description, helpfile, helpcontext)

Arguments
object
Always the Err object.
number
A Long integer subtype that identifies the nature of the error. VBScript errors (both VBScript-defined and user-defined errors) are in the range 065535.
source
A string expression naming the object or application that originally generated the error. When setting this property for an Automation object, use the form project.class. If nothing is specified, the programmatic ID of the
current VBScript project is used.
description
A string expression describing the error. If unspecified, the value in number is examined. If it can be mapped to a VBScript run-time error code, a string provided by VBScript is used as description. If there is no VBScript
error corresponding to number, a generic error message is used.
helpfile
The fully qualified path to the Help file in which help on this error can be found. If unspecified, VBScript uses the fully qualified drive, path, and file name of the VBScript Help file.
helpcontext
The context ID identifying a topic within helpfile that provides help for the error. If omitted, the VBScript Help file context ID for the error corresponding to the number property is used, if it exists.
Remarks
All the arguments are optional except number. If you use Raise, however, without specifying some arguments, and the property settings of the Err object contain values that have not been cleared, those values become the values
for your error.
When setting the number property to your own error code in an Automation object, you add your error code number to the constant vbObjectError. For example, to generate the error number 1050, assign vbObjectError +
1050 to the number property.
The following example illustrates use of the Raise method.
On Error Resume Next
Err.Raise 6 ' Raise an overflow error.
MsgBox ("Error # " & CStr(Err.Number) & " " & Err.Description)
Err.Clear
' Clear the error.

Requirements
Version 1
See Also
Clear Method | Description Property | Err Object | Number Property Source Property
Applies To: Err Object

2001 Microsoft Corporation. All rights reserved.


Build: Topic Version 5.6.9309.1546
Visual Basic Scripting Edition

Replace Method
Replaces text found in a regular expression search.
object.Replace(string1, string2)

Arguments
object
Required. Always the name of a RegExp object.
string1
Required. String1 is the text string in which the text replacement is to occur.
string2
Required. String2 is the replacement text string.
Remarks
The actual pattern for the text being replaced is set using the Pattern property of the RegExp object.
The Replace method returns a copy of string1 with the text of RegExp.Pattern replaced with string2. If no match is found, a copy of string1 is returned unchanged.
The following code illustrates use of the Replace method.
Function ReplaceTest(patrn, replStr)
Dim regEx, str1
' Create variables.
str1 = "The quick brown fox jumped over the lazy dog."
Set regEx = New RegExp
' Create regular expression.
regEx.Pattern = patrn
' Set pattern.
regEx.IgnoreCase = True
' Make case insensitive.
ReplaceTest = regEx.Replace(str1, replStr)
' Make replacement.
End Function
MsgBox(ReplaceTest("fox", "cat"))

' Replace 'fox' with 'cat'.

In addition, the Replace method can replace subexpressions in the pattern. The following call to the function shown in the previous example swaps each pair of words in the original string:
MsgBox(ReplaceText("(\S+)(\s+)(\S+)", "$3$2$1"))

' Swap pairs of words.

Requirements
Version 5
See Also
Execute Method | Test Method
Applies To: RegExp Object

2001 Microsoft Corporation. All rights reserved.


Build: Topic Version 5.6.9309.1546
Visual Basic Scripting Edition

Test Method
Executes a regular expression search against a specified string and returns a Boolean value that indicates if a pattern match was found.
object.Test(string)

Arguments
object
Required. Always the name of a RegExp object.
string
Required. The text string upon which the regular expression is executed.
Remarks
The actual pattern for the regular expression search is set using the Pattern property of the RegExp object. The RegExp.Global property has no effect on the Test method.
The Test method returns True if a pattern match is found; False if no match is found.
The following code illustrates the use of the Test method.
Function RegExpTest(patrn, strng)
Dim regEx, retVal
' Create variable.
Set regEx = New RegExp
' Create regular expression.
regEx.Pattern = patrn
' Set pattern.
regEx.IgnoreCase = False
' Set case sensitivity.
retVal = regEx.Test(strng)
' Execute the search test.
If retVal Then
RegExpTest = "One or more matches were found."
Else
RegExpTest = "No match was found."
End If
End Function
MsgBox(RegExpTest("is.", "IS1 is2 IS3 is4"))

Requirements
Version 5
See Also
Execute Method | Replace Method
Applies To: RegExp Object

2001 Microsoft Corporation. All rights reserved.


Build: Topic Version 5.6.9309.1546
Visual Basic Scripting Edition

Miscellaneous
In This Section
Character Set (0 - 127)
Character Set (128 - 255)
Locale ID (LCID) Chart
Related Sections
VBScript Langauge Reference

2001 Microsoft Corporation. All rights reserved.


Build: Topic Version 5.6.9309.1546
Visual Basic Scripting Edition

Character Set (0 - 127)


The following table lists 0 - 127.
Code Char Code Char
0
32
[space]
1
33
!
2
34
"
3
35
#
4
36
$
5
37
%
6
38
&
7
39
'
8
** 40
(
9
** 41
)
10
** 42
*
11
43
+
12
44
,
13
** 45
14
46
.
15
47
/
16
48
0
17
49
1
18
50
2
19
51
3
20
52
4
21
53
5
22
54
6
23
55
7
24
56
8
25
57
9
26
58
:
27
59
;
28
60
<
29
61
=
30
62
>
31
63
?

Code
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95

Char Code Char


@ 96
`
A
97
a
B
98
b
C
99
c
D
100 d
E
101 e
F
102 f
G
103 g
H
104 h
I
105 i
J
106 j
K
107 k
L
108 l
M 109 m
N
110 n
O
111 o
P
112 p
Q
113 q
R
114 r
S
115 s
T
116 t
U
117 u
V
118 v
W 119 w
X
120 x
Y
121 y
Z
122 z
[
123 {
\
124 |
]
125 }
^
126 ~
_
127

** Values 8, 9, 10, and 13 convert to backspace, tab, linefeed, and carriage return characters, respectively. They have no graphical representation, but depending on the application, may affect the visual display of text.
Not supported on the current platform.
See Also
Character Set (128 - 255)

2001 Microsoft Corporation. All rights reserved.


Build: Topic Version 5.6.9309.1546
Visual Basic Scripting Edition

Character Set (128 - 255)


The following table lists 128 - 255.
Code Char Code Char
128
160 [space]
129
161
130
162
131
163
132
164
133 165
134
166
135
167
136
168

Code Char Code Char


192
224
193
225
194
226
195
227
196
228
197
229
198
230
199
231
200
231

137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159

'
'
"
"

169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191

201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223

232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254

Not supported on the current platform.


See Also
Character Set (0 - 127)

2001 Microsoft Corporation. All rights reserved.


Build: Topic Version 5.6.9309.1546
Visual Basic Scripting Edition

Locale ID (LCID) Chart


The following table lists Locale IDs (LCID).
Locale Description
Short String
Afrikaans
af
Albanian
sq
Arabic United Arab Emirates ar-ae
Arabic - Bahrain
ar-bh
Arabic - Algeria
ar-dz
Arabic - Egypt
ar-eg
Arabic - Iraq
ar-iq
Arabic - Jordan
ar-jo
Arabic - Kuwait
ar-kw
Arabic - Lebanon
ar-lb
Arabic - Libya
ar-ly
Arabic - Morocco
ar-ma
Arabic - Oman
ar-om
Arabic - Qatar
ar-qa
Arabic - Saudi Arabia
ar-sa
Arabic - Syria
ar-sy
Arabic - Tunisia
ar-tn
Arabic - Yemen
ar-ye
Armenian
hy
Azeri Latin
az-az
Azeri Cyrillic
az-az
Basque
eu
Belarusian
be
Bulgarian
bg
Catalan
ca
Chinese - China
zh-cn
Chinese - Hong Kong S.A.R. zh-hk
Chinese Macau S.A.R
zh-mo
Chinese - Singapore
zh-sg
Chinese - Taiwan
zh-tw
Croatian
hr
Czech
cs
Danish
da
Dutch The Netherlands
nl-nl
Dutch - Belgium
nl-be
English - Australia
en-au
English - Belize
en-bz
English - Canada
en-ca
English Carribbean
en-cb
English - Ireland
en-ie
English - Jamaica
en-jm
English - New Zealand
en-nz
English Phillippines
en-ph
English - South Africa
en-za
English - Trinidad
en-tt
English - United Kingdom
en-gb
English - United States
en-us
Estonian
et
Farsi
fa
Finnish
fi
Faroese
fo
French - France
fr-fr
French - Belgium
fr-be
French - Canada
fr-ca
French - Luxembourg
fr-lu
French - Switzerland
fr-ch

Hex Value
0x0436
0x041C
0x3801
0x3C01
0x1401
0x0C01
0x0801
0x2C01
0x3401
0x3001
0x1001
0x1801
0x2001
0x4001
0x0401
0x2801
0x1C01
0x2401
0x042B
0x042C
0x082C
0x042D
0x0423
0x0402
0x0403
0x0804
0x0C04
0x1404
0x1004
0x0404
0x041A
0x0405
0x0406
0x0413
0x0813
0x0C09
0x2809
0x1009
0x2409
0x1809
0x2009
0x1409
0x3409
0x1C09
0x2C09
0x0809
0x0409
0x0425
0x0429
0x040B
0x0438
0x040C
0x080C
0x0C0C
0x140C
0x100C

Decimal Value
1078
1052
14337
15361
5121
3073
2049
11265
13313
12289
4097
6145
8193
16385
1025
10241
7169
9217
1067
1068
2092
1069
1059
1026
1027
2052
3076
5124
4100
1028
1050
1029
1030
1043
2067
3081
10249
4105
9225
6153
8201
5129
13321
7177
11273
2057
1033
1061
1065
1035
1080
1036
2060
3084
5132
4108

Locale Description
Icelandic
Indonesian
Italian - Italy
Italian - Switzerland
Japanese
Korean
Latvian
Lithuanian
FYRO Macedonian
Malay - Malaysia
Malay Brunei
Maltese
Marathi
Norwegian - Bokml
Norwegian Nynorsk
Polish
Portuguese - Portugal
Portuguese - Brazil
Raeto-Romance
Romanian - Romania
Romanian - Moldova
Russian
Russian - Moldova
Sanskrit
Serbian - Cyrillic
Serbian Latin
Setsuana
Slovenian
Slovak
Sorbian
Spanish - Spain
Spanish - Argentina
Spanish - Bolivia
Spanish - Chile
Spanish - Colombia
Spanish - Costa Rica
Spanish - Dominican Republic
Spanish - Ecuador
Spanish - Guatemala
Spanish - Honduras
Spanish - Mexico
Spanish - Nicaragua
Spanish - Panama
Spanish - Peru
Spanish - Puerto Rico
Spanish - Paraguay
Spanish - El Salvador
Spanish - Uruguay
Spanish - Venezuela
Sutu
Swahili
Swedish - Sweden
Swedish - Finland
Tamil
Tatar
Thai

Short String
is
id
it-it
it-ch
ja
ko
lv
lt
mk
ms-my
ms-bn
mt
mr
no-no
no-no
pl
pt-pt
pt-br
rm
ro
ro-mo
ru
ru-mo
sa
sr-sp
sr-sp
tn
sl
sk
sb
es-es
es-ar
es-bo
es-cl
es-co
es-cr
es-do
es-ec
es-gt
es-hn
es-mx
es-ni
es-pa
es-pe
es-pr
es-py
es-sv
es-uy
es-ve
sx
sw
sv-se
sv-fi
ta
tt
th

Hex Value
0x040F
0x0421
0x0410
0x0810
0x0411
0x0412
0x0426
0x0427
0x042F
0x043E
0x083E
0x043A
0x044E
0x0414
0x0814
0x0415
0x0816
0x0416
0x0417
0x0418
0x0818
0x0419
0x0819
0x044F
0x0C1A
0x081A
0x0432
0x0424
0x041B
0x042E
0x0C0A
0x2C0A
0x400A
0x340A
0x240A
0x140A
0x1C0A
0x300A
0x100A
0x480A
0x080A
0x4C0A
0x180A
0x280A
0x500A
0x3C0A
0x440A
0x380A
0x200A
0x0430
0x0441
0x041D
0x081D
0x0449
0X0444
0x041E

Decimal Value
1039
1057
1040
2064
1041
1042
1062
1063
1071
1086
2110
1082
1102
1044
2068
1045
2070
1046
1047
1048
2072
1049
2073
1103
3098
2074
1074
1060
1051
1070
1034
11274
16394
13322
9226
5130
7178
12298
4106
18442
2058
19466
6154
10250
20490
15370
17418
14346
8202
1072
1089
1053
2077
1097
1092
1054

Gaelic Ireland
Gaelic - Scotland
German - Germany
German - Austria
German - Liechtenstein
German - Luxembourg
German - Switzerland
Greek
Hebrew
Hindi
Hungarian

gd-ie
gd
de-de
de-at
de-li
de-lu
de-ch
el
he
hi
hu

0x083C
0x043C
0x0407
0x0C07
0x1407
0x1007
0x0807
0x0408
0x040D
0x0439
0x040E

2108
1084
1031
3079
5127
4103
2055
1032
1037
1081
1038

Turkish
Tsonga
Ukrainian
Urdu
Uzbek Cyrillic
Uzbek Latin
Vietnamese
Xhosa
Yiddish
Zulu

tr
ts
uk
ur
uz-uz
uz-uz
vi
xh
yi
zu

0x041F
0x0431
0x0422
0x0420
0x0843
0x0443
0x042A
0x0434
0x043D
0x0435

1055
1073
1058
1056
2115
1091
1066
1076
1085
1077

2001 Microsoft Corporation. All rights reserved.


Build: Topic Version 5.6.9309.1546
Visual Basic Scripting Edition

Objects and Collections


In This Section
Class Object
Err Object
Matches Collection
Match Object
Regular Expression (RegExp) Object
SubMatches Collection
Related Sections
VBScript Langauge Reference

2001 Microsoft Corporation. All rights reserved.


Build: Topic Version 5.6.9309.1546
Visual Basic Scripting Edition

Class Object
The object created using the Class statement. Provides access to the events of the class.
Remarks
You cannot explicitly declare a variable to be of type Class. In the VBScript context, the term "class object" refers to any object defined using the VBScript Class statement.
Once you have created a class definition using the Class statement, you can create an instance of the class using the following form:
Dim X
Set X = New classname

Because VBScript is a late-bound language, you cannot do any of the following:


Dim X as New classname

-orDim X
X = New classname

-orSet X = New Scripting.FileSystemObject

Events
Class Object Events
Requirements
Version 5
See Also
Class Statement | Dim Statement | Set Statement

2001 Microsoft Corporation. All rights reserved.


Build: Topic Version 5.6.9309.1546
Visual Basic Scripting Edition

Class Object Events


The Class object provides access to the events of the class.
Events
Initialize Event
Terminate Event

2001 Microsoft Corporation. All rights reserved.


Build: Topic Version 5.6.9309.1546
Visual Basic Scripting Edition

Matches Collection
Collection of regular expression Match objects.
Remarks
A Matches collection contains individual Match objects, and can be only created using the Execute method of the RegExp object. The Matches collection's one property is read-only, as are the individual Match object
properties.
When a regular expression is executed, zero or more Match objects can result. Each Match object provides access to the string found by the regular expression, the length of the string, and an index to where the match was
found.
The following code illustrates how to obtain a Matches collection from a regular expression search and how to iterate the collection:
Function RegExpTest(patrn, strng)
Dim regEx, Match, Matches
' Create variable.
Set regEx = New RegExp
' Create regular expression.
regEx.Pattern = patrn
' Set pattern.
regEx.IgnoreCase = True
' Set case insensitivity.
regEx.Global = True
' Set global applicability.
Set Matches = regEx.Execute(strng)
' Execute search.
For Each Match in Matches
' Iterate Matches collection.
RetStr = RetStr & "Match found at position "
RetStr = RetStr & Match.FirstIndex & ". Match Value is '"
RetStr = RetStr & Match.Value & "'." & vbCRLF
Next
RegExpTest = RetStr
End Function
MsgBox(RegExpTest("is.", "IS1 is2 IS3 is4"))

Requirements
Version 1
See Also
For Each...Next Statement | Match Object | RegExp Object | SubMatches Collection

2001 Microsoft Corporation. All rights reserved.


Build: Topic Version 5.6.9309.1546
Visual Basic Scripting Edition

Err Object
Contains information about run-time errors. Accepts the Raise and Clear methods for generating and clearing run-time errors.
Remarks
The Err object is an intrinsic object with global scope there is no need to create an instance of it in your code. The properties of the Err object are set by the generator of an error Visual Basic, an Automation object, or the
VBScript programmer.
The default property of the Err object is Number. Err.Number contains an integer and can be used by an Automation object to return an SCODE.
When a run-time error occurs, the properties of the Err object are filled with information that uniquely identifies the error and information that can be used to handle it. To generate a run-time error in your code, use the Raise
method.
The Err object's properties are reset to zero or zero-length strings ("") after an On Error Resume Next statement. The Clear method can be used to explicitly reset Err.
The following example illustrates use of the Err object:
On Error Resume Next
Err.Raise 6
' Raise an overflow error.
MsgBox ("Error # " & CStr(Err.Number) & " " & Err.Description)
Err.Clear
' Clear the error.

Properties and Methods


Err Object Properties and Methods
Requirements
Version 1
See Also
On Error Statement

2001 Microsoft Corporation. All rights reserved.


Build: Topic Version 5.6.9309.1546
Visual Basic Scripting Edition

Err Object Properties and Methods


The Err object contains information about run-time errors.
Properties
Description Property

HelpContext Property
HelpFile Property
Number Property
Source Property
Methods
Clear Method
Raise Method

2001 Microsoft Corporation. All rights reserved.


Build: Topic Version 5.6.9309.1546
Visual Basic Scripting Edition

Match Object
Provides access to the read-only properties of a regular expression match.
Remarks
A Match object can be only created using the Execute method of the RegExp object, which actually returns a collection of Match objects. All Match object properties are read-only.
When a regular expression is executed, zero or more Match objects can result. Each Match object provides access to the string found by the regular expression, the length of the string, and an index to where the match was
found.
The following code illustrates the use of the Match object:
Function RegExpTest(patrn, strng)
Dim regEx, Match, Matches
' Create variable.
Set regEx = New RegExp
' Create regular expression.
regEx.Pattern = patrn
' Set pattern.
regEx.IgnoreCase = True
' Set case insensitivity.
regEx.Global = True
' Set global applicability.
Set Matches = regEx.Execute(strng)
' Execute search.
For Each Match in Matches
' Iterate Matches collection.
RetStr = RetStr & "Match " & I & " found at position "
RetStr = RetStr & Match.FirstIndex & ". Match Value is "'
RetStr = RetStr & Match.Value & "'." & vbCRLF
Next
RegExpTest = RetStr
End Function
MsgBox(RegExpTest("is.", "IS1 is2 IS3 is4"))

Properties
Match Object Properties
Requirements
Version 5
See Also
Matches Collection | RegExp Object | SubMatches Colleciton

2001 Microsoft Corporation. All rights reserved.


Build: Topic Version 5.6.9309.1546
Visual Basic Scripting Edition

Match Object Properties


The Match object provides access to the read-only properties of a regular expression match.
Properties
FirstIndex Property
Length Property
Value Property

2001 Microsoft Corporation. All rights reserved.


Build: Topic Version 5.6.9309.1546
Visual Basic Scripting Edition

Regular Expression (RegExp) Object


Provides simple regular expression support.
Remarks
The following code illustrates the use of the RegExp object.
Function RegExpTest(patrn, strng)
Dim regEx, Match, Matches
' Create variable.
Set regEx = New RegExp
' Create a regular expression.
regEx.Pattern = patrn
' Set pattern.
regEx.IgnoreCase = True
' Set case insensitivity.
regEx.Global = True
' Set global applicability.
Set Matches = regEx.Execute(strng)
' Execute search.

For Each Match in Matches


' Iterate Matches collection.
RetStr = RetStr & "Match found at position "
RetStr = RetStr & Match.FirstIndex & ". Match Value is '"
RetStr = RetStr & Match.Value & "'." & vbCRLF
Next
RegExpTest = RetStr
End Function
MsgBox(RegExpTest("is.", "IS1 is2 IS3 is4"))

Properties and Methods


Regular Expression Object Properties and Methods
Requirements
Version 5
See Also
Match Object | Matches Collection

2001 Microsoft Corporation. All rights reserved.


Build: Topic Version 5.6.9309.1546
Visual Basic Scripting Edition

Regular Expression Object Properties and Methods


The Regular Expression object provides simple regular expression support.
Properties
Global Property
IgnoreCase Property
Pattern Property
Methods
Execute Method
Replace Method
Test Method

2001 Microsoft Corporation. All rights reserved.


Build: Topic Version 5.6.9309.1546
Visual Basic Scripting Edition

SubMatches Collection
Collection of regular expression submatch strings.
Remarks
A SubMatches collection contains individual submatch strings, and can only be created using the Execute method of the RegExp object. The SubMatches collection's properties are read-only
When a regular expression is executed, zero or more submatches can result when subexpressions are enclosed in capturing parentheses. Each item in the SubMatches collection is the string found and captured by the regular
expression.
The following code illustrates how to obtain a SubMatches collection from a regular expression search and how to access its individual members:
Function SubMatchTest(inpStr)
Dim oRe, oMatch, oMatches
Set oRe = New RegExp
' Look for an e-mail address (not a perfect RegExp)
oRe.Pattern = "(\w+)@(\w+)\.(\w+)"
' Get the Matches collection
Set oMatches = oRe.Execute(inpStr)
' Get the first item in the Matches collection
Set oMatch = oMatches(0)
' Create the results string.
' The Match object is the entire match - dragon@xyzzy.com
retStr = "Email address is: " & oMatch & vbNewline
' Get the sub-matched parts of the address.
retStr = retStr & "Email alias is: " & oMatch.SubMatches(0) ' dragon
retStr = retStr & vbNewline
retStr = retStr & "Organization is: " & oMatch. SubMatches(1)' xyzzy
SubMatchTest = retStr
End Function
MsgBox(SubMatchTest("Please send mail to dragon@xyzzy.com. Thanks!"))

Requirements
Version 5.5
See Also
For Each...Next Statement | Match Object | Matches Collection |RegExp Object

2001 Microsoft Corporation. All rights reserved.


Build: Topic Version 5.6.9309.1546
Visual Basic Scripting Edition

Operators
In This Section
Operator Precedence
Operator Summary
Arithmetic Operators
Comparison Operators
Concatenation Operators
Logical Operators
Related Sections
VBScript Langauge Reference

2001 Microsoft Corporation. All rights reserved.


Build: Topic Version 5.6.9309.1546
Visual Basic Scripting Edition

Operator Precedence
When several operations occur in an expression, each part is evaluated and resolved in a predetermined order called operator precedence. Parentheses can be used to override the order of precedence and force some parts of an
expression to be evaluated before other parts. Operations within parentheses are always performed before those outside. Within parentheses, however, normal operator precedence is maintained.
When expressions contain operators from more than one category, arithmetic operators are evaluated first, comparison operators are evaluated next, and logical operators are evaluated last. Comparison operators all have equal
precedence; that is, they are evaluated in the left-to-right order in which they appear. Arithmetic and logical operators are evaluated in the following order of precedence:
Arithmetic
Comparison
Negation (-)
Equality (=)
Exponentiation (^)
Inequality (<>)
Multiplication and division (*, /) Less than (<)
Integer division (\)
Greater than (>)
Modulus arithmetic (Mod)
Less than or equal to (<=)
Addition and subtraction (+, -) Greater than or equal to (>=)
String concatenation (&)
Is

Logical
Not
And
Or
Xor
Eqv
Imp
&

When multiplication and division occur together in an expression, each operation is evaluated as it occurs from left to right. Likewise, when addition and subtraction occur together in an expression, each operation is evaluated in
order of appearance from left to right.
The string concatenation operator (&) is not an arithmetic operator, but in precedence it does fall after all arithmetic operators and before all comparison operators. The Is operator is an object reference comparison operator. It
does not compare objects or their values; it checks only to determine if two object references refer to the same object.
Requirements
Version 1
See Also
Is Operator | Operator Summary

2001 Microsoft Corporation. All rights reserved.


Build: Topic Version 5.6.9309.1546
Visual Basic Scripting Edition

Operator Summary
Arithmetic Operators
Operators used to perform mathematical calculations.
Assignment Operator
Operator used to assign a value to a property or variable.
Comparison Operators
Operators used to perform comparisons.
Concatenation Operators
Operators used to combine strings.
Logical Operators
Operators used to perform logical operations.
See Also
Operator Precedence

2001 Microsoft Corporation. All rights reserved.


Build: Topic Version 5.6.9309.1546
Visual Basic Scripting Edition

Addition Operator (+)


Sums two numbers.
result = expression1 + expression2

Arguments
result
Any numeric variable.
expression1
Any expression.
expression2
Any expression.
Remarks
Although you can also use the + operator to concatenate two character strings, you should use the & operator for concatenation to eliminate ambiguity and provide self-documenting code.
When you use the + operator, you may not be able to determine whether addition or string concatenation will occur.
The underlying subtype of the expressions determines the behavior of the + operator in the following way:
If
Then
Both expressions are numeric
Add.
Both expressions are strings
Concatenate.
One expression is numeric and the other is a string Add.
If one or both expressions are Null expressions, result is Null. If both expressions are Empty, result is an Integer subtype. However, if only one expression is Empty, the other expression is returned unchanged as result.
Requirements
Version 1
See Also
& Operator | - Operator | Arithmetic Operators | Concatenation Operators | Operator Precedence | Operator Summary

2001 Microsoft Corporation. All rights reserved.


Build: Topic Version 5.6.9309.1546
Visual Basic Scripting Edition

And Operator
Performs a logical conjunction on two expressions.
result = expression1 And expression2

Arguments
result
Any numeric variable.
expression1
Any expression.
expression2
Any expression.
Remarks
If, and only if, both expressions evaluate to True, result is True. If either expression evaluates to False, result is False. The following table illustrates how result is determined:
If expression1 is
True
True
True
False
False
False
Null
Null
Null

And expression2 is
The result is
True
True
False
False
Null
Null
True
False
False
False
Null
False
True
Null
False
False
Null
Null

The And operator also performs a bitwise comparison of identically positioned bits in two numeric expressions and sets the corresponding bit in result according to the following table:

0
0
1
1

If bit in expression1 is And bit in expression2 is


0
0
1
0
0
0
1
1

The result is

Requirements
Version 1
See Also
Logical Operators | Not Operator | Operator Precedence | Operator Summary | Or Operator | Xor Operator

2001 Microsoft Corporation. All rights reserved.


Build: Topic Version 5.6.9309.1546
Visual Basic Scripting Edition

Assignment Operator (=)


Assigns a value to a variable or property.
variable = value

Arguments
variable

Any variable or any writable property.


value
Any numeric or string literal, constant, or expression.
Remarks
The name on the left side of the equal sign can be a simple scalar variable or an element of an array. Properties on the left side of the equal sign can only be those properties that are writable at run time.
Requirements
Version 1
See Also
Comparison Operators | Operator Precedence | Operator Summary | Set Statement

2001 Microsoft Corporation. All rights reserved.


Build: Topic Version 5.6.9309.1546
Visual Basic Scripting Edition

Concatenation Operator (&)


Forces string concatenation of two expressions.
result = expression1 & expression2

Arguments
result
Any variable.
expression1
Any expression.
expression2
Any expression.
Remarks
Whenever an expression is not a string, it is converted to a String subtype. If both expressions are Null, result is also Null. However, if only one expression is Null, that expression is treated as a zero-length string ("") when
concatenated with the other expression. Any expression that is Empty is also treated as a zero-length string.
Requirements
Version 1
See Also
Concatenation Operators | Operator Precedence | Operator Summary

2001 Microsoft Corporation. All rights reserved.


Build: Topic Version 5.6.9309.1546
Visual Basic Scripting Edition

Division Operator (/)


Divides two numbers and returns a floating-point result.
result = number1/number2

Arguments
result
Any numeric variable.
number1
Any numeric expression.
number2
Any numeric expression.
Remarks
If one or both expressions are Null expressions, result is Null. Any expression that is Empty is treated as 0.
Requirements
Version 1
See Also
* Operator | \ Operator | Arithmetic Operators | Operator Precedence | Operator Summary

2001 Microsoft Corporation. All rights reserved.


Build: Topic Version 5.6.9309.1546
Visual Basic Scripting Edition

Eqv Operator
Performs a logical equivalence on two expressions.
result = expression1 Eqv expression2

Arguments

result
Any numeric variable.
expression1
Any expression.
expression2
Any expression.
Remarks
If either expression is Null, result is also Null. When neither expression is Null, result is determined according to the following table:
If expression1 is
True
True
False
False

And expression2 is
The result is
True
True
False
False
True
False
False
True

The Eqv operator performs a bitwise comparison of identically positioned bits in two numeric expressions and sets the corresponding bit in result according to the following table:

0
0
1
1

If bit in expression1 is And bit in expression2 is


0
1
1
0
0
0
1
1

The result is

Requirements
Version 1
See Also
Imp Operator | Logical Operators | Operator Precedence | Operator Summary

2001 Microsoft Corporation. All rights reserved.


Build: Topic Version 5.6.9309.1546
Visual Basic Scripting Edition

Exponentiation Operator (^)


Raises a number to the power of an exponent.
result = number^exponent

Arguments
result
Any numeric variable.
number
Any numeric expression.
exponent
Any numeric expression.
Remarks
Number can be negative only if exponent is an integer value. When more than one exponentiation is performed in a single expression, the ^ operator is evaluated as it is encountered from left to right.
If either number or exponent is a Null expression, result is also Null.
Requirements
Version 1
See Also
Arithmetic Operators | Operator Precedence | Operator Summary

2001 Microsoft Corporation. All rights reserved.


Build: Topic Version 5.6.9309.1546
Visual Basic Scripting Edition

Imp Operator
Performs a logical implication on two expressions.
result = expression1 Imp expression2

Arguments
result
Any numeric variable.
expression1
Any expression.
expression2
Any expression.
Remarks
The following table illustrates how result is determined:
If expression1 is
True
True
True
False
False

And expression2 is Then result is


True
True
False
False
Null
Null
True
True
False
True

False
Null
Null
Null

Null
True
False
Null

True
True
Null
Null

The Imp operator performs a bitwise comparison of identically positioned bits in two numeric expressions and sets the corresponding bit in result according to the following table:

0
0
1
1

If bit in expression1 is And bit in expression2 is


0
1
1
1
0
0
1
1

Then result is

Requirements
Version 1
See Also
Eqv Operator | Logical Operators | Operator Precedence | Operator Summary

2001 Microsoft Corporation. All rights reserved.


Build: Topic Version 5.6.9309.1546
Visual Basic Scripting Edition

Integer Division Operator (\)


Divides two numbers and returns an integer result.
result = number1\number2

Arguments
result
Any numeric variable.
number1
Any numeric expression.
number2
Any numeric expression.
Remarks
Before division is performed, numeric expressions are rounded to Byte, Integer, or Long subtype expressions.
If any expression is Null, result is also Null. Any expression that is Empty is treated as 0.
Requirements
Version 1
See Also
* Operator | / Operator | Arithmetic Operators | Operator Precedence | Operator Summary

2001 Microsoft Corporation. All rights reserved.


Build: Topic Version 5.6.9309.1546
Visual Basic Scripting Edition

Is Operator
Compares two object reference variables.
result = object1 Is object2

Arguments
result
Any numeric variable.
object1
Any object name.
object2
Any object name.
Remarks
If object1 and object2 both refer to the same object, result is True; if they do not, result is False. Two variables can be made to refer to the same object in several ways.
In the following example, A has been set to refer to the same object as B:
Set A = B

The following example makes A and B refer to the same object as C:


Set A = C
Set B = C

Requirements
Version 1
See Also
Comparison Operators | Operator Precedence | Operator Summary

2001 Microsoft Corporation. All rights reserved.


Build: Topic Version 5.6.9309.1546
Visual Basic Scripting Edition

Mod Operator
Divides two numbers and returns only the remainder.
result = number1 Mod number2

Arguments
result
Any numeric variable.
number1
Any numeric expression.
number2
Any numeric expression.
Remarks
The modulus, or remainder, operator divides number1 by number2 (rounding floating-point numbers to integers) and returns only the remainder as result. For example, in the following expression, A (which is result) equals 5.
A = 19 Mod 6.7

If any expression is Null, result is also Null. Any expression that is Empty is treated as 0.
Requirements
Version 1
See Also
Arithmetic Operators | Operator Precedence | Operator Summary

2001 Microsoft Corporation. All rights reserved.


Build: Topic Version 5.6.9309.1546
Visual Basic Scripting Edition

Multiplication Operator (*)


Multiplies two numbers.
result = number1*number2

Arguments
result
Any numeric variable.
number1
Any numeric expression.
number2
Any numeric expression.
Remarks
If one or both expressions are Null expressions, result is Null. If an expression is Empty, it is treated as if it were 0.
Requirements
Version 1
See Also
\ Operator | Arithmetic Operators | Operator Precedence | Operator Summary

2001 Microsoft Corporation. All rights reserved.


Build: Topic Version 5.6.9309.1546
Visual Basic Scripting Edition

Not Operator
Performs logical negation on an expression.
result = Not expression

Arguments
result
Any numeric variable.
expression
Any expression.
Remarks
The following table illustrates how result is determined:
If expression is Then result is
True
False
False
True
Null
Null
In addition, the Not operator inverts the bit values of any variable and sets the corresponding bit in result according to the following table:

Bit in expression Bit in result


0
1
1
0
Requirements
Version 1
See Also
And Operator | Logical Operators | Operator Precedence | Operator Summary | Or Operator | Xor Operator

2001 Microsoft Corporation. All rights reserved.


Build: Topic Version 5.6.9309.1546
Visual Basic Scripting Edition

Or Operator
Performs a logical disjunction on two expressions.
result = expression1 Or expression2

Arguments
result
Any numeric variable.
expression1
Any expression.
expression2
Any expression.
Remarks
If either or both expressions evaluate to True, result is True. The following table illustrates how result is determined:
If expression1 is
True
True
True
False
False
False
Null
Null
Null

And expression2 is Then result is


True
True
False
True
Null
True
True
True
False
False
Null
Null
True
True
False
Null
Null
Null

The Or operator also performs a bitwise comparison of identically positioned bits in two numeric expressions and sets the corresponding bit in result according to the following table:

0
0
1
1

If bit in expression1 is And bit in expression2 is


0
0
1
1
0
1
1
1

Then result is

Requirements
Version 1
See Also
And Operator | Logical Operators | Not Operator | Operator Precedence | Operator Summary | Xor Operator

2001 Microsoft Corporation. All rights reserved.


Build: Topic Version 5.6.9309.1546
Visual Basic Scripting Edition

Subtraction Operator (-)


Finds the difference between two numbers or indicates the negative value of a numeric expression.
Syntax 1
result = number1-number2

Syntax 2
-number

Arguments
result
Any numeric variable.
number
Any numeric expression.
number1
Any numeric expression.
number2
Any numeric expression.
Remarks
In Syntax 1, the - operator is the arithmetic subtraction operator used to find the difference between two numbers. In Syntax 2, the - operator is used as the unary negation operator to indicate the negative value of an expression.
If one or both expressions are Null expressions, result is Null. If an expression is Empty, it is treated as if it were 0.

Requirements
Version 1
See Also
+ Operator | Arithmetic Operators | Operator Precedence | Operator Summary

2001 Microsoft Corporation. All rights reserved.


Build: Topic Version 5.6.9309.1546
Visual Basic Scripting Edition

Xor Operator
Performs a logical exclusion on two expressions.
result = expression1 Xor expression2

Arguments
result
Any numeric variable.
expression1
Any expression.
expression2
Any expression.
Remarks
If one, and only one, of the expressions evaluates to True, result is True. However, if either expression is Null, result is also Null. When neither expression is Null, result is determined according to the following table:
If expression1 is
True
True
False
False

And expression2 is Then result is


True
False
False
True
True
True
False
False

The Xor operator also performs a bitwise comparison of identically positioned bits in two numeric expressions and sets the corresponding bit in result according to the following table:

0
0
1
1

If bit in expression1 is And bit in expression2 is


0
0
1
1
0
1
1
0

Then result is

Requirements
Version 1
See Also
And Operator | Logical Operators | Not Operator | Operator Precedence | Operator Summary | Or Operator

2001 Microsoft Corporation. All rights reserved.


Build: Topic Version 5.6.9309.1546
Visual Basic Scripting Edition

Arithmetic Operators
^ Operator
* Operator
/ Operator
\ Operator
Mod Operator
+ Operator
- Operator
Concatenation Operators

2001 Microsoft Corporation. All rights reserved.


Build: Topic Version 5.6.9309.1546
Visual Basic Scripting Edition

Comparison Operators
Used to compare expressions.
result = expression1 comparisonoperator expression2
result = object1 Is object2

Parts
result
Any numeric variable.

expression
Any expression.
comparisonoperator
Any comparison operator.
object
Any object name.
Remarks
The Is operator has specific comparison functionality that differs from the operators in the following table. The following table contains a list of the comparison operators and the conditions that determine whether result is True,
False, or Null:
Operator
<
<=
>
>=
=
<>

Description
Less than
Less than or equal to
Greater than
Greater than or equal to
Equal to
Not equal to

True if
expression1 < expression2
expression1 <= expression2
expression1 > expression2
expression1 >= expression2
expression1 = expression2
expression1 <> expression2

False if
expression1 >= expression2
expression1 > expression2
expression1 <= expression2
expression1 < expression2
expression1 <> expression2
expression1 = expression2

Null if
expression1 or expression2 = Null
expression1 or expression2 = Null
expression1 or expression2 = Null
expression1 or expression2 = Null
expression1 or expression2 = Null
expression1 or expression2 = Null

When comparing two expressions, you may not be able to easily determine whether the expressions are being compared as numbers or as strings.
The following table shows how expressions are compared or what results from the comparison, depending on the underlying subtype:
If
Both expressions are numeric
Both expressions are strings
One expression is numeric and the other is a string
One expression is Empty and the other is numeric
One expression is Empty and the other is a string
Both expressions are Empty

Then
Perform a numeric comparison.
Perform a string comparison.
The numeric expression is less than the string expression.
Perform a numeric comparison, using 0 as the Empty expression.
Perform a string comparison, using a zero-length string ("") as the Empty expression.
The expressions are equal.

Requirements
Version 1
See Also
= Operator | Is Operator | Operator Precedence | Operator Summary

2001 Microsoft Corporation. All rights reserved.


Build: Topic Version 5.6.9309.1546
Visual Basic Scripting Edition

Concatenation Operators
& Operator
+ Operator

2001 Microsoft Corporation. All rights reserved.


Build: Topic Version 5.6.9309.1546
Visual Basic Scripting Edition

Logical Operators
And Operator
Not Operator
Or Operator
Xor Operator

2001 Microsoft Corporation. All rights reserved.


Build: Topic Version 5.6.9309.1546
Visual Basic Scripting Edition

Properties
In This Section
Description Property
FirstIndex Property
Global Property
HelpContext Property
HelpFile Property
IgnoreCase Property
Length Property
Number Property
Pattern Property

Source Property
Value Property
Related Sections
VBScript Langauge Reference

2001 Microsoft Corporation. All rights reserved.


Build: Topic Version 5.6.9309.1546
Visual Basic Scripting Edition

Description Property
Returns or sets a descriptive string associated with an error.
object.Description [= stringexpression]

Arguments
object
Always the Err object.
stringexpression
A string expression containing a description of the error.
Remarks
The Description property consists of a short description of the error. Use this property to alert the user to an error that you can't or don't want to handle. When generating a user-defined error, assign a short description of your
error to this property. If Description isn't filled in, and the value of Number corresponds to a VBScript run-time error, the descriptive string associated with the error is returned.
On Error Resume Next
Err.Raise 6
' Raise an overflow error.
MsgBox ("Error # " & CStr(Err.Number) & " " & Err.Description)
Err.Clear
' Clear the error.

Requirements
Version 1
See Also
Err Object | HelpContext Property | HelpFile Property | Number Property | Source Property
Applies To: Err Object

2001 Microsoft Corporation. All rights reserved.


Build: Topic Version 5.6.9309.1546
Visual Basic Scripting Edition

FirstIndex Property
Returns the position in a search string where a match occurs.
object.FirstIndex

The object argument is always a Match object.


Remarks
The FirstIndex property uses a zero-based offset from the beginning of the search string. In other words, the first character in the string is identified as character zero (0). The following code illustrates the use of the FirstIndex
property.
Function RegExpTest(patrn, strng)
Dim regEx, Match, Matches
' Create variable.
Set regEx = New RegExp
' Create regular expression.
regEx.Pattern = patrn
' Set pattern.
regEx.IgnoreCase = True
' Set case insensitivity.
regEx.Global = True
' Set global applicability.
Set Matches = regEx.Execute(strng)
' Execute search.
For Each Match in Matches
' Iterate Matches collection.
RetStr = RetStr & "Match " & I & " found at position "
RetStr = RetStr & Match.FirstIndex & ". Match Value is "'
RetStr = RetStr & Match.Value & "'." & vbCRLF
Next
RegExpTest = RetStr
End Function
MsgBox(RegExpTest("is.", "IS1 is2 IS3 is4"))

Requirements
Version 5
See Also
Length Property | Value Property
Applies To: Match Object

2001 Microsoft Corporation. All rights reserved.


Build: Topic Version 5.6.9309.1546
Visual Basic Scripting Edition

Global Property

Sets or returns a Boolean value that indicates if a pattern should match all occurrences in an entire search string or just the first one.
object.Global [= True | False ]

The object argument is always a RegExp object. The value of the Global property is True if the search applies to the entire string, False if it does not. Default is False.
Remarks
The following code illustrates the use of the Global property (change the value assigned to Global property to see its effect):
Function RegExpTest(patrn, strng)
Dim regEx, Match, Matches
' Create variable.
Set regEx = New RegExp
' Create a regular expression.
regEx.Pattern = patrn
' Set pattern.
regEx.IgnoreCase = True
' Set case insensitivity.
regEx.Global = True
' Set global applicability.
Set Matches = regEx.Execute(strng)
' Execute search.
For Each Match in Matches
' Iterate Matches collection.
RetStr = RetStr & "Match found at position "
RetStr = RetStr & Match.FirstIndex & ". Match Value is '"
RetStr = RetStr & Match.Value & "'." & vbCRLF
Next
RegExpTest = RetStr
End Function
MsgBox(RegExpTest("is.", "IS1 is2 IS3 is4"))

Requirements
Version 5
See Also
IgnoreCase Property | Pattern Property
Applies To: RegExp Object

2001 Microsoft Corporation. All rights reserved.


Build: Topic Version 5.6.9309.1546
Visual Basic Scripting Edition

HelpContext Property
Sets or returns a context ID for a topic in a Help File.
object.HelpContext [= contextID]

Arguments
object
Required. Always the Err object.
contextID
Optional. A valid identifier for a Help topic within the Help file.
Remarks
If a Help file is specified in HelpFile, the HelpContext property is used to automatically display the Help topic identified. If both HelpFile and HelpContext are empty, the value of the Number property is checked. If it
corresponds to a VBScript run-time error value, then the VBScript Help context ID for the error is used. If the Number property doesn't correspond to a VBScript error, the contents screen for the VBScript Help file is displayed.
The following example illustrates use of the HelpContext property:
On Error Resume Next
Dim Msg
Err.Clear
Err.Raise 6
' Generate "Overflow" error.
Err.Helpfile = "yourHelp.hlp"
Err.HelpContext = yourContextID
If Err.Number <> 0 Then
Msg = "Press F1 or Help to see " & Err.Helpfile & " topic for" & _
" the following HelpContext: " & Err.HelpContext
MsgBox Msg, , "error: " & Err.Description, Err.Helpfile, Err.HelpContext
End If

Requirements
Version 2
See Also
Description Property | HelpFile Property | Number Property | Source Property
Applies To: Err Object

2001 Microsoft Corporation. All rights reserved.


Build: Topic Version 5.6.9309.1546
Visual Basic Scripting Edition

HelpFile Property
Sets or returns a fully qualified path to a Help File.
object.HelpFile [= contextID]

Arguments
object
Required. Always the Err object.
contextID
Optional. Fully qualified path to the Help file.
Remarks

If a Help file is specified in HelpFile, it is automatically called when the user clicks the Help button (or presses the F1 key) in the error message dialog box. If the HelpContext property contains a valid context ID for the
specified file, that topic is automatically displayed. If no HelpFile is specified, the VBScript Help file is displayed.
On Error Resume Next
Dim Msg
Err.Clear
Err.Raise 6
' Generate "Overflow" error.
Err.Helpfile = "yourHelp.hlp"
Err.HelpContext = yourContextID
If Err.Number <> 0 Then
Msg = "Press F1 or Help to see " & Err.Helpfile & " topic for" & _
" the following HelpContext: " & Err.HelpContext
MsgBox Msg, , "error: " & Err.Description, Err.Helpfile, Err.HelpContext
End If

Requirements
Version 2
See Also
Description Property | HelpContext Property | Number Property | Source Property
Applies To: Err Object

2001 Microsoft Corporation. All rights reserved.


Build: Topic Version 5.6.9309.1546
Visual Basic Scripting Edition

IgnoreCase Property
Sets or returns a Boolean value that indicates if a pattern search is case-sensitive or not.
object.IgnoreCase [= True | False ]

The object argument is always a RegExp object. The value of the IgnoreCase property is False if the search is case-sensitive, True if it is not. Default is False.
Remarks
The following code illustrates the use of the IgnoreCase property (change the value assigned to IgnoreCase property to see its effect):
Function RegExpTest(patrn, strng)
Dim regEx, Match, Matches
' Create variable.
Set regEx = New RegExp
' Create a regular expression.
regEx.Pattern = patrn
' Set pattern.
regEx.IgnoreCase = True
' Set case insensitivity.
regEx.Global = True
' Set global applicability.
Set Matches = regEx.Execute(strng)
' Execute search.
For Each Match in Matches
' Iterate Matches collection.
RetStr = RetStr & "Match found at position "
RetStr = RetStr & Match.FirstIndex & ". Match Value is '"
RetStr = RetStr & Match.Value & "'." & vbCRLF
Next
RegExpTest = RetStr
End Function
MsgBox(RegExpTest("is.", "IS1 is2 IS3 is4"))

Requirements
Version 5
See Also
Global Property | Pattern Property
Applies To: RegExp Object

2001 Microsoft Corporation. All rights reserved.


Build: Topic Version 5.6.9309.1546
Visual Basic Scripting Edition

Length Property
Returns the length of a match found in a search string.
object.Length

The object argument is always a Match object.


Remarks
The following code illustrates the use of the Length property:
Function RegExpTest(patrn, strng)
Dim regEx, Match, Matches
' Create variable.
Set regEx = New RegExp
' Create regular expression.
regEx.Pattern = patrn
' Set pattern.
regEx.IgnoreCase = True
' Set case insensitivity.
regEx.Global = True
' Set global applicability.
Set Matches = regEx.Execute(strng)
' Execute search.
For Each Match in Matches
' Iterate Matches collection.
RetStr = RetStr & "Match " & I & " found at position "
RetStr = RetStr & Match.FirstIndex & ". Match Length is "
RetStr = RetStr & Match.Length
RetStr = RetStr & " characters." & vbCRLF
Next
RegExpTest = RetStr
End Function
MsgBox(RegExpTest("is.", "IS1 is2 IS3 is4"))

Requirements
Version 5

See Also
FirstIndex Property | Value Property
Applies To: Match Object

2001 Microsoft Corporation. All rights reserved.


Build: Topic Version 5.6.9309.1546
Visual Basic Scripting Edition

Number Property
Returns or sets a numeric value specifying an error. Number is the Err object's default property.
object.Number [= errornumber]

Arguments
object
Always the Err object.
errornumber
An integer representing a VBScript error number or an SCODE error value.
Remarks
When returning a user-defined error from an Automation object, set Err.Number by adding the number you selected as an error code to the constant vbObjectError.
The following code illustrates the use of the Number property.
On Error Resume Next
Err.Raise vbObjectError + 1, "SomeObject"
' Raise Object Error #1.
MsgBox ("Error # " & CStr(Err.Number) & " " & Err.Description)
Err.Clear
' Clear the error.

Requirements
Version 1
See Also
Description Property | HelpContext Property | HelpFile Property | Err Object | Source Property
Applies To: Err Object

2001 Microsoft Corporation. All rights reserved.


Build: Topic Version 5.6.9309.1546
Visual Basic Scripting Edition

Pattern Property
Sets or returns the regular expression pattern being searched for.
object.Pattern [= "searchstring"]

Arguments
object
Required. Always a RegExp object variable.
searchstring
Optional. Regular string expression being searched for. May include any of the regular expression characters defined in the table in the Settings section.
Settings
Special characters and sequences are used in writing patterns for regular expressions. The following table describes and gives an example of the characters and sequences that can be used.
Character
\
^
$
*
+
?
.
(pattern)
x|y
{n}
{n,}
{n,m}
[xyz]
[^xyz]
[a-z]
[^m-z]
\b
\B
\d
\D
\f
\n
\r
\s
\S
\t

Description
Marks the next character as either a special character or a literal. For example, "n" matches the character "n". "\n" matches a newline character. The sequence "\\" matches "\" and
"\(" matches "(".
Matches the beginning of input.
Matches the end of input.
Matches the preceding character zero or more times. For example, "zo*" matches either "z" or "zoo".
Matches the preceding character one or more times. For example, "zo+" matches "zoo" but not "z".
Matches the preceding character zero or one time. For example, "a?ve?" matches the "ve" in "never".
Matches any single character except a newline character.
Matches pattern and remembers the match. The matched substring can be retrieved from the resulting Matches collection, using Item [0]...[n]. To match parentheses characters ( ),
use "\(" or "\)".
Matches either x or y. For example, "z|wood" matches "z" or "wood". "(z|w)oo" matches "zoo" or "wood".
n is a nonnegative integer. Matches exactly n times. For example, "o{2}" does not match the "o" in "Bob," but matches the first two o's in "foooood".
n is a nonnegative integer. Matches at least n times. For example, "o{2,}" does not match the "o" in "Bob" and matches all the o's in "foooood." "o{1,}" is equivalent to "o+". "o
{0,}" is equivalent to "o*".
m and n are nonnegative integers. Matches at least n and at most m times. For example, "o{1,3}" matches the first three o's in "fooooood." "o{0,1}" is equivalent to "o?".
A character set. Matches any one of the enclosed characters. For example, "[abc]" matches the "a" in "plain".
A negative character set. Matches any character not enclosed. For example, "[^abc]" matches the "p" in "plain".
A range of characters. Matches any character in the specified range. For example, "[a-z]" matches any lowercase alphabetic character in the range "a" through "z".
A negative range characters. Matches any character not in the specified range. For example, "[m-z]" matches any character not in the range "m" through "z".
Matches a word boundary, that is, the position between a word and a space. For example, "er\b" matches the "er" in "never" but not the "er" in "verb".
Matches a non-word boundary. "ea*r\B" matches the "ear" in "never early".
Matches a digit character. Equivalent to [0-9].
Matches a non-digit character. Equivalent to [^0-9].
Matches a form-feed character.
Matches a newline character.
Matches a carriage return character.
Matches any white space including space, tab, form-feed, etc. Equivalent to "[ \f\n\r\t\v]".
Matches any nonwhite space character. Equivalent to "[^ \f\n\r\t\v]".
Matches a tab character.

\v
\w
\W
\num
\n
\xn

Matches a vertical tab character.


Matches any word character including underscore. Equivalent to "[A-Za-z0-9_]".
Matches any non-word character. Equivalent to "[^A-Za-z0-9_]".
Matches num, where num is a positive integer. A reference back to remembered matches. For example, "(.)\1" matches two consecutive identical characters.
Matches n, where n is an octal escape value. Octal escape values must be 1, 2, or 3 digits long. For example, "\11" and "\011" both match a tab character. "\0011" is the equivalent
of "\001" & "1". Octal escape values must not exceed 256. If they do, only the first two digits comprise the expression. Allows ASCII codes to be used in regular expressions.
Matches n, where n is a hexadecimal escape value. Hexadecimal escape values must be exactly two digits long. For example, "\x41" matches "A". "\x041" is equivalent to "\x04"
& "1". Allows ASCII codes to be used in regular expressions.

Remarks
The following code illustrates the use of the Pattern property.
Function RegExpTest(patrn, strng)
Dim regEx, Match, Matches
' Create variable.
Set regEx = New RegExp
' Create a regular expression.
regEx.Pattern = patrn
' Set pattern.
regEx.IgnoreCase = True
' Set case insensitivity.
regEx.Global = True
' Set global applicability.
Set Matches = regEx.Execute(strng)
' Execute search.
For Each Match in Matches
' Iterate Matches collection.
RetStr = RetStr & "Match found at position "
RetStr = RetStr & Match.FirstIndex & ". Match Value is '"
RetStr = RetStr & Match.Value & "'." & vbCRLF
Next
RegExpTest = RetStr
End Function
MsgBox(RegExpTest("is.", "IS1 is2 IS3 is4"))

Requirements
Version 2
See Also
Global Property | IgnoreCase Property
Applies To: RegExp Object

2001 Microsoft Corporation. All rights reserved.


Build: Topic Version 5.6.9309.1546
Visual Basic Scripting Edition

Source Property
Returns or sets the name of the object or application that originally generated the error.
object.Source [= stringexpression]

Arguments
object
Always the Err object.
stringexpression
A string expression representing the application that generated the error.
Remarks
The Source property specifies a string expression that is usually the class name or programmatic ID of the object that caused the error. Use Source to provide your users with information when your code is unable to handle an
error generated in an accessed object. For example, if you access Microsoft Excel and it generates a Division by zero error, Microsoft Excel sets Err.Number to its error code for that error and sets Source to Excel.Application.
Note that if the error is generated in another object called by Microsoft Excel, Excel intercepts the error and sets Err.Number to its own code for Division by zero. However, it leaves the other Err object (including Source) as
set by the object that generated the error.
Source always contains the name of the object that originally generated the error your code can try to handle the error according to the error documentation of the object you accessed. If your error handler fails, you can use
the Err object information to describe the error to your user, using Source and the other Err to inform the user which object originally caused the error, its description of the error, and so forth.
When generating an error from code, Source is your application's programmatic ID.
The following code illustrates use of the Source property.
On Error Resume Next
Err.Raise 6
' Raise an overflow error.
MsgBox ("Error # " & CStr(Err.Number) & " " & Err.Description & Err.Source)
Err.Clear
' Clear the error.

Requirements
Version 1
See Also
Description Property | Err Object | HelpContext Property | HelpFile Property | Number Property | On Error Statement
Applies To: Err Object

2001 Microsoft Corporation. All rights reserved.


Build: Topic Version 5.6.9309.1546
Visual Basic Scripting Edition

Value Property
Returns the value or text of a match found in a search string.
object.Value

The object argument is always a Match object.


Remarks

The following code illustrates the use of the Value property.


Function RegExpTest(patrn, strng)
Dim regEx, Match, Matches
' Create variable.
Set regEx = New RegExp
' Create regular expression.
regEx.Pattern = patrn
' Set pattern.
regEx.IgnoreCase = True
' Set case insensitivity.
regEx.Global = True
' Set global applicability.
Set Matches = regEx.Execute(strng)
' Execute search.
For Each Match in Matches
' Iterate Matches collection.
RetStr = RetStr & "Match " & I & " found at position "
RetStr = RetStr & Match.FirstIndex & ". Match Value is "'
RetStr = RetStr & Match.Value & "'." & vbCRLF
Next
RegExpTest = RetStr
End Function
MsgBox(RegExpTest("is.", "IS1 is2 IS3 is4"))

Requirements
Version 1
See Also
FirstIndex Property | Length Property
Applies To: Match Object

2001 Microsoft Corporation. All rights reserved.


Build: Topic Version 5.6.9309.1546
Visual Basic Scripting Edition

Statements
In This Section
Call Statement
Class Statement
Const Statement
Dim Statement
Do...Loop Statement
Erase Statement
Execute Statement
ExecuteGlobal Statement
Exit Statement
For Each...Next Statement
For...Next Statement
Function Statement
If...Then...Else Statement
On Error Statement
Option Explicit Statement
Private Statement
Property Get Statement
Property Let Statement
Property Set Statement
Public Statement
Randomize Statement
ReDim Statement
Rem Statement
Select Case Statement
Set Statement
Sub Statement
While...Wend Statement
With Statement
Related Sections
VBScript Langauge Reference

2001 Microsoft Corporation. All rights reserved.


Build: Topic Version 5.6.9309.1546
Visual Basic Scripting Edition

Call Statement
Transfers control to a Sub or Function procedure.
[Call] name [argumentlist]

Arguments
Call
Optional keyword. If specified, you must enclose argumentlist in parentheses. For example:
Call MyProc(0)
name
Required. Name of the procedure to call.
argumentlist
Optional. Comma-delimited list of variables, arrays, or expressions to pass to the procedure.
Remarks
You are not required to use the Call keyword when calling a procedure. However, if you use the Call keyword to call a procedure that requires arguments, argumentlist must be enclosed in parentheses. If you omit the Call
keyword, you also must omit the parentheses around argumentlist. If you use either Call syntax to call any intrinsic or user-defined function, the function's return value is discarded.
Call MyFunction("Hello World")
Function MyFunction(text)
MsgBox text
End Function

Requirements
Version 1

2001 Microsoft Corporation. All rights reserved.


Build: Topic Version 5.6.9309.1546
Visual Basic Scripting Edition

Class Statement
Declares the name of a class, as well as a definition of the variables, properties, and methods that comprise the class.
Class name
statements
End Class

Arguments
name
Required. Name of the Class; follows standard variable naming conventions.
statements
Required. One or more statements that define the variables, properties, and methods of the Class.
Remarks
Within a Class block, members are declared as either Private or Public using the appropriate declaration statements. Anything declared as Private is visible only within the Class block. Anything declared as Public is visible
within the Class block, as well as by code outside the Class block. Anything not explicitly declared as either Private or Public is Public by default. Procedures (either Sub or Function) declared Public within the class block
become methods of the class. Public variables serve as properties of the class, as do properties explicitly declared using Property Get, Property Let, and Property Set. Default properties and methods for the class are specified
in their declarations using the Default keyword. See the individual declaration statement topics for information on how this keyword is used.
Requirements
Version 5
See Also
Dim Statement | Function Statement | Private Statement | Property Get Statement | Property Let Statement | Property Set Statement | Public Statement | Set Statement | Sub Statement

2001 Microsoft Corporation. All rights reserved.


Build: Topic Version 5.6.9309.1546
Visual Basic Scripting Edition

Const Statement
Declares constants for use in place of literal values.
[Public | Private] Const constname = expression

Arguments
Public
Optional. Keyword used at script level to declare constants that are available to all procedures in all scripts. Not allowed in procedures.
Private
Optional. Keyword used at script level to declare constants that are available only within the script where the declaration is made. Not allowed in procedures.
constname
Required. Name of the constant; follows standard variable naming conventions.
expression
Required. Literal or other constant, or any combination that includes all arithmetic or logical operators except Is.
Remarks
Constants are public by default. Within procedures, constants are always private; their visibility can't be changed. Within a script, the default visibility of a script-level constant can be changed using the Private keyword.
To combine several constant declarations on the same line, separate each constant assignment with a comma. When constant declarations are combined in this way, the Public or Private keyword, if used, applies to all of them.
You can't use variables, user-defined functions, or intrinsic VBScript functions (such as Chr) in constant declarations. By definition, they can't be constants. You also can't create a constant from any expression that involves an
operator, that is, only simple constants are allowed. Constants declared in a Sub or Function procedure are local to that procedure. A constant declared outside a procedure is defined throughout the script in which it is declared.
You can use constants anywhere you can use an expression. The following code illustrates the use of the Const statement:

Const MyVar = 459


' Constants are Public by default.
Private Const MyString = "HELP"
' Declare Private constant.
Const MyStr = "Hello", MyNumber = 3.4567
' Declare multiple constants on same line.

Note Constants can make your scripts self-documenting and easy to modify. Unlike variables, constants cannot be inadvertently changed while your script is running.
Requirements
Version 5
See Also
Dim Statement | Function Statement | Private Statement | Public Statement | Sub Statement

2001 Microsoft Corporation. All rights reserved.


Build: Topic Version 5.6.9309.1546
Visual Basic Scripting Edition

Dim Statement
Declares variables and allocates storage space.
Dim varname[([subscripts])][, varname[([subscripts])]] . . .

Arguments
varname
Name of the variable; follows standard variable naming conventions.
subscripts
Dimensions of an array variable; up to 60 multiple dimensions may be declared. The subscripts argument uses the following syntax:
upperbound [,upperbound] . . .
The lower bound of an array is always zero.
Remarks
Variables declared with Dim at the script level are available to all procedures within the script. At the procedure level, variables are available only within the procedure.
You can also use the Dim statement with empty parentheses to declare a dynamic array. After declaring a dynamic array, use the ReDim statement within a procedure to define the number of dimensions and elements in the
array. If you try to redeclare a dimension for an array variable whose size was explicitly specified in a Dim statement, an error occurs.
Note When you use the Dim statement in a procedure, you generally put the Dim statement at the beginning of the procedure.
The following examples illustrate the use of the Dim statement:
Dim Names(9)
Dim Names()
Dim MyVar, MyNum

' Declare an array with 10 elements.


' Declare a dynamic array.
' Declare two variables.

Requirements
Version 1
See Also
Private Statement | Public Statement | ReDim Statement | Set Statement

2001 Microsoft Corporation. All rights reserved.


Build: Topic Version 5.6.9309.1546
Visual Basic Scripting Edition

Do...Loop Statement
Repeats a block of statements while a condition is True or until a condition becomes True.
Do [{While | Until} condition]
statements]
[
Exit
[ Do]
statements]
[
Loop

Or, you can use this syntax:


Do
statements]
[
Exit
[ Do]
statements]
[
Loop [{While | Until} condition]

Arguments
condition
Numeric or string expression that is True or False. If condition is Null, condition is treated as False.
statements
One or more statements that are repeated while or until condition is True.
Remarks
The Exit Do can only be used within a Do...Loop control structure to provide an alternate way to exit a Do...Loop. Any number of Exit Do statements may be placed anywhere in the Do...Loop. Often used with the evaluation
of some condition (for example, If...Then), Exit Do transfers control to the statement immediately following the Loop.
When used within nested Do...Loop statements, Exit Do transfers control to the loop that is nested one level above the loop where it occurs.
The following examples illustrate use of the Do...Loop statement:
Do Until DefResp = vbNo
MyNum = Int (6 * Rnd + 1)
' Generate a random integer between 1 and 6.
DefResp = MsgBox (MyNum & " Do you want another number?", vbYesNo)

Loop
Dim Check, Counter
Check = True: Counter = 0
' Initialize variables.
Do
' Outer loop.
Do While Counter < 20
' Inner loop.
Counter = Counter + 1
' Increment Counter.
If Counter = 10 Then
' If condition is True...
Check = False
' set value of flag to False.
Exit Do
' Exit inner loop.
End If
Loop
Loop Until Check = False
' Exit outer loop immediately.

Requirements
Version 1
See Also
Exit Statement | For...Next Statement | While...Wend Statement

2001 Microsoft Corporation. All rights reserved.


Build: Topic Version 5.6.9309.1546
Visual Basic Scripting Edition

Erase Statement
Reinitializes the elements of fixed-size arrays and deallocates dynamic-array storage space.
Erase array

The array argument is the name of the array variable to be erased.


Remarks
It is important to know whether an array is fixed-size (ordinary) or dynamic because Erase behaves differently depending on the type of array. Erase recovers no memory for fixed-size arrays. Erase sets the elements of a fixed
array as follows:
Type of array
Fixed numeric array
Fixed string array
Array of objects

Effect of Erase on fixed-array elements


Sets each element to zero.
Sets each element to zero-length ("").
Sets each element to the special value Nothing.

Erase frees the memory used by dynamic arrays. Before your program can refer to the dynamic array again, it must redeclare the array variable's dimensions using a ReDim statement.
The following example illustrates the use of the Erase statement.
Dim NumArray(9)
Dim DynamicArray()
ReDim DynamicArray(9)
' Allocate storage space.
Erase NumArray
' Each element is reinitialized.
Erase DynamicArray
' Free memory used by array.

Requirements
Version 1
See Also
Dim Statement | Nothing | ReDim Statement

2001 Microsoft Corporation. All rights reserved.


Build: Topic Version 5.6.9309.1546
Visual Basic Scripting Edition

Execute Statement
Executes one or more specified statements.
Execute statement

The required statement argument is a string expression containing one or more statements for execution. Include multiple statements in the statement argument, using colons or embedded line breaks to separate them.
Remarks
In VBScript, x = y can be interpreted two ways. The first is as an assignment statement, where the value of y is assigned to x. The second interpretation is as an expression that tests if x and y have the same value. If they do,
result is True; if they are not, result is False. The Execute statement always uses the first interpretation, whereas the Eval method always uses the second.
Note In Microsoft JScript, no confusion exists between assignment and comparison, because the assignment operator (=) is different from the comparison operator(==).
The context in which the Execute statement is invoked determines what objects and variables are available to the code being run. In-scope objects and variables are available to code running in an Execute statement. However, it
is important to understand that if you execute code that creates a procedure, that procedure does not inherit the scope of the procedure in which it occurred.
Like any procedure, the new procedure's scope is global, and it inherits everything in the global scope. Unlike any other procedure, its context is not global scope, so it can only be executed in the context of the procedure where
the Execute statement occurred. However, if the same Execute statement is invoked outside of a procedure (i.e., in global scope), not only does it inherit everything in global scope, but it can also be called from anywhere, since
its context is global. The following example illustrates this behavior:
Dim X
' Declare X in global scope.
X = "Global"
' Assign global X a value.
Sub Proc1
' Declare procedure.
Dim X
' Declare X in local scope.
X = "Local"
' Assign local X a value.
' The Execute statement here creates a
' procedure that, when invoked, prints X.
' It print the global X because Proc2
' inherits everything in global scope.
Execute "Sub Proc2: Print X: End Sub"
Print Eval("X")
' Print local X.
Proc2
' Invoke Proc2 in Proc1's scope.
End Sub

Proc2

' This line causes an error since


' Proc2 is unavailable outside Proc1.
Proc1
' Invoke Proc1.
Execute "Sub Proc2: Print X: End Sub"
Proc2
' This invocation succeeds because Proc2
' is now available globally.

The following example shows how the Execute statement can be rewritten so you don't have to enclose the entire procedure in the quotation marks:
S = "Sub Proc2" & vbCrLf
S = S & "
Print X" & vbCrLf
S = S & "End Sub"
Execute S

Requirements
Version 1
See Also
Eval Function | ExecuteGlobal Statement

2001 Microsoft Corporation. All rights reserved.


Build: Topic Version 5.6.9309.1546
Visual Basic Scripting Edition

ExecuteGlobal Statement
Executes one or more specified statements in the global namespace of a script.
ExecuteGlobal statement

The required statement argument is a string expression containing one or more statements for execution. Include multiple statements in the statement argument, using colons or embedded line breaks to separate them.
Remarks
In VBScript, x = y can be interpreted two ways. The first is as an assignment statement, where the value of y is assigned to x. The second interpretation is as an expression that tests if x and y have the same value. If they do,
result is True; if they are not, result is False. The ExecuteGlobal statement always uses the first interpretation, whereas the Eval method always uses the second.
Note In Microsoft JScript, no confusion exists between assignment and comparison, because the assignment operator (=) is different from the comparison operator.
All statements used with ExecuteGlobal are executed in the script's global namespace. This allows code to be added to the program so that any procedure can access it. For example, a VBScript Class statement can be executed
at run time and functions can subsequently create new instances of the class.
Adding procedures and classes at runtime can be useful, but also introduces the possibility of overwriting existing global variable and functions at runtime. Because this can cause significant programming problems, care should
be exercised when using the ExecuteGlobal statement. If you don't need access to a variable or function outside of a procedure, use the Execute statement that will only affect the namespace of the calling function.
The following example illustrates the use of the ExecuteGlobal statement:
Dim X
' Declare X in global scope.
X = "Global"
' Assign global X a value.
Sub Proc1
' Declare procedure.
Dim X
' Declare X in local scope.
X = "Local"
' Assign local X a value.
' The Execute statement here creates a
' procedure that, when invoked, prints X.
' It print the global X because Proc2
' inherits everything in global scope.
ExecuteGlobal "Sub Proc2: Print X: End Sub"
Print Eval("X")
' Print local X.
Proc2
' Invoke Proc2 in Global scope resulting
' in "Global" being printed.
End Sub
Proc2
' This line causes an error since
' Proc2 is unavailable outside Proc1.
Proc1
' Invoke Proc1.
Execute "Sub Proc2: Print X: End Sub"
Proc2
' This invocation succeeds because Proc2
' is now available globally.

The following example shows how the ExecuteGlobal statement can be rewritten so you don't have to enclose the entire procedure in the quotation marks:
S = "Sub Proc2" & vbCrLf
S = S & " Print X" & vbCrLf
S = S & "End Sub"
ExecuteGlobal S

Requirements
Version 1

2001 Microsoft Corporation. All rights reserved.


Build: Topic Version 5.6.9309.1546
Visual Basic Scripting Edition

Exit Statement
Exits a block of Do...Loop, For...Next, Function, or Sub code.
Exit
Exit
Exit
Exit
Exit

Do
For
Function
Property
Sub

The Exit statement syntax has these forms:


Statement
Exit Do
Exit For

Description
Provides a way to exit a Do...Loop statement. It can be used only inside a Do...Loop statement. Exit Do transfers control to the statement following the Loop statement. When
used within nested Do...Loop statements, Exit Do transfers control to the loop that is one nested level above the loop where it occurs.
Provides a way to exit a For loop. It can be used only in a For...Next or For Each...Next loop. Exit For transfers control to the statement following the Next statement. When
used within nested For loops, Exit For transfers control to the loop that is one nested level above the loop where it occurs.

Exit Function
Exit Property
Exit Sub

Immediately exits the Function procedure in which it appears. Execution continues with the statement following the statement that called the Function.
Immediately exits the Property procedure in which it appears. Execution continues with the statement following the statement that called the Property procedure.
Immediately exits the Sub procedure in which it appears. Execution continues with the statement following the statement that called the Sub.

The following example illustrates the use of the Exit statement:


Sub RandomLoop
Dim I, MyNum
Do
' Set up infinite loop.
For I = 1 To 1000
' Loop 1000 times.
MyNum = Int(Rnd * 100)
' Generate random numbers.
Select Case MyNum
' Evaluate random number.
Case 17: MsgBox "Case 17"
Exit For
' If 17, exit For...Next.
Case 29: MsgBox "Case 29"
Exit Do
' If 29, exit Do...Loop.
Case 54: MsgBox "Case 54"
Exit Sub
' If 54, exit Sub procedure.
End Select
Next
Loop
End Sub

Requirements
Version 1
See Also
Do...Loop Statement | For Each...Next Statement | For...Next Statement | Function Statement | Sub Statement

2001 Microsoft Corporation. All rights reserved.


Build: Topic Version 5.6.9309.1546
Visual Basic Scripting Edition

For Each...Next Statement


Repeats a group of statements for each element in an array or collection.
For Each element In group
statements]
[
Exit
[ For]
statements]
[
Next [element]

Arguments
element
Variable used to iterate through the elements of the collection or array. For collections, element can only be a Variant variable, a generic Object variable, or any specific Automation object variable. For arrays, element
can only be a Variant variable.
group
Name of an object collection or array.
statements
One or more statements that are executed on each item in group.
Remarks
The For Each block is entered if there is at least one element in group. Once the loop has been entered, all the statements in the loop are executed for the first element in group. As long as there are more elements in group, the
statements in the loop continue to execute for each element. When there are no more elements in group, the loop is exited and execution continues with the statement following the Next statement.
The Exit For can only be used within a For Each...Next or For...Next control structure to provide an alternate way to exit. Any number of Exit For statements may be placed anywhere in the loop. The Exit For is often used
with the evaluation of some condition (for example, If...Then), and transfers control to the statement immediately following Next.
You can nest For Each...Next loops by placing one For Each...Next loop within another. However, each loop element must be unique.
Note If you omit element in a Next statement, execution continues as if you had included it. If a Next statement is encountered before it's corresponding For statement, an error occurs.
The following example illustrates use of the For Each...Next statement:
Function ShowFolderList(folderspec)
Dim fso, f, f1, fc, s
Set fso = CreateObject("Scripting.FileSystemObject")
Set f = fso.GetFolder(folderspec)
Set fc = f.Files
For Each f1 in fc
s = s & f1.name
s = s & "<BR>"
Next
ShowFolderList = s
End Function

Requirements
Version 2
See Also
Do...Loop Statement | Exit Statement | For...Next Statement | While...Wend Statement

2001 Microsoft Corporation. All rights reserved.


Build: Topic Version 5.6.9309.1546
Visual Basic Scripting Edition

For...Next Statement
Repeats a group of statements a specified number of times.
For counter = start To end [Step step]
statements]
[
Exit
[ For]
statements]
[
Next

Arguments
counter
Numeric variable used as a loop counter. The variable can't be an array element or an element of a user-defined type.
start
Initial value of counter.
end
Final value of counter.
step
Amount counter is changed each time through the loop. If not specified, step defaults to one.
statements
One or more statements between For and Next that are executed the specified number of times.
Remarks
The step argument can be either positive or negative. The value of the step argument determines loop processing as follows:
Value
Positive or 0
Negative

Loop executes if
counter <= end
counter >= end

Once the loop starts and all statements in the loop have executed, step is added to counter. At this point, either the statements in the loop execute again (based on the same test that caused the loop to execute initially), or the loop
is exited and execution continues with the statement following the Next statement.
Note Changing the value of counter while inside a loop can make it more difficult to read and debug your code.
Exit For can only be used within a For Each...Next or For...Next control structure to provide an alternate way to exit. Any number of Exit For statements may be placed anywhere in the loop. Exit For is often used with the
evaluation of some condition (for example, If...Then), and transfers control to the statement immediately following Next.
You can nest For...Next loops by placing one For...Next loop within another. Give each loop a unique variable name as its counter. The following construction is correct:
For I = 1 To 10
For J = 1 To 10
For K = 1 To 10
. . .
Next
Next
Next

Requirements
Version 1
See Also
Do...Loop Statement | Exit Statement | For Each...Next Statement | While...Wend Statement

2001 Microsoft Corporation. All rights reserved.


Build: Topic Version 5.6.9309.1546
Visual Basic Scripting Edition

Function Statement
Declares the name, arguments, and code that form the body of a Function procedure.
[Public [Default] | Private] Function name [(arglist)]
statements]
[
name
[ = expression]
Exit
[ Function]
statements]
[
name
[ = expression]
End Function

Arguments
Public
Indicates that the Function procedure is accessible to all other procedures in all scripts.
Default
Used only with the Public keyword in a Class block to indicate that the Function procedure is the default method for the class. An error occurs if more than one Default procedure is specified in a class.
Private
Indicates that the Function procedure is accessible only to other procedures in the script where it is declared or if the function is a member of a class, and that the Function procedure is accessible only to other procedures
in that class.
name
Name of the Function; follows standard variable naming conventions.
arglist
List of variables representing arguments that are passed to the Function procedure when it is called. Commas separate multiple variables.
statements
Any group of statements to be executed within the body of the Function procedure.
expression
Return value of the Function.
The arglist argument has the following syntax and parts:
[ByVal | ByRef] varname[( )]
Arguments
ByVal
Indicates that the argument is passed by value.
ByRef
Indicates that the argument is passed by reference.
varname
Name of the variable representing the argument; follows standard variable naming conventions.
Remarks
If not explicitly specified using either Public or Private, Function procedures are public by default, that is, they are visible to all other procedures in your script. The value of local variables in a Function is not preserved
between calls to the procedure.
You cannot define a Function procedure inside any other procedure (e.g. Sub or Property Get).
The Exit Function statement causes an immediate exit from a Function procedure. Program execution continues with the statement that follows the statement that called the Function procedure. Any number of Exit Function
statements can appear anywhere in a Function procedure.
Like a Sub procedure, a Function procedure is a separate procedure that can take arguments, perform a series of statements, and change the values of its arguments. However, unlike a Sub procedure, you can use a Function

procedure on the right side of an expression in the same way you use any intrinsic function, such as Sqr, Cos, or Chr, when you want to use the value returned by the function.
You call a Function procedure using the function name, followed by the argument list in parentheses, in an expression. See the Call statement for specific information on how to call Function procedures.
Caution

Function
procedures can be recursive, that is, they can call themselves to perform a given task. However, recursion can lead to stack overflow.

To return a value from a function, assign the value to the function name. Any number of such assignments can appear anywhere within the procedure. If no value is assigned to name, the procedure returns a default value: a
numeric function returns 0 and a string function returns a zero-length string (""). A function that returns an object reference returns Nothing if no object reference is assigned to name (using Set) within the Function.
The following example shows how to assign a return value to a function named BinarySearch. In this case, False is assigned to the name to indicate that some value was not found.
Function BinarySearch(. . .)
. . .
' Value not found. Return a value of False.
If lower > upper Then
BinarySearch = False
Exit Function
End If
. . .
End Function

Variables used in Function procedures fall into two categories: those that are explicitly declared within the procedure and those that are not. Variables that are explicitly declared in a procedure (using Dim or the equivalent) are
always local to the procedure. Variables that are used but not explicitly declared in a procedure are also local unless they are explicitly declared at some higher level outside the procedure.
Caution A procedure can use a variable that is not explicitly declared in the procedure, but a naming conflict can occur if anything you have defined at the script level has the same name. If your procedure refers to
an undeclared variable that has the same name as another procedure, constant, or variable, it is assumed that your procedure is referring to that script-level name. To avoid this kind of conflict, use an Option Explicit
statement to force explicit declaration of variables.
Caution VBScript may rearrange arithmetic expressions to increase internal efficiency. Avoid using a Function procedure in an arithmetic expression when the function changes the value of variables in the same
expression.
Requirements
Version 1
See Also
Call Statement | Dim Statement | Exit Statement | Nothing | Set Statement | Sub Statement

2001 Microsoft Corporation. All rights reserved.


Build: Topic Version 5.6.9309.1546
Visual Basic Scripting Edition

If...Then...Else Statement
Conditionally executes a group of statements, depending on the value of an expression.
If condition Then statements [Else elsestatements ]

Or, you can use the block form syntax:


If condition Then
statements]
[
[ElseIf condition-n Then
elseifstatements]]
[
. . .
[Else
elsestatements]]
[
End If

Arguments
condition
One or more of the following two types of expressions:
A numeric or string expression that evaluates to True or False. If condition is Null, condition is treated as False.
An expression of the form TypeOf objectname Is objecttype. The objectname is any object reference and objecttype is any valid object type. The expression is True if objectname is of the object type specified by
objecttype; otherwise it is False.
statements
One or more statements separated by colons; executed if condition is True.
condition-n
Same as condition.
elseifstatements
One or more statements executed if the associated condition-n is True.
elsestatements
One or more statements executed if no previous condition or condition-n expression is True.
Remarks
You can use the single-line form (first syntax) for short, simple tests. However, the block form (second syntax) provides more structure and flexibility than the single-line form and is usually easier to read, maintain, and debug.
Note With the single-line syntax, it is possible to have multiple statements executed as the result of an If...Then decision, but they must all be on the same line and separated by colons, as in the following statement:
If A > 10 Then A = A + 1 : B = B + A : C = C + B

When executing a block If (second syntax), condition is tested. If condition is True, the statements following Then are executed. If condition is False, each ElseIf (if any) is evaluated in turn. When a True condition is found,
the statements following the associated Then are executed. If none of the ElseIf statements are True (or there are no ElseIf clauses), the statements following Else are executed. After executing the statements following Then or
Else, execution continues with the statement following End If.
The Else and ElseIf clauses are both optional. You can have as many ElseIf statements as you want in a block If, but none can appear after the Else clause. Block If statements can be nested; that is, contained within one
another.
What follows the Then keyword is examined to determine whether or not a statement is a block If. If anything other than a comment appears after Then on the same line, the statement is treated as a single-line If statement.
A block If statement must be the first statement on a line. The block If must end with an End If statement.
Requirements
Version 1

2001 Microsoft Corporation. All rights reserved.

Build: Topic Version 5.6.9309.1546


Visual Basic Scripting Edition

On Error Statement
Enables or disables error-handling.
On Error Resume Next
On Error GoTo 0

Remarks
If you don't use an On Error Resume Next statement anywhere in your code, any run-time error that occurs can cause an error message to be displayed and code execution stopped. However, the host running the code
determines the exact behavior. The host can sometimes opt to handle such errors differently. In some cases, the script debugger may be invoked at the point of the error. In still other cases, there may be no apparent indication
that any error occurred because the host does not to notify the user. Again, this is purely a function of how the host handles any errors that occur.
Within any particular procedure, an error is not necessarily fatal as long as error-handling is enabled somewhere along the call stack. If local error-handling is not enabled in a procedure and an error occurs, control is passed back
through the call stack until a procedure with error-handling enabled is found and the error is handled at that point. If no procedure in the call stack is found to have error-handling enabled, an error message is displayed at that
point and execution stops or the host handles the error as appropriate.
On Error Resume Next causes execution to continue with the statement immediately following the statement that caused the run-time error, or with the statement immediately following the most recent call out of the procedure
containing the On Error Resume Next statement. This allows execution to continue despite a run-time error. You can then build the error-handling routine inline within the procedure.
An On Error Resume Next statement becomes inactive when another procedure is called, so you should execute an On Error Resume Next statement in each called routine if you want inline error handling within that routine.
When a procedure is exited, the error-handling capability reverts to whatever error-handling was in place before entering the exited procedure.
Use On Error GoTo 0 to disable error handling if you have previously enabled it using On Error Resume Next.
The following example illustrates use of the On Error Resume Next statement.
On Error Resume Next
Err.Raise 6
' Raise an overflow error.
MsgBox "Error # " & CStr(Err.Number) & " " & Err.Description
Err.Clear
' Clear the error.

Requirements
Version 1
See Also
Err Object | Exit Statement

2001 Microsoft Corporation. All rights reserved.


Build: Topic Version 5.6.9309.1546
Visual Basic Scripting Edition

Option Explicit Statement


Forces explicit declaration of all variables in a script.
Option Explicit

Remarks
If used, the Option Explicit statement must appear in a script before any other statements.
When you use the Option Explicit statement, you must explicitly declare all variables using the Dim, Private, Public, or ReDim statements. If you attempt to use an undeclared variable name, an error occurs.
Tip Use Option Explicit to avoid incorrectly typing the name of an existing variable or to avoid confusion in code where the scope of the variable is not clear.
The following example illustrates use of the Option Explicit statement.
Option Explicit
' Force explicit variable declaration.
Dim MyVar
' Declare variable.
MyInt = 10
' Undeclared variable generates error.
MyVar = 10
' Declared variable does not generate error.

Requirements
Version 1

2001 Microsoft Corporation. All rights reserved.


Build: Topic Version 5.6.9309.1546
Visual Basic Scripting Edition

Private Statement
Declares private variables and allocates storage space. Declares, in a Class block, a private variable.
Private varname[([subscripts])][, varname[([subscripts])]] . . .

Arguments
varname
Name of the variable; follows standard variable naming conventions.
subscripts
Dimensions of an array variable; up to 60 multiple dimensions may be declared. The subscripts argument uses the following syntax:
upper [, upper] . . .
The lower bound of an array is always zero.
Remarks
Private statement variables are available only to the script in which they are declared.

A variable that refers to an object must be assigned an existing object using the Set statement before it can be used. Until it is assigned an object, the declared object variable is initialized as Empty.
You can also use the Private statement with empty parentheses to declare a dynamic array. After declaring a dynamic array, use the ReDim statement within a procedure to define the number of dimensions and elements in the
array. If you try to redeclare a dimension for an array variable whose size was explicitly specified in a Private, Public, or Dim statement, an error occurs.
Note When you use the Private statement in a procedure, you generally put the Private statement at the beginning of the procedure.
The following example illustrates use of the Private statement.
Private MyNumber
' Private Variant variable.
Private MyArray(9)
' Private array variable.
' Multiple Private declarations of Variant variables.
Private MyNumber, MyVar, YourNumber

Requirements
Version 1
See Also
Dim Statement | Public Statement | ReDim Statement | Set Statement

2001 Microsoft Corporation. All rights reserved.


Build: Topic Version 5.6.9309.1546
Visual Basic Scripting Edition

Property Get Statement


Declares, in a Class block, the name, arguments, and code that form the body of a Property procedure that gets (returns) the value of a property.
[Public [Default] | Private] Property Get name [(arglist)]
statements]
[
Set]
[[ name = expression]
Exit
[ Property]
statements]
[
Set]
[[ name = expression]
End Property

Arguments
Public
Indicates that the Property Get procedure is accessible to all other procedures in all scripts.
Default
Used only with the Public keyword to indicate that the property defined in the Property Get procedure is the default property for the class.
Private
Indicates that the Property Get procedure is accessible only to other procedures in the Class block where it's declared.
name
Name of the Property Get procedure; follows standard variable naming conventions, except that the name can be the same as a Property Let or Property Set procedure in the same Class block.
arglist
List of variables representing arguments that are passed to the Property Get procedure when it is called. Commas separate multiple arguments. The name of each argument in a Property Get procedure must be the same
as the corresponding argument in a Property Let procedure (if one exists).
statements
Any group of statements to be executed within the body of the Property Get procedure.
Set
Keyword used when assigning an object as the return value of a Property Get procedure.
expression
Return value of the Property Get procedure.
Remarks
If not explicitly specified using either Public or Private, Property Get procedures are public by default, that is, they are visible to all other procedures in your script. The value of local variables in a Property Get procedure is
not preserved between calls to the procedure.
You can't define a Property Get procedure inside any other procedure (e.g. Function or Property Let).
The Exit Property statement causes an immediate exit from a Property Get procedure. Program execution continues with the statement that follows the statement that called the Property Get procedure. Any number of Exit
Property statements can appear anywhere in a Property Get procedure.
Like a Sub and Property Let procedure, a Property Get procedure is a separate procedure that can take arguments, perform a series of statements, and change the value of its arguments. However, unlike a Sub and Property
Let, you can use a Property Get procedure on the right side of an expression in the same way you use a Function or property name when you want to return the value of a property.
Requirements
Version 5
See Also
Class Statement | Dim Statement | Exit Statement | Function Statement | Private Statement | Property Let Statement | Property Set Statement | Public Statement | Set Statement | Sub Statement

2001 Microsoft Corporation. All rights reserved.


Build: Topic Version 5.6.9309.1546
Visual Basic Scripting Edition

Property Let Statement


Declares, in a Class block, the name, arguments, and code that form the body of a Property procedure that assigns (sets) the value of a property.
[Public | Private] Property Let name ([arglist,] value)
statements]
[
Exit
[ Property]
statements]
[
End Property

Arguments
Public
Indicates that the Property Let procedure is accessible to all other procedures in all scripts.
Private
Indicates that the Property Let procedure is accessible only to other procedures in the Class block where it's declared.

name
Name of the Property Let procedure; follows standard variable naming conventions, except that the name can be the same as a Property Get or Property Set procedure in the same Class block.
arglist
List of variables representing arguments that are passed to the Property Let procedure when it is called. Commas separate multiple arguments. The name of each argument in a Property Let procedure must be the same as
the corresponding argument in a Property Get procedure. In addition, the Property Let procedure will always have one more argument than its corresponding Property Get procedure. That argument is the value being
assigned to the property.
value
Variable to contain the value to be assigned to the property. When the procedure is called, this argument appears on the right side of the calling expression.
statements
Any group of statements to be executed within the body of the Property Let procedure.
Remarks
If not explicitly specified using either Public or Private, Property Let procedures are public by default, that is, they are visible to all other procedures in your script. The value of local variables in a Property Let procedure is
not preserved between calls to the procedure.
You can't define a Property Let procedure inside any other procedure (e.g. Function or Property Get).
The Exit Property statement causes an immediate exit from a Property Let procedure. Program execution continues with the statement that follows the statement that called the Property Let procedure. Any number of Exit
Property statements can appear anywhere in a Property Let procedure.
Note Every Property Let statement must define at least one argument for the procedure it defines. That argument (or the last argument if there is more than one) contains the actual value to be assigned to the
property when the procedure defined by the Property Let statement is invoked. That argument is referred to as value in the preceding syntax.
Like a Function and Property Get procedure, a Property Let procedure is a separate procedure that can take arguments, perform a series of statements, and change the value of its arguments. However, unlike a Function and
Property Get procedure, both of which return a value, you can only use a Property Let procedure on the left side of a property assignment expression.
Requirements
Version 5
See Also
Class Statement | Dim Statement | Exit Statement | Function Statement | Private Statement | Property Get Statement | Property Set Statement | Public Statement | Set Statement | Sub Statement

2001 Microsoft Corporation. All rights reserved.


Build: Topic Version 5.6.9309.1546
Visual Basic Scripting Edition

Property Set Statement


Declares, in a Class block, the name, arguments, and code that form the body of a Property procedure that sets a reference to an object.
[Public | Private] Property Set name([arglist,] reference)
statements]
[
Exit
[ Property]
statements]
[
End Property

Arguments
Public
Indicates that the Property Set procedure is accessible to all other procedures in all scripts.
Private
Indicates that the Property Set procedure is accessible only to other procedures in the Class block where it's declared.
name
Name of the Property Set procedure; follows standard variable naming conventions, except that the name can be the same as a Property Get or Property Let procedure in the same Class block.
arglist
List of variables representing arguments that are passed to the Property Set procedure when it is called. Commas separate multiple arguments. In addition, the Property Set procedure will always have one more argument
than its corresponding Property Get procedure. That argument is the object being assigned to the property.
reference
Variable containing the object reference used on the right side of the object reference assignment.
statements
Any group of statements to be executed within the body of the Property Set procedure.
Remarks
If not explicitly specified using either Public or Private, Property Set procedures are public by default, that is, they are visible to all other procedures in your script. The value of local variables in a Property Set procedure is
not preserved between calls to the procedure.
You can't define a Property Set procedure inside any other procedure (e.g. Function or Property Let).
The Exit Property statement causes an immediate exit from a Property Set procedure. Program execution continues with the statement that follows the statement that called the Property Set procedure. Any number of Exit
Property statements can appear anywhere in a Property Set procedure.
Note Every Property Set statement must define at least one argument for the procedure it defines. That argument (or the last argument if there is more than one) contains the actual object reference for the property
when the procedure defined by the Property Set statement is invoked. That argument is referred to as reference in the preceding syntax.
Like a Function and Property Get procedure, a Property Set procedure is a separate procedure that can take arguments, perform a series of statements, and change the value of its arguments. However, unlike a Function and
Property Get procedure, both of which return a value, you can only use a Property Set procedure on the left side of an object reference assignment (Set statement).
Requirements
Version 5
See Also
Class Statement | Dim Statement | Exit Statement | Function Statement | Private Statement | Property Get Statement | Property Let Statement | Public Statement | Set Statement | Sub Statement

2001 Microsoft Corporation. All rights reserved.


Build: Topic Version 5.6.9309.1546
Visual Basic Scripting Edition

Public Statement
Declares public variables and allocates storage space. Declares, in a Class block, a private variable.
Public varname[([subscripts])][, varname[([subscripts])]] . . .

Arguments
varname
Name of the variable; follows standard variable naming conventions.
subscripts
Dimensions of an array variable; up to 60 multiple dimensions may be declared. The subscripts argument uses the following syntax:
upper [, upper] . . .
The lower bound of an array is always zero.
Remarks
Public statement variables are available to all procedures in all scripts.
A variable that refers to an object must be assigned an existing object using the Set statement before it can be used. Until it is assigned an object, the declared object variable is initialized as Empty.
You can also use the Public statement with empty parentheses to declare a dynamic array. After declaring a dynamic array, use the ReDim statement within a procedure to define the number of dimensions and elements in the
array. If you try to redeclare a dimension for an array variable whose size was explicitly specified in a Private, Public, or Dim statement, an error occurs.
The following example illustrates the use of the Public statement:
Public MyNumber
' Public Variant variable.
Public MyArray(9)
' Public array variable.
' Multiple Public declarations of Variant variables.
Public MyNumber, MyVar, YourNumber

Requirements
Version 1
See Also
Dim Statement | Private Statement | ReDim Statement | Set Statement

2001 Microsoft Corporation. All rights reserved.


Build: Topic Version 5.6.9309.1546
Visual Basic Scripting Edition

Randomize Statement
Initializes the random-number generator.
Randomize [number]

The number argument can be any valid numeric expression.


Remarks
Randomize uses number to initialize the Rnd function's random-number generator, giving it a new seed value. If you omit number, the value returned by the system timer is used as the new seed value.
If Randomize is not used, the Rnd function (with no arguments) uses the same number as a seed the first time it is called, and thereafter uses the last generated number as a seed value.
Note To repeat sequences of random numbers, call Rnd with a negative argument immediately before using Randomize with a numeric argument. Using Randomize with the same value for number does not
repeat the previous sequence.
The following example illustrates use of the Randomize statement.
Dim MyValue, Response
Randomize
' Initialize random-number generator.
Do Until Response = vbNo
MyValue = Int((6 * Rnd) + 1)
' Generate random value between 1 and 6.
MsgBox MyValue
Response = MsgBox ("Roll again? ", vbYesNo)
Loop

Requirements
Version 1
See Also
Rnd Function | Timer Function

2001 Microsoft Corporation. All rights reserved.


Build: Topic Version 5.6.9309.1546
Visual Basic Scripting Edition

ReDim Statement
Declares dynamic-array variables, and allocates or reallocates storage space at procedure level.
ReDim [Preserve] varname(subscripts) [, varname(subscripts)] . . .

Arguments
Preserve
Preserves the data in an existing array when you change the size of the last dimension.
varname
Name of the variable; follows standard variable naming conventions.
subscripts
Dimensions of an array variable; up to 60 multiple dimensions may be declared. The subscripts argument uses the following syntax:
upper [,upper] . . .
The lower bound of an array is always zero.
Remarks

The ReDim statement is used to size or resize a dynamic array that has already been formally declared using a Private, Public, or Dim statement with empty parentheses (without dimension subscripts). You can use the ReDim
statement repeatedly to change the number of elements and dimensions in an array.
If you use the Preserve keyword, you can resize only the last array dimension, and you can't change the number of dimensions at all. For example, if your array has only one dimension, you can resize that dimension because it
is the last and only dimension. However, if your array has two or more dimensions, you can change the size of only the last dimension and still preserve the contents of the array.
The following example shows how you can increase the size of the last dimension of a dynamic array without erasing any existing data contained in the array.
ReDim X(10, 10, 10)
. . .
ReDim Preserve X(10, 10, 15)

Caution If you make an array smaller than it was originally, data in the eliminated elements is lost.
When variables are initialized, a numeric variable is initialized to 0 and a string variable is initialized to a zero-length string (""). A variable that refers to an object must be assigned an existing object using the Set statement
before it can be used. Until it is assigned an object, the declared object variable has the special value Nothing.
Requirements
Version 1
See Also
Dim Statement | Set Statement

2001 Microsoft Corporation. All rights reserved.


Build: Topic Version 5.6.9309.1546
Visual Basic Scripting Edition

Rem Statement
Includes explanatory remarks in a program.
Rem comment

-or' comment

The comment argument is the text of any comment you want to include. After the Rem keyword, a space is required before comment.
Remarks
As shown in the syntax section, you can use an apostrophe (') instead of the Rem keyword. If the Rem keyword follows other statements on a line, it must be separated from the statements by a colon. However, when you use an
apostrophe, the colon is not required after other statements.
The following example illustrates the use of the Rem statement.
Dim MyStr1, MyStr2
MyStr1 = "Hello" : Rem Comment after a statement separated by a colon.
MyStr2 = "Goodbye" ' This is also a comment; no colon is needed.
Rem Comment on a line with no code; no colon is needed.

Requirements
Version 1

2001 Microsoft Corporation. All rights reserved.


Build: Topic Version 5.6.9309.1546
Visual Basic Scripting Edition

Select Case Statement


Executes one of several groups of statements, depending on the value of an expression.
Select Case testexpression
Case
[ expressionlist-n
statements-n]]
[
. . .
Case
[ Else expressionlist-n
elsestatements-n]]
[
End Select

Arguments
testexpression
Any numeric or string expression.
expressionlist-n
Required if Case appears. Delimited list of one or more expressions.
statements-n
One or more statements executed if testexpression matches any part of expressionlist-n.
elsestatements-n
One or more statements executed if testexpression doesn't match any of the Case clauses.
Remarks
If testexpression matches any Case expressionlist expression, the statements following that Case clause are executed up to the next Case clause, or for the last clause, up to End Select. Control then passes to the statement
following End Select. If testexpression matches an expressionlist expression in more than one Case clause, only the statements following the first match are executed.
The Case Else clause is used to indicate the elsestatements to be executed if no match is found between the testexpression and an expressionlist in any of the other Case selections. Although not required, it is a good idea to have
a Case Else statement in your Select Case block to handle unforeseen testexpression values. If no Case expressionlist matches testexpression and there is no Case Else statement, execution continues at the statement following
End Select.
Select Case statements can be nested. Each nested Select Case statement must have a matching End Select statement.
The following example illustrates the use of the Select Case statement.
Dim Color, MyVar
Sub ChangeBackground (Color)
MyVar = lcase (Color)

Select Case MyVar


Case "red"
Case "green"
Case "blue"
Case Else
End Select
End Sub

document.bgColor = "red"
document.bgColor = "green"
document.bgColor = "blue"
MsgBox "pick another color"

Requirements
Version 1
See Also
If...Then...Else Statement

2001 Microsoft Corporation. All rights reserved.


Build: Topic Version 5.6.9309.1546
Visual Basic Scripting Edition

Set Statement
Assigns an object reference to a variable or property, or associates a procedure reference with an event.
Set objectvar = {objectexpression | New classname | Nothing}

-orSet object.eventname = GetRef(procname)

Parameters
objectvar
Required. Name of the variable or property; follows standard variable naming conventions.
objectexpression
Optional. Expression consisting of the name of an object, another declared variable of the same object type, or a function or method that returns an object of the same object type.
New
Keyword used to create a new instance of a class. If objectvar contained a reference to an object, that reference is released when the new one is assigned. The New keyword can only be used to create an instance of a class.
classname
Optional. Name of the class being created. A class and its members are defined using the Class statement.
Nothing
Optional. Discontinues association of objectvar with any specific object or class. Assigning objectvar to Nothing releases all the system and memory resources associated with the previously referenced object when no
other variable refers to it.
object
Required. Name of the object with which event is associated.
event
Required. Name of the event to which the function is to be bound.
procname
Required. String containing the name of the Sub or Function being associated with the event.
Remarks
To be valid, objectvar must be an object type consistent with the object being assigned to it.
The Dim, Private, Public, or ReDim statements only declare a variable that refers to an object. No actual object is referred to until you use the Set statement to assign a specific object.
Generally, when you use Set to assign an object reference to a variable, no copy of the object is created for that variable. Instead, a reference to the object is created. More than one object variable can refer to the same object.
Because these variables are references to (rather than copies of) the object, any change in the object is reflected in all variables that refer to it.
Function ShowFreeSpace(drvPath)
Dim fso, d, s
Set fso = CreateObject("Scripting.FileSystemObject")
Set d = fso.GetDrive(fso.GetDriveName(drvPath))
s = "Drive " & UCase(drvPath) & " - "
s = s & d.VolumeName & "<BR>"
s = s & "Free Space: " & FormatNumber(d.FreeSpace/1024, 0)
s = s & " Kbytes"
ShowFreeSpace = s
End Function

Using the New keyword allows you to concurrently create an instance of a class and assign it to an object reference variable. The variable to which the instance of the class is being assigned must already have been declared with
the Dim (or equivalent) statement.
Refer to the documentation for the GetRef function for information on using Set to associate a procedure with an event.
Requirements
Version 1
See Also
= Operator | Dim Statement | GetRef Function | ReDim Statement

2001 Microsoft Corporation. All rights reserved.


Build: Topic Version 5.6.9309.1546
Visual Basic Scripting Edition

Sub Statement
Declares the name, arguments, and code that form the body of a Sub procedure.
[Public [Default] | Private] Sub name [(arglist)]
statements]
[
Exit
[ Sub]
statements]
[
End Sub

Arguments
Public

Indicates that the Sub procedure is accessible to all other procedures in all scripts.
Default
Used only with the Public keyword in a Class block to indicate that the Sub procedure is the default method for the class. An error occurs if more than one Default procedure is specified in a class.
Private
Indicates that the Sub procedure is accessible only to other procedures in the script where it is declared.
name
Name of the Sub; follows standard variable naming conventions.
arglist
List of variables representing arguments that are passed to the Sub procedure when it is called. Commas separate multiple variables.
statements
Any group of statements to be executed within the body of the Sub procedure.
The arglist argument has the following syntax and parts:
[ByVal | ByRef] varname[( )]

Arguments
ByVal
Indicates that the argument is passed by value.
ByRef
Indicates that the argument is passed by reference.
varname
Name of the variable representing the argument; follows standard variable naming conventions.
Remarks
If not explicitly specified using either Public or Private, Sub procedures are public by default, that is, they are visible to all other procedures in your script. The value of local variables in a Sub procedure is not preserved
between calls to the procedure.
You can't define a Sub procedure inside any other procedure (e.g. Function or Property Get).
The Exit Sub statement causes an immediate exit from a Sub procedure. Program execution continues with the statement that follows the statement that called the Sub procedure. Any number of Exit Sub statements can appear
anywhere in a Sub procedure.
Like a Function procedure, a Sub procedure is a separate procedure that can take arguments, perform a series of statements, and change the value of its arguments. However, unlike a Function procedure, which returns a value,
a Sub procedure can't be used in an expression.
You call a Sub procedure using the procedure name followed by the argument list. See the Call statement for specific information on how to call Sub procedures.
Caution

Subprocedures can be recursive, that is, they can call themselves to perform a given task. However, recursion can lead to stack overflow.

Variables used in Sub procedures fall into two categories: those that are explicitly declared within the procedure and those that are not. Variables that are explicitly declared in a procedure (using Dim or the equivalent) are
always local to the procedure. Variables that are used but not explicitly declared in a procedure are also local, unless they are explicitly declared at some higher level outside the procedure.
Caution A procedure can use a variable that is not explicitly declared in the procedure, but a naming conflict can occur if anything you have defined at the script level has the same name. If your procedure refers to
an undeclared variable that has the same name as another procedure, constant or variable, it is assumed that your procedure is referring to that script-level name. To avoid this kind of conflict, use an Option Explicit
statement to force explicit declaration of variables.
Requirements
Version 1
See Also
Call Statement | Dim Statement | Exit Statement | Function Statement

2001 Microsoft Corporation. All rights reserved.


Build: Topic Version 5.6.9309.1546
Visual Basic Scripting Edition

While...Wend Statement
Executes a series of statements as long as a given condition is True.
While condition
Version
statements]
[
Wend

Arguments
condition
Numeric or string expression that evaluates to True or False. If condition is Null, condition is treated as False.
statements
One or more statements executed while condition is True.
Remarks
If condition is True, all statements in statements are executed until the Wend statement is encountered. Control then returns to the While statement and condition is again checked. If condition is still True, the process is
repeated. If it is not True, execution resumes with the statement following the Wend statement.
While...Wend loops can be nested to any level. Each Wend matches the most recent While.
Note The Do...Loop statement provides a more structured and flexible way to perform looping.
The following example illustrates use of the While...Wend statement:
Dim Counter
Counter = 0
' Initialize variable.
While Counter < 20
' Test value of Counter.
Counter = Counter + 1
' Increment Counter.
Alert Counter
Wend
' End While loop when Counter > 19.

Requirements
Version 1
See Also
Do...Loop Statement

2001 Microsoft Corporation. All rights reserved.


Build: Topic Version 5.6.9309.1546
Visual Basic Scripting Edition

With Statement
Executes a series of statements on a single object.
With object
statements
End With

Arguments
object
Required. Name of an object or a function that returns an object.
statements
Required. One or more statements to be executed on object.
Remarks
The With statement allows you to perform a series of statements on a specified object without requalifying the name of the object. For example, to change a number of different properties on a single object, place the property
assignment statements within the With control structure, referring to the object once instead of referring to it with each property assignment. The following example illustrates use of the With statement to assign values to
several properties of the same object.
With MyLabel
.Height = 2000
.Width = 2000
.Caption = "This is MyLabel"
End With

While property manipulation is an important aspect of With functionality, it is not the only use. Any legal code can be used within a With block.
Note Once a With block is entered, object can't be changed. As a result, you can't use a single With statement to affect a number of different objects.
You can nest With statements by placing one With block within another. However, because members of outer With blocks are masked within the inner With blocks, you must provide a fully qualified object reference in an
inner With block to any member of an object in an outer With block.
Important Do not jump into or out of With blocks. If statements in a With block are executed, but either the With or End With statement is not executed, you may get errors or unpredictable behavior.
Requirements
Version 1
See Also
Set Statement

2001 Microsoft Corporation. All rights reserved.


Build: Topic Version 5.6.9309.1546
Scripting Runtime Library

Dictionary Object
Object that stores data key, item pairs.
Remarks
A Dictionary object is the equivalent of a PERL associative array. Items can be any form of data, and are stored in the array. Each item is associated with a unique key. The key is used to retrieve an individual item and is
usually a integer or a string, but can be anything except an array.
The following code illustrates how to create a Dictionary object:
[JScript]
var y = new ActiveXObject("Scripting.Dictionary");
y.add ("a", "test");
if (y.Exists("a"))
document.write("true");
...
[VBScript]
Dim d
' Create a variable.
Set d = CreateObject("Scripting.Dictionary")
d.Add "a", "Athens"
' Add some keys and items.
d.Add "b", "Belgrade"
d.Add "c", "Cairo"
...

Methods
Add Method (Dictionary) | Exists Method | Items Method | Keys Method | Remove Method | RemoveAll Method
Properties
Count Property | Item Property | Key Property
See Also
FileSystemObject Object | TextStream Object

2001 Microsoft Corporation. All rights reserved.


Build: Topic Version 5.6.9309.1546
Scripting Runtime Library

Count Property
Returns the number of items in a collection or Dictionary object. Read-only.

object.Count

The object is always the name of one of the items in the Applies To list.
Remarks
The following code illustrates use of the Count property:
[JScript]
function CountDemo()
{
var a, d, i, s;
// Create some variables.
d = new ActiveXObject("Scripting.Dictionary");
d.Add ("a", "Athens");
// Add some keys and items.
d.Add ("b", "Belgrade");
d.Add ("c", "Cairo");
a = (new VBArray(d.Keys()));
// Get the keys.
s = "";
for (i = 0; i < d.Count; i++)
//Iterate the dictionary.
{
s += a.getItem(i) + " - " + d(a.getItem(i)) + "<br>";
}
return(s);
// Return the results.
}
[VBScript]
Function ShowKeys
Dim a, d, i, s
' Create some variables.
Set d = CreateObject("Scripting.Dictionary")
d.Add "a", "Athens"
' Add some keys and items.
d.Add "b", "Belgrade"
d.Add "c", "Cairo"
a = d.Keys
' Get the keys.
For i = 0 To d.Count -1 ' Iterate the array.
s = s & a(i) & "<BR>" ' Create return string.
Next
ShowKeys = s
End Function

See Also
CompareMode Property | Item Property | Key Property
Applies To: Dictionary Object | Drives Collection | Files Collection | Folders Collection

2001 Microsoft Corporation. All rights reserved.


Build: Topic Version 5.6.9309.1546
Scripting Runtime Library

Item Property
Sets or returns an item for a specified key in a Dictionary object. For collections, returns an item based on the specified key. Read/write.
object.Item(key)[ = newitem]

Arguments
object
Required. Always the name of a collection or Dictionary object.
key
Required. Key associated with the item being retrieved or added.
newitem
Optional. Used for Dictionary object only; no application for collections. If provided, newitem is the new value associated with the specified key.
Remarks
If key is not found when changing an item, a new key is created with the specified newitem. If key is not found when attempting to return an existing item, a new key is created and its corresponding item is left empty.
The following example illustrates the use of the Item property.
[JScript]
function DicTest(keyword)
{
var a, d;
d = new ActiveXObject("Scripting.Dictionary");
d.Add("a", "Athens");
d.Add("b", "Belgrade");
d.Add("c", "Cairo");
a = d.Item(keyword);
return(a);
}
[VBScript]
Function ItemDemo
Dim d
' Create some variables.
Set d = CreateObject("Scripting.Dictionary")
d.Add "a", "Athens"
' Add some keys and items.
d.Add "b", "Belgrade"
d.Add "c", "Cairo"
ItemDemo = d.Item("c")
' Get the item.
End Function

See Also
CompareMode Property | Count Property | Key Property
Applies To: Dictionary Object | Drives Collection | Files Collection | Folders Collection

2001 Microsoft Corporation. All rights reserved.


Build: Topic Version 5.6.9309.1546
Scripting Runtime Library

Key Property
Sets a key in a Dictionary object.
object.Key(key) = newkey

Arguments
object
Required. Always the name of a Dictionary object.
key
Required. Key value being changed.
newkey
Required. New value that replaces the specified key.
Remarks
If key is not found when changing a key, a new key is created and its associated item is left empty.
The following example illustrates the use of the Key property:
[JScript]
var d;
d = new ActiveXObject("Scripting.Dictionary");
function AddStuff()
{
var a;
d.Add("a", "Athens");
d.Add("b", "Belgrade");
d.Add("c", "Cairo");
}
function ChangeKey(oldkey, newkey)
{
var s;
d.Key("c") = "Ca";
s = "Key " + oldkey + " changed to " + newkey;
return(s);
}
[VBScript]
Function DicDemo
Dim d
' Create some variables.
Set d = CreateObject("Scripting.Dictionary")
d.Add "a", "Athens"
' Add some keys and items.
d.Add "b", "Belgrade"
d.Add "c", "Cairo"
d.Key("c") = "d"
' Set key for "c" to "d".
DicDemo = d.Item("d")
' Return associate item.
End Function

See Also
CompareMode Property | Count Property | Item Property
Applies To: Dictionary Object

2001 Microsoft Corporation. All rights reserved.


Build: Topic Version 5.6.9309.1546
Scripting Runtime Library

Add Method (Dictionary)


Adds a key and item pair to a Dictionary object.
object.Add (key, item)

Arguments
object
Required. Always the name of a Dictionary object.
key
Required. The key associated with the item being added.
item
Required. The item associated with the key being added.
Remarks
An error occurs if the key already exists.
The following example illustrates the use of the Add method.
[JScript]
var d;
d = new ActiveXObject("Scripting.Dictionary");
d.Add("a", "Athens");
d.Add("b", "Belgrade");
d.Add("c", "Cairo");
[VBScript]
Dim d
' Create a variable.
Set d = CreateObject("Scripting.Dictionary")
d.Add "a", "Athens"
' Add some keys and items.
d.Add "b", "Belgrade"
d.Add "c", "Cairo"

See Also
Add Method (Folders) | Exists Method | Items Method | Keys Method | Remove Method | RemoveAll Method
Applies To: Dictionary Object

2001 Microsoft Corporation. All rights reserved.


Build: Topic Version 5.6.9309.1546
Scripting Runtime Library

Exists Method
Returns true if a specified key exists in the Dictionary object, false if it does not.

object.Exists(key)

Arguments
object
Required. Always the name of a Dictionary object.
key
Required. Key value being searched for in the Dictionary object.
Remarks
The following example illustrates the use of the Exists method.
[JScript]
function keyExists(k)
{
var fso, s = "";
d = new ActiveXObject("Scripting.Dictionary");
d.Add("a", "Athens");
d.Add("b", "Belgrade");
d.Add("c", "Cairo");
if (d.Exists(k))
s += "Specified key exists.";
else
s += "Specified key doesn't exist.";
return(s);
}
[VBScript]
Function KeyExistsDemo
Dim d, msg
' Create some variables.
Set d = CreateObject("Scripting.Dictionary")
d.Add "a", "Athens"
' Add some
keys and items.
d.Add "b", "Belgrade"
d.Add "c", "Cairo"
If d.Exists("c") Then
msg = "Specified key exists."
Else
msg = "Specified key doesn't exist."
End If
KeyExistsDemo = msg
End Function

See Also
Add Method (Dictionary) | Items Method | Keys Method | Remove Method | RemoveAll Method
Applies To: Dictionary Object

2001 Microsoft Corporation. All rights reserved.


Build: Topic Version 5.6.9309.1546
Scripting Runtime Library

Items Method
Returns an array containing all the items in a Dictionary object.
object.Items( )

The object is always the name of a Dictionary object.


Remarks
The following code illustrates use of the Items method:
[JScript]
function ItemsDemo()
{
var a, d, i, s;
// Create some variables.
d = new ActiveXObject("Scripting.Dictionary");
d.Add ("a", "Athens");
// Add some keys and items.
d.Add ("b", "Belgrade");
d.Add ("c", "Cairo");
a = (new VBArray(d.Items())).toArray();
// Get the items.
s = "";
for (i in a)
// Iterate the dictionary.
{
s += a[i] + "<br>";
}
return(s);
// Return the results.
}
[VBScript]
Function DicDemo
Dim a, d, i, s
' Create some variables.
Set d = CreateObject("Scripting.Dictionary")
d.Add "a", "Athens"
' Add some keys and items.
d.Add "b", "Belgrade"
d.Add "c", "Cairo"
a = d.Items
' Get the items.
For i = 0 To d.Count -1 ' Iterate the array.
s = s & a(i) & "<BR>" ' Create return string.
Next
DicDemo = s
End Function

See Also
Add Method (Dictionary) | Exists Method | Keys Method | Remove Method | RemoveAll Method
Applies To: Dictionary Object

2001 Microsoft Corporation. All rights reserved.


Build: Topic Version 5.6.9309.1546
Scripting Runtime Library

Keys Method
Returns an array containing all existing keys in a Dictionary object.

object.Keys( )

The object is always the name of a Dictionary object.


Remarks
The following code illustrates use of the Keys method:
[JScript]
function KeysDemo()
{
var a, d, i, s;
// Create some variables.
d = new ActiveXObject("Scripting.Dictionary");
d.Add ("a", "Athens");
// Add some keys and items.
d.Add ("b", "Belgrade");
d.Add ("c", "Cairo");
a = (new VBArray(d.Keys())).toArray();
// Get the keys.
s = "";
for (i in a)
// Iterate the dictionary.
{
s += a[i] + " - " + d(a[i]) + "<br>";
}
return(s);
// Return the results.
}
[VBScript]
Function DicDemo
Dim a, d, i
' Create some variables.
Set d = CreateObject("Scripting.Dictionary")
d.Add "a", "Athens"
' Add some keys and items.
d.Add "b", "Belgrade"
d.Add "c", "Cairo"
a = d.Keys
' Get the keys.
For i = 0 To d.Count -1 ' Iterate the array.
s = s & a(i) & "<BR>" ' Return results.
Next
DicDemo = s
End Function

See Also
Add Method (Dictionary) | Exists Method | Items Method | Remove Method | RemoveAll Method
Applies To: Dictionary Object

2001 Microsoft Corporation. All rights reserved.


Build: Topic Version 5.6.9309.1546
Scripting Runtime Library

Remove Method
Removes a key, item pair from a Dictionary object.
object.Remove(key)

Arguments
object
Required. Always the name of a Dictionary object.
key
Required. Key associated with the key, item pair you want to remove from the Dictionary object.
Remarks
An error occurs if the specified key, item pair does not exist.
The following code illustrates use of the Remove method:
[JScript]
var a, d, i, s;
// Create some variables.
d = new ActiveXObject("Scripting.Dictionary");
d.Add ("a", "Athens");
// Add some keys and items.
d.Add ("b", "Belgrade");
d.Add ("c", "Cairo");
...
d.Remove("b");
// Remove second pair.
[VBScript]
Dim a, d
' Create some variables.
Set d = CreateObject("Scripting.Dictionary")
d.Add "a", "Athens"
' Add some keys and items.
d.Add "b", "Belgrade"
d.Add "c", "Cairo"
...
d.Remove("b")
' Remove second pair.

See Also
Add Method (Dictionary) | Exists Method | Items Method | Keys Method | RemoveAll Method
Applies To: Dictionary Object

2001 Microsoft Corporation. All rights reserved.


Build: Topic Version 5.6.9309.1546
Scripting Runtime Library

RemoveAll Method
The RemoveAll method removes all key, item pairs from a Dictionary object.
object.RemoveAll( )

The object is always the name of a Dictionary object.


Remarks
The following code illustrates use of the RemoveAll method:

[JScript]
var a, d, i;
// Create some variables.
d = new ActiveXObject("Scripting.Dictionary");
d.Add ("a", "Athens");
// Add some keys and items.
d.Add ("b", "Belgrade");
d.Add ("c", "Cairo");
...
d.RemoveAll( );
// Clear the dictionary.
[VBScript]
Dim a, d, i
' Create some variables.
Set d = CreateObject("Scripting.Dictionary")
d.Add "a", "Athens"
' Add some keys and items.
d.Add "b", "Belgrade"
d.Add "c", "Cairo"
...
a = d.RemoveAll
' Clear the dictionary.

See Also
Add Method (Dictionary) | Exists Method | Items Method | Keys Method | Remove Method
Applies To: Dictionary Object

2001 Microsoft Corporation. All rights reserved.


Build: Topic Version 5.6.9309.1546
Scripting Runtime Library

FileSystemObject
In This Section
Scripting Run-Time Reference
List of elements that make up Scripting Run-Time Reference.
FileSystemObject Basics
A guide to the fundamentals of the FileSystemObject.

2001 Microsoft Corporation. All rights reserved.


Build: Topic Version 5.6.9309.1546
Scripting Runtime Library

FileSystemObject Basics
When writing scripts for Active Server Pages, the Windows Script Host, or other applications where scripting can be used, it's often important to add, move, change, create, or delete folders (directories) and files on the Web
server. It may also be necessary to get information about and manipulate drives attached to the Web server.
Scripting allows you to process drives, folders, and files using the FileSystemObject (FSO) object model, which is explained in the following sections:
The FileSystemObject Object Model
The FileSystemObject object model allows you to use the familiar object.method syntax with a rich set of properties, methods, and events to process folders and files.
FileSystemObject Objects
A list of the objects and collections in FileSystemObject object model.
Programming the FileSystemObject
Description of how to program with the FileSystemObject.
Working with Drives and Folders
Describes how you use the FileSystemObject to copy and move folders, as well as get information about drives and folders.
Working with Files
Describes how you use the FileSystemObject to manipulate files.
FileSystemObject Sample Code
A real-world example that demonstrates many of the features available in the FileSystemObject object model.

2001 Microsoft Corporation. All rights reserved.


Build: Topic Version 5.6.9309.1546
Scripting Runtime Library

The FileSystemObject Object Model


The FileSystemObject (FSO) object model allows you to use the familiar object.method syntax with a rich set of properties, methods, and events to process folders and files.
Use this object-based tool with:

HTML to create Web pages


Windows Scripting Host to create batch files for Microsoft Windows
Script Control to provide a scripting capability to applications developed in other languages

Because use of the FSO on the client side raises serious security issues about providing potentially unwelcome access to a client's local file system, this documentation assumes use of the FSO object model to create scripts
executed by Internet Web pages on the server side. Since the server side is used, the Internet Explorer default security settings do not allow client-side use of the FileSystemObject object. Overriding those defaults could subject
a local computer to unwelcome access to the file system, which could result in total destruction of the file system's integrity, causing loss of data, or worse.
The FSO object model gives your server-side applications the ability to create, alter, move, and delete folders, or to detect if particular folders exist, and if so, where. You can also find out information about folders, such as their
names, the date they were created or last modified, and so forth.
The FSO object model also makes it easy to process files. When processing files, the primary goal is to store data in a space- and resource-efficient, easy-to-access format. You need to be able to create files, insert and change the
data, and output (read) the data. Since storing data in a database, such as Access or SQL Server, adds a significant amount of overhead to your application, storing your data in a binary or text file may be the most efficient

solution. You may prefer not to have this overhead, or your data access requirements may not require all the extra features associated with a full-featured database.

The FSO object model, which is contained in the Scripting type library (Scrrun.dll), supports text file creation and manipulation through the TextStream object. Although it does not yet support the creation or
manipulation of binary files, future support of binary files is planned.

2001 Microsoft Corporation. All rights reserved.


Build: Topic Version 5.6.9309.1546
Scripting Runtime Library

FileSystemObject Objects
The FileSystemObject (FSO) object model contains the following objects and collections.
Object/Collection
FileSystemObject
Drive

Drives
File
Files
Folder
Folders
TextStream

Description
Main object. Contains methods and properties that allow you to create, delete, gain information about, and generally manipulate drives, folders, and files. Many of the
methods associated with this object duplicate those in other FSO objects; they are provided for convenience.
Object. Contains methods and properties that allow you to gather information about a drive attached to the system, such as its share name and how much room is
available. Note that a "drive" isn't necessarily a hard disk, but can be a CD-ROM drive, a RAM disk, and so forth. A drive doesn't need to be physically attached to the
system; it can be also be logically connected through a network.
Collection. Provides a list of the drives attached to the system, either physically or logically. The Drives collection includes all drives, regardless of type. Removablemedia drives need not have media inserted for them to appear in this collection.
Object. Contains methods and properties that allow you to create, delete, or move a file. Also allows you to query the system for a file name, path, and various other
properties.
Collection. Provides a list of all files contained within a folder.
Object. Contains methods and properties that allow you to create, delete, or move folders. Also allows you to query the system for folder names, paths, and various other
properties.
Collection. Provides a list of all the folders within a Folder.
Object. Allows you to read and write text files.

2001 Microsoft Corporation. All rights reserved.


Build: Topic Version 5.6.9309.1546
Scripting Runtime Library

Programming the FileSystemObject


To program with the FileSystemObject (FSO) object model:

Use the CreateObject method to create a FileSystemObject object.


Use the appropriate method on the newly created object.
Access the object's properties.

The FSO object model is contained in the Scripting type library, which is located in the Scrrun.dll file. Therefore, you must have Scrrun.dll in the appropriate system directory on your Web server to use the FSO object model.

Creating a FileSystemObject Object


First, create a FileSystemObject object by using the CreateObject method.
The following code displays how to create an instance of the FileSystemObject:
[VBScript]
Dim fso
Set fso = CreateObject("Scripting.FileSystemObject")
[JScript]
var fso;
fso = new ActiveXObject("Scripting.FileSystemObject");

In both of these examples, Scripting is the name of the type library and FileSystemObject is the name of the object that you want to create. You can create only one instance of the FileSystemObject object, regardless of how
many times you try to create another.

Using the Appropriate Method


Second, use the appropriate method of the FileSystemObject object. For example, to create a new object, use either CreateTextFile or CreateFolder (the FSO object model doesn't support the creation or deletion of drives).
To delete objects, use the DeleteFile and DeleteFolder methods of the FileSystemObject object, or the Delete method of the File and Folder objects. You can also copy and move files and folders, by using the appropriate
methods.
Note Some functionality in the FileSystemObject object model is redundant. For example, you can copy a file using either the CopyFile method of the FileSystemObject object, or you can use the Copy method
of the File object. The methods work the same; both exist to offer programming flexibility.

Accessing Existing Drives, Files, and Folders


To gain access to an existing drive, file, or folder, use the appropriate "get" method of the FileSystemObject object:

GetDrive
GetFolder
GetFile

To gain access to an existing file:


[VBScript]
Dim fso, f1
Set fso = CreateObject("Scripting.FileSystemObject")
Set f1 = fso.GetFile("c:\test.txt")
[JScript]
var fso, f1;
fso = new ActiveXObject("Scripting.FileSystemObject");
f1 = fso.GetFile("c:\\test.txt");

Do not use the "get" methods for newly created objects, since the "create" functions already return a handle to that object. For example, if you create a new folder using the CreateFolder method, don't use the GetFolder method
to access its properties, such as Name, Path, Size, and so forth. Just set a variable to the CreateFolder function to gain a handle to the newly created folder, then access its properties, methods, and events.
To set a variable to the CreateFolder function, use this syntax:
[VBScript]
Sub CreateFolder
Dim fso, fldr
Set fso = CreateObject("Scripting.FileSystemObject")
Set fldr = fso.CreateFolder("C:\MyTest")

Response.Write "Created folder: " & fldr.Name


End Sub
[JScript]
function CreateFolder()
{
var fso, fldr;
fso = new ActiveXObject("Scripting.FileSystemObject");
fldr = fso.CreateFolder("C:\\MyTest");
Response.Write("Created folder: " + fldr.Name);
}

Accessing the Object's Properties


Once you have a handle to an object, you can access its properties. For example, to get the name of a particular folder, first create an instance of the object, then get a handle to it with the appropriate method (in this case, the
GetFolder method, since the folder already exists).
Use this code to get a handle to the GetFolder method:
[VBScript]
Set fldr = fso.GetFolder("c:\")
[JScript]
var fldr = fso.GetFolder("c:\\");

Now that you have a handle to a Folder object, you can check its Name property.
[VBScript]
Response.Write "Folder name is: " & fldr.Name
[JScript]
Response.Write("Folder name is: " + fldr.Name);

To find out the last time a file was modified, use the following syntax:
[VBScript]
Dim fso, f1
Set fso = CreateObject("Scripting.FileSystemObject")
' Get a File object to query.
Set f1 = fso.GetFile("c:\detlog.txt")
' Print information.
Response.Write "File last modified: " & f1.DateLastModified
[JScript]
var fso, f1;
fso = new ActiveXObject("Scripting.FileSystemObject");
// Get a File object to query.
f1 = fso.GetFile("c:\\detlog.txt");
// Print information.
Response.Write("File last modified: " + f1.DateLastModified);

2001 Microsoft Corporation. All rights reserved.


Build: Topic Version 5.6.9309.1546
Scripting Runtime Library

Working with Drives and Folders


With the FileSystemObject (FSO) object model, you can work with drives and folders programmatically just as you can in the Windows Explorer interactively. You can copy and move folders, get information about drives and
folders, and so forth.

Getting Information About Drives


The Drive object allows you to gain information about the various drives attached to a system, either physically or over a network. Its properties allow you to obtain information about:

The total size of the drive in bytes (TotalSize property)


How much space is available on the drive in bytes (AvailableSpace or FreeSpace properties)
What letter is assigned to the drive (DriveLetter property)
What type of drive it is, such as removable, fixed, network, CD-ROM, or RAM disk (DriveType property)
The drive's serial number (SerialNumber property)
The type of file system the drive uses, such as FAT, FAT32, NTFS, and so forth (FileSystem property)
Whether a drive is available for use (IsReady property)
The name of the share and/or volume (ShareName and VolumeName properties)
The path or root folder of the drive (Path and RootFolder properties)

View the sample code to see how these properties are used in FileSystemObject.
Example Usage of the Drive Object
Use the Drive object to gather information about a drive. You won't see a reference to an actual Drive object in the following code; instead, use the GetDrive method to get a reference to an existing Drive object (in this case,
drv).
The following example demonstrates how to use the Drive object:
[VBScript]
Sub ShowDriveInfo(drvPath)
Dim fso, drv, s
Set fso = CreateObject("Scripting.FileSystemObject")
Set drv = fso.GetDrive(fso.GetDriveName(drvPath))
s = "Drive " & UCase(drvPath) & " - "
s = s & drv.VolumeName & "<br>"
s = s & "Total Space: " & FormatNumber(drv.TotalSize / 1024, 0)
s = s & " Kb" & "<br>"
s = s & "Free Space: " & FormatNumber(drv.FreeSpace / 1024, 0)
s = s & " Kb" & "<br>"
Response.Write s
End Sub
[JScript]
function ShowDriveInfo1(drvPath)
{
var fso, drv, s ="";
fso = new ActiveXObject("Scripting.FileSystemObject");
drv = fso.GetDrive(fso.GetDriveName(drvPath));
s += "Drive " + drvPath.toUpperCase()+ " - ";
s += drv.VolumeName + "<br>";
s += "Total Space: " + drv.TotalSize / 1024;
s += " Kb" + "<br>";
s += "Free Space: " + drv.FreeSpace / 1024;
s += " Kb" + "<br>";
Response.Write(s);
}

Working with Folders


Common folder tasks and the methods for performing them are described in the following table.

Task
Method
Create a folder.
FileSystemObject.CreateFolder
Delete a folder.
Folder.Delete or FileSystemObject.DeleteFolder
Move a folder.
Folder.Move or FileSystemObject.MoveFolder
Copy a folder.
Folder.Copy or FileSystemObject.CopyFolder
Retrieve the name of a folder.
Folder.Name
Find out if a folder exists on a drive.
FileSystemObject.FolderExists
Get an instance of an existing Folder object. FileSystemObject.GetFolder
Find out the name of a folder's parent folder. FileSystemObject.GetParentFolderName
Find out the path of system folders.
FileSystemObject.GetSpecialFolder
View the sample code to see how many of these methods and properties are used in FileSystemObject.
The following example demonstrates how to use the Folder and FileSystemObject objects to manipulate folders and gain information about them.
[VBScript]
Sub ShowFolderInfo()
Dim fso, fldr, s
' Get instance of FileSystemObject.
Set fso = CreateObject("Scripting.FileSystemObject")
' Get Drive object.
Set fldr = fso.GetFolder("c:")
' Print parent folder name.
Response.Write "Parent folder name is: " & fldr & "<br>"
' Print drive name.
Response.Write "Contained on drive " & fldr.Drive & "<br>"
' Print root file name.
If fldr.IsRootFolder = True Then
Response.Write "This is the root folder." & ""<br>"<br>"
Else
Response.Write "This folder isn't a root folder." & "<br><br>"
End If
' Create a new folder with the FileSystemObject object.
fso.CreateFolder ("C:\Bogus")
Response.Write "Created folder C:\Bogus" & "<br>"
' Print the base name of the folder.
Response.Write "Basename = " & fso.GetBaseName("c:\bogus") & "<br>"
' Delete the newly created folder.
fso.DeleteFolder ("C:\Bogus")
Response.Write "Deleted folder C:\Bogus" & "<br>"
End Sub
[JScript]
function ShowFolderInfo()
{
var fso, fldr, s = "";
// Get instance of FileSystemObject.
fso = new ActiveXObject("Scripting.FileSystemObject");
// Get Drive object.
fldr = fso.GetFolder("c:");
// Print parent folder name.
Response.Write("Parent folder name is: " + fldr + "<br>");
// Print drive name.
Response.Write("Contained on drive " + fldr.Drive + "<br>");
// Print root file name.
if (fldr.IsRootFolder)
Response.Write("This is the root folder.");
else
Response.Write("This folder isn't a root folder.");
Response.Write("<br><br>");
// Create a new folder with the FileSystemObject object.
fso.CreateFolder ("C:\\Bogus");
Response.Write("Created folder C:\\Bogus" + "<br>");
// Print the base name of the folder.
Response.Write("Basename = " + fso.GetBaseName("c:\\bogus") + "<br>");
// Delete the newly created folder.
fso.DeleteFolder ("C:\\Bogus");
Response.Write("Deleted folder C:\\Bogus" + "<br>");
}

2001 Microsoft Corporation. All rights reserved.


Build: Topic Version 5.6.9309.1546
Scripting Runtime Library

Working with Files


There are two major categories of file manipulation:

Creating, adding, or removing data, and reading files


Moving, copying, and deleting files

Creating Files
There are three ways to create an empty text file (sometimes referred to as a "text stream").
The first way is to use the CreateTextFile method. The following example demonstrates how to create a text file using the CreateTextFileMethod method.
[VBScript]
Dim fso, f1
Set fso = CreateObject("Scripting.FileSystemObject")
Set f1 = fso.CreateTextFile("c:\testfile.txt", True)
[JScript]
var fso, f1;
fso = new ActiveXObject("Scripting.FileSystemObject");
f1 = fso.CreateTextFile("c:\\testfile.txt", true);

The second way to create a text file is to use the OpenTextFile method of the FileSystemObject object with the ForWriting flag set.
[VBScript]
Dim fso, ts
Const ForWriting = 2
Set fso = CreateObject("Scripting. FileSystemObject")
Set ts = fso.OpenTextFile("c:\test.txt", ForWriting, True)
[JScript]
var fso, ts;
var ForWriting= 2;
fso = new ActiveXObject("Scripting.FileSystemObject");
ts = fso.OpenTextFile("c:\\test.txt", ForWriting, true);

A third way to create a text file is to use the OpenAsTextStream method with the ForWriting flag set.
[VBScript]
Dim fso, f1, ts
Const ForWriting = 2
Set fso = CreateObject("Scripting.FileSystemObject")

fso.CreateTextFile ("c:\test1.txt")
Set f1 = fso.GetFile("c:\test1.txt")
Set ts = f1.OpenAsTextStream(ForWriting, True)
[JScript]
var fso, f1, ts;
var ForWriting = 2;
fso = new ActiveXObject("Scripting.FileSystemObject");
fso.CreateTextFile ("c:\\test1.txt");
f1 = fso.GetFile("c:\\test1.txt");
ts = f1.OpenAsTextStream(ForWriting, true);

Adding Data to the File


Once the text file is created, add data to the file using the following three steps:
Open the text file.
Write the data.
Close the file.
To open an existing file, use either the OpenTextFile method of the FileSystemObject object or the OpenAsTextStream method of the File object.
To write data to the open text file, use the Write, WriteLine, or WriteBlankLines methods of the TextStream object, according to the tasks outlined in the following table.
Task
Method
Write data to an open text file without a trailing newline character. Write
Write data to an open text file with a trailing newline character. WriteLine
Write one or more blank lines to an open text file.
WriteBlankLines
To close an open file, use the Close method of the TextStream object.
Note The newline character contains a character or characters (depending on the operating system) to advance the cursor to the beginning of the next line (carriage return/line feed). Be aware that the end of some
strings may already have such nonprinting characters.
The following example demonstrates how to open a file, use all three write methods to add data to the file, and then close the file:
[VBScript]
Sub CreateFile()
Dim fso, tf
Set fso = CreateObject("Scripting.FileSystemObject")
Set tf = fso.CreateTextFile("c:\testfile.txt", True)
' Write a line with a newline character.
tf.WriteLine("Testing 1, 2, 3.")
' Write three newline characters to the file.
tf.WriteBlankLines(3)
' Write a line.
tf.Write ("This is a test.")
tf.Close
End Sub
[JScript]
function CreateFile()
{
var fso, tf;
fso = new ActiveXObject("Scripting.FileSystemObject");
tf = fso.CreateTextFile("c:\\testfile.txt", true);
// Write a line with a newline character.
tf.WriteLine("Testing 1, 2, 3.") ;
// Write three newline characters to the file.
tf.WriteBlankLines(3) ;
// Write a line.
tf.Write ("This is a test.");
tf.Close();
}

Reading Files
To read data from a text file, use the Read, ReadLine, or ReadAll method of the TextStream object. The following table describes which method to use for various tasks.
Task
Method
Read a specified number of characters from a file.
Read
Read an entire line (up to, but not including, the newline character). ReadLine
Read the entire contents of a text file.
ReadAll
If you use the Read or ReadLine method and want to skip to a particular portion of data, use the Skip or SkipLine method. The resulting text of the read methods is stored in a string which can be displayed in a control, parsed
by string functions (such as Left, Right, and Mid), concatenated, and so forth.
The following example demonstrates how to open a file, write to it, and then read from it:
[VBScript]
Sub ReadFiles
Dim fso, f1, ts, s
Const ForReading = 1
Set fso = CreateObject("Scripting.FileSystemObject")
Set f1 = fso.CreateTextFile("c:\testfile.txt", True)
' Write a line.
Response.Write "Writing file <br>"
f1.WriteLine "Hello World"
f1.WriteBlankLines(1)
f1.Close
' Read the contents of the file.
Response.Write "Reading file <br>"
Set ts = fso.OpenTextFile("c:\testfile.txt", ForReading)
s = ts.ReadLine
Response.Write "File contents = '" & s & "'"
ts.Close
End Sub
[JScript]
function ReadFiles()
{
var fso, f1, ts, s;
var ForReading = 1;
fso = new ActiveXObject("Scripting.FileSystemObject");
f1 = fso.CreateTextFile("c:\\testfile.txt", true);
// Write a line.
Response.Write("Writing file <br>");
f1.WriteLine("Hello World");
f1.WriteBlankLines(1);
f1.Close();
// Read the contents of the file.
Response.Write("Reading file <br>");
ts = fso.OpenTextFile("c:\\testfile.txt", ForReading);
s = ts.ReadLine();
Response.Write("File contents = '" + s + "'");
ts.Close();
}

Moving, Copying, and Deleting Files

The FSO object model has two methods each for moving, copying, and deleting files, as described in the following table.
Task
Move a file
Copy a file
Delete a file

Method
File.Move or FileSystemObject.MoveFile
File.Copy or FileSystemObject.CopyFile
File.Delete or FileSystemObject.DeleteFile

The following example creates a text file in the root directory of drive C, writes some information to it, moves it to a directory called \tmp, makes a copy of it in a directory called \temp, then deletes the copies from both
directories.
To run the following example, create directories named \tmp and \temp in the root directory of drive C:
[VBScript]
Sub ManipFiles
Dim fso, f1, f2, s
Set fso = CreateObject("Scripting.FileSystemObject")
Set f1 = fso.CreateTextFile("c:\testfile.txt", True)
Response.Write "Writing file <br>"
' Write a line.
f1.Write ("This is a test.")
' Close the file to writing.
f1.Close
Response.Write "Moving file to c:\tmp <br>"
' Get a handle to the file in root of C:\.
Set f2 = fso.GetFile("c:\testfile.txt")
' Move the file to \tmp directory.
f2.Move ("c:\tmp\testfile.txt")
Response.Write "Copying file to c:\temp <br>"
' Copy the file to \temp.
f2.Copy ("c:\temp\testfile.txt")
Response.Write "Deleting files <br>"
' Get handles to files' current location.
Set f2 = fso.GetFile("c:\tmp\testfile.txt")
Set f3 = fso.GetFile("c:\temp\testfile.txt")
' Delete the files.
f2.Delete
f3.Delete
Response.Write "All done!"
End Sub
[JScript]
function ManipFiles()
{
var fso, f1, f2, s;
fso = new ActiveXObject("Scripting.FileSystemObject");
f1 = fso.CreateTextFile("c:\\testfile.txt", true);
Response.Write("Writing file <br>");
// Write a line.
f1.Write("This is a test.");
// Close the file to writing.
f1.Close();
Response.Write("Moving file to c:\\tmp <br>");
// Get a handle to the file in root of C:\.
f2 = fso.GetFile("c:\\testfile.txt");
// Move the file to \tmp directory.
f2.Move ("c:\\tmp\\testfile.txt");
Response.Write("Copying file to c:\\temp <br>");
// Copy the file to \temp.
f2.Copy ("c:\\temp\\testfile.txt");
Response.Write("Deleting files <br>");
// Get handles to files' current location.
f2 = fso.GetFile("c:\\tmp\\testfile.txt");
f3 = fso.GetFile("c:\\temp\\testfile.txt");
// Delete the files.
f2.Delete();
f3.Delete();
Response.Write("All done!");
}

2001 Microsoft Corporation. All rights reserved.


Build: Topic Version 5.6.9309.1546
Scripting Runtime Library

FileSystemObject Sample Code


The sample code described in this section provides a real-world example that demonstrates many of the features available in the FileSystemObject object model. This code shows how all the features of the object model work
together, and how to use those features effectively in your own code.
Notice that since this code is fairly generic, some additional code and a little tweaking are needed to make this code actually run on your machine. These changes are necessary because of the different ways input and output to
the user is handled between Active Server Pages and the Windows Scripting Host.
To run this code on an Active Server Page, use the following steps:
Create a standard web page with an .asp extension.
Copy the following sample code into that file between the <BODY>...</BODY> tags.
Enclose all the code within <%...%> tags.
Move the Option Explicit statement from its current position in the code to the very top of your HTML page, positioning it even before the opening <HTML> tag.
Place <%...%> tags around the Option Explicit statement to ensure that it's run on the server side.
Add the following code to the end of the sample code:
Sub Print(x)
Response.Write "<PRE>&ltFONT FACE=""Courier New"" SIZE=""1"">"
Response.Write x
Response.Write "</FONT></PRE>"
End Sub
Main

The previous code adds a print procedure that will run on the server side, but display results on the client side. To run this code on the Windows Scripting Host, add the following code to the end of the sample code:
Sub Print(x)
WScript.Echo x
End Sub
Main

The code is contained in the following section:


''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
' FileSystemObject Sample Code
' Copyright 1998 Microsoft Corporation.
All Rights Reserved.

''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
Option Explicit
''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
' Regarding code quality:
' 1) The following code does a lot of string manipulation by
'
concatenating short strings together with the "&" operator.
'
Since string concatenation is expensive, this is a very
'
inefficient way to write code. However, it is a very
'
maintainable way to write code, and is used here because this
'
program performs extensive disk operations, and because the
'
disk is much slower than the memory operations required to
'
concatenate the strings. Keep in mind that this is demonstration
'
code, not production code.
'
' 2) "Option Explicit" is used, because declared variable access is
'
slightly faster than undeclared variable access. It also prevents
'
bugs from creeping into your code, such as when you misspell
'
DriveTypeCDROM as DriveTypeCDORM.
'
' 3) Error handling is absent from this code, to make the code more
'
readable. Although precautions have been taken to ensure that the
'
code will not error in common cases, file systems can be
'
unpredictable. In production code, use On Error Resume Next and
'
the Err object to trap possible errors.
''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
' Some handy global variables
''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
Dim TabStop
Dim NewLine
Const TestDrive = "C"
Const TestFilePath = "C:\Test"
''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
' Constants returned by Drive.DriveType
''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
Const DriveTypeRemovable = 1
Const DriveTypeFixed = 2
Const DriveTypeNetwork = 3
Const DriveTypeCDROM = 4
Const DriveTypeRAMDisk = 5
''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
' Constants returned by File.Attributes
''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
Const FileAttrNormal
= 0
Const FileAttrReadOnly = 1
Const FileAttrHidden = 2
Const FileAttrSystem = 4
Const FileAttrVolume = 8
Const FileAttrDirectory = 16
Const FileAttrArchive = 32
Const FileAttrAlias = 64
Const FileAttrCompressed = 128
''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
' Constants for opening files
''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
Const OpenFileForReading = 1
Const OpenFileForWriting = 2
Const OpenFileForAppending = 8
''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
' ShowDriveType
' Purpose:
'
Generates a string describing the drive type of a given Drive object.
' Demonstrates the following
' - Drive.DriveType
''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
Function ShowDriveType(Drive)
Dim S
Select Case Drive.DriveType
Case DriveTypeRemovable
S = "Removable"
Case DriveTypeFixed
S = "Fixed"
Case DriveTypeNetwork
S = "Network"
Case DriveTypeCDROM
S = "CD-ROM"
Case DriveTypeRAMDisk
S = "RAM Disk"
Case Else
S = "Unknown"
End Select
ShowDriveType = S
End Function
''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
' ShowFileAttr
' Purpose:
'
Generates a string describing the attributes of a file or folder.
' Demonstrates the following
' - File.Attributes
' - Folder.Attributes
''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
Function ShowFileAttr(File) ' File can be a file or folder
Dim S
Dim Attr
Attr = File.Attributes
If Attr = 0 Then
ShowFileAttr = "Normal"
Exit Function
End If
If
If
If
If
If
If
If
If

Attr
Attr
Attr
Attr
Attr
Attr
Attr
Attr

And
And
And
And
And
And
And
And

FileAttrDirectory Then S = S & "Directory "


FileAttrReadOnly Then S = S & "Read-Only "
FileAttrHidden Then S = S & "Hidden "
FileAttrSystem Then S = S & "System "
FileAttrVolume Then S = S & "Volume "
FileAttrArchive Then S = S & "Archive "
FileAttrAlias Then S = S & "Alias "
FileAttrCompressed Then S = S & "Compressed "

ShowFileAttr = S
End Function
''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''

' GenerateDriveInformation
' Purpose:
'
Generates a string describing the current state of the
'
available drives.
' Demonstrates the following
' - FileSystemObject.Drives
' - Iterating the Drives collection
' - Drives.Count
' - Drive.AvailableSpace
' - Drive.DriveLetter
' - Drive.DriveType
' - Drive.FileSystem
' - Drive.FreeSpace
' - Drive.IsReady
' - Drive.Path
' - Drive.SerialNumber
' - Drive.ShareName
' - Drive.TotalSize
' - Drive.VolumeName
''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
Function GenerateDriveInformation(FSO)
Dim Drives
Dim Drive
Dim S
Set Drives = FSO.Drives
S = "Number of drives:" & TabStop & Drives.Count & NewLine & NewLine
'
S
S
S
S
S
S

Construct 1st line of report.


= S & String(2, TabStop) & "Drive"
= S & String(3, TabStop) & "File"
= S & TabStop & "Total"
= S & TabStop & "Free"
= S & TabStop & "Available"
= S & TabStop & "Serial" & NewLine

'
S
S
S
S
S
S
S
S
S
S

Construct 2nd line of report.


= S & "Letter"
= S & TabStop & "Path"
= S & TabStop & "Type"
= S & TabStop & "Ready?"
= S & TabStop & "Name"
= S & TabStop & "System"
= S & TabStop & "Space"
= S & TabStop & "Space"
= S & TabStop & "Space"
= S & TabStop & "Number" & NewLine

' Separator line.


S = S & String(105, "-") & NewLine
For Each
S = S
S = S
S = S
S = S

Drive In Drives
& Drive.DriveLetter
& TabStop & Drive.Path
& TabStop & ShowDriveType(Drive)
& TabStop & Drive.IsReady

If Drive.IsReady Then
If DriveTypeNetwork = Drive.DriveType Then
S = S & TabStop & Drive.ShareName
Else
S = S & TabStop & Drive.VolumeName
End If
S = S & TabStop & Drive.FileSystem
S = S & TabStop & Drive.TotalSize
S = S & TabStop & Drive.FreeSpace
S = S & TabStop & Drive.AvailableSpace
S = S & TabStop & Hex(Drive.SerialNumber)
End If
S = S & NewLine
Next
GenerateDriveInformation = S
End Function
''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
' GenerateFileInformation
' Purpose:
'
Generates a string describing the current state of a file.
' Demonstrates the following
' - File.Path
' - File.Name
' - File.Type
' - File.DateCreated
' - File.DateLastAccessed
' - File.DateLastModified
' - File.Size
''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
Function GenerateFileInformation(File)
Dim S
S
S
S
S
S
S
S
S

=
=
=
=
=
=
=
=

NewLine & "Path:" & TabStop & File.Path


S & NewLine & "Name:" & TabStop & File.Name
S & NewLine & "Type:" & TabStop & File.Type
S & NewLine & "Attribs:" & TabStop & ShowFileAttr(File)
S & NewLine & "Created:" & TabStop & File.DateCreated
S & NewLine & "Accessed:" & TabStop & File.DateLastAccessed
S & NewLine & "Modified:" & TabStop & File.DateLastModified
S & NewLine & "Size" & TabStop & File.Size & NewLine

GenerateFileInformation = S
End Function
''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
' GenerateFolderInformation
' Purpose:
'
Generates a string describing the current state of a folder.
' Demonstrates the following
' - Folder.Path
' - Folder.Name
' - Folder.DateCreated
' - Folder.DateLastAccessed
' - Folder.DateLastModified
' - Folder.Size
''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
Function GenerateFolderInformation(Folder)
Dim S
S = "Path:" & TabStop & Folder.Path
S = S & NewLine & "Name:" & TabStop & Folder.Name
S = S & NewLine & "Attribs:" & TabStop & ShowFileAttr(Folder)

S
S
S
S

=
=
=
=

S
S
S
S

&
&
&
&

NewLine
NewLine
NewLine
NewLine

&
&
&
&

"Created:" & TabStop & Folder.DateCreated


"Accessed:" & TabStop & Folder.DateLastAccessed
"Modified:" & TabStop & Folder.DateLastModified
"Size:" & TabStop & Folder.Size & NewLine

GenerateFolderInformation = S
End Function
''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
' GenerateAllFolderInformation
' Purpose:
'
Generates a string describing the current state of a
'
folder and all files and subfolders.
' Demonstrates the following
' - Folder.Path
' - Folder.SubFolders
' - Folders.Count
''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
Function GenerateAllFolderInformation(Folder)
Dim
Dim
Dim
Dim
Dim

S
SubFolders
SubFolder
Files
File

S = "Folder:" & TabStop & Folder.Path & NewLine & NewLine


Set Files = Folder.Files
If 1 = Files.Count Then
S = S & "There is 1 file" & NewLine
Else
S = S & "There are " & Files.Count & " files" & NewLine
End If
If Files.Count <> 0 Then
For Each File In Files
S = S & GenerateFileInformation(File)
Next
End If
Set SubFolders = Folder.SubFolders
If 1 = SubFolders.Count Then
S = S & NewLine & "There is 1 sub folder" & NewLine & NewLine
Else
S = S & NewLine & "There are " & SubFolders.Count & " sub folders" _
NewLine & NewLine
End If
If SubFolders.Count <> 0 Then
For Each SubFolder In SubFolders
S = S & GenerateFolderInformation(SubFolder)
Next
S = S & NewLine
For Each SubFolder In SubFolders
S = S & GenerateAllFolderInformation(SubFolder)
Next
End If
GenerateAllFolderInformation = S
End Function
''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
' GenerateTestInformation
' Purpose:
'
Generates a string describing the current state of the C:\Test
'
folder and all files and subfolders.
' Demonstrates the following
' - FileSystemObject.DriveExists
' - FileSystemObject.FolderExists
' - FileSystemObject.GetFolder
''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
Function GenerateTestInformation(FSO)
Dim TestFolder
Dim S
If Not FSO.DriveExists(TestDrive) Then Exit Function
If Not FSO.FolderExists(TestFilePath) Then Exit Function
Set TestFolder = FSO.GetFolder(TestFilePath)
GenerateTestInformation = GenerateAllFolderInformation(TestFolder)
End Function
''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
' DeleteTestDirectory
' Purpose:
'
Cleans up the test directory.
' Demonstrates the following
' - FileSystemObject.GetFolder
' - FileSystemObject.DeleteFile
' - FileSystemObject.DeleteFolder
' - Folder.Delete
' - File.Delete
''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
Sub DeleteTestDirectory(FSO)
Dim TestFolder
Dim SubFolder
Dim File

' Two ways to delete a file:


FSO.DeleteFile(TestFilePath & "\Beatles\OctopusGarden.txt")
Set File = FSO.GetFile(TestFilePath & "\Beatles\BathroomWindow.txt")
File.Delete
' Two ways to delete a folder:
FSO.DeleteFolder(TestFilePath & "\Beatles")
FSO.DeleteFile(TestFilePath & "\ReadMe.txt")
Set TestFolder = FSO.GetFolder(TestFilePath)
TestFolder.Delete
End Sub
''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
' CreateLyrics
' Purpose:
'
Builds a couple of text files in a folder.
' Demonstrates the following
' - FileSystemObject.CreateTextFile

' - TextStream.WriteLine
' - TextStream.Write
' - TextStream.WriteBlankLines
' - TextStream.Close
''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
Sub CreateLyrics(Folder)
Dim TextStream

Set TextStream = Folder.CreateTextFile("OctopusGarden.txt")

' Note that this does not add a line feed to the file.
TextStream.Write("Octopus' Garden ")
TextStream.WriteLine("(by Ringo Starr)")
TextStream.WriteBlankLines(1)
TextStream.WriteLine("I'd like to be under the sea in an octopus' garden in the shade,")
TextStream.WriteLine("He'd let us in, knows where we've been -- in his octopus' garden in the shade.")
TextStream.WriteBlankLines(2)
TextStream.Close
Set TextStream = Folder.CreateTextFile("BathroomWindow.txt")
TextStream.WriteLine("She Came In Through The Bathroom Window (by Lennon/McCartney)")
TextStream.WriteLine("")
TextStream.WriteLine("She came in through the bathroom window protected by a silver spoon")
TextStream.WriteLine("But now she sucks her thumb and wanders by the banks of her own lagoon")
TextStream.WriteBlankLines(2)
TextStream.Close
End Sub
''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
' GetLyrics
' Purpose:
'
Displays the contents of the lyrics files.
' Demonstrates the following
' - FileSystemObject.OpenTextFile
' - FileSystemObject.GetFile
' - TextStream.ReadAll
' - TextStream.Close
' - File.OpenAsTextStream
' - TextStream.AtEndOfStream
' - TextStream.ReadLine
''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
Function GetLyrics(FSO)
Dim TextStream
Dim S
Dim File
' There are several ways to open a text file, and several
' ways to read the data out of a file. Here's two ways
' to do each:
Set TextStream = FSO.OpenTextFile(TestFilePath & "\Beatles\OctopusGarden.txt", OpenFileForReading)

S = TextStream.ReadAll & NewLine & NewLine


TextStream.Close
Set File = FSO.GetFile(TestFilePath & "\Beatles\BathroomWindow.txt")
Set TextStream = File.OpenAsTextStream(OpenFileForReading)
Do
While Not TextStream.AtEndOfStream
S = S & TextStream.ReadLine & NewLine
Loop
TextStream.Close
GetLyrics = S
End Function
''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
' BuildTestDirectory
' Purpose:
'
Builds a directory hierarchy to demonstrate the FileSystemObject.
'
We'll build a hierarchy in this order:
'
C:\Test
'
C:\Test\ReadMe.txt
'
C:\Test\Beatles
'
C:\Test\Beatles\OctopusGarden.txt
'
C:\Test\Beatles\BathroomWindow.txt
' Demonstrates the following
' - FileSystemObject.DriveExists
' - FileSystemObject.FolderExists
' - FileSystemObject.CreateFolder
' - FileSystemObject.CreateTextFile
' - Folders.Add
' - Folder.CreateTextFile
' - TextStream.WriteLine
' - TextStream.Close
''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
Function BuildTestDirectory(FSO)
Dim
Dim
Dim
Dim

TestFolder
SubFolders
SubFolder
TextStream

' Bail out if (a) the drive does not exist, or if (b) the directory is being built
' already exists.
If Not FSO.DriveExists(TestDrive) Then
BuildTestDirectory = False
Exit Function
End If
If FSO.FolderExists(TestFilePath) Then
BuildTestDirectory = False
Exit Function
End If
Set TestFolder = FSO.CreateFolder(TestFilePath)
Set TextStream = FSO.CreateTextFile(TestFilePath & "\ReadMe.txt")
TextStream.WriteLine("My song lyrics collection")
TextStream.Close
Set SubFolders = TestFolder.SubFolders
Set SubFolder = SubFolders.Add("Beatles")
CreateLyrics SubFolder
BuildTestDirectory = True
End Function
''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''

' The main routine


' First, it creates a test directory, along with some subfolders
' and files. Then, it dumps some information about the available
' disk drives and about the test directory, and then cleans
' everything up again.
''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
Sub Main
Dim FSO
' Set up global data.
TabStop = Chr(9)
NewLine = Chr(10)

Set FSO = CreateObject("Scripting.FileSystemObject")


If Not BuildTestDirectory(FSO) Then
Print "Test directory already exists or cannot be created.
Exit Sub
End If

Cannot continue."

Print GenerateDriveInformation(FSO) & NewLine & NewLine


Print GenerateTestInformation(FSO) & NewLine & NewLine
Print GetLyrics(FSO) & NewLine & NewLine
DeleteTestDirectory(FSO)
End Sub

2001 Microsoft Corporation. All rights reserved.


Build: Topic Version 5.6.9309.1546
Scripting Runtime Library

Scripting Run-Time Reference


In This Section
FileSystemObject Properties
List of properties you can use with the FileSystemObject object model.
FileSystemObject Methods
List of methods you can use with the FileSystemObject object model.
FileSystemObject Objects
List of objects you can use with the FileSystemObject object model.
FileSystemObject Collections
List of collections you can use with the FileSystemObject object model.
Related Section
FileSystemObject Basics
A guide to the fundamentals of the FileSystemObject.

2001 Microsoft Corporation. All rights reserved.


Build: Topic Version 5.6.9309.1546
Scripting Runtime Library

FileSystemObject Properties
In This Section
AtEndOfLine Property
Returns true if the file pointer is positioned immediately before the end-of-line marker in a TextStream file; false if it is not.
AtEndOfStream Property
Returns true if the file pointer is at the end of a TextStream file; false if it is not.
Attributes Property
Sets or returns the attributes of files or folders.
AvailableSpace Property
Returns the amount of space available to a user on the specified drive or network share.
Column Property
Returns the column number of the current character position in a TextStream file.
CompareMode Property
Sets and returns the comparison mode for comparing string keys in a Dictionary object.
Count Property
Returns the number of items in a collection or Dictionary object.
DateCreated Property
Returns the date and time that the specified file or folder was created. Read-only.
DateLastAccessed Property
Returns the date and time that the specified file or folder was last accessed.
DateLastModified Property
Returns the date and time that the specified file or folder was last modified.
Drive Property
Returns the drive letter of the drive on which the specified file or folder resides.
DriveLetter Property
Returns the drive letter of a physical local drive or a network share.
Drives Property
Returns a Drives collection consisting of all Drive objects available on the local machine.
DriveType Property
Returns a value indicating the type of a specified drive.
Files Property
Returns a Files collection consisting of all File objects contained in the specified folder, including those with hidden and system file attributes set.
FileSystemProperty
Returns the type of file system in use for the specified drive.
FreeSpace Property
Returns the amount of free space available to a user on the specified drive or network share.
IsReady Property
Returns true if the specified drive is ready; false if it is not.
IsRootFolder Property
Returns true if the specified folder is the root folder; false if it is not.
Item Property
Sets or returns an item for a specified key in a Dictionary object. For collections, returns an item based on the specified key.
Key Property
Sets a key in a Dictionary object.

Line Property
Returns the current line number in a TextStream file.
Name Property
Sets or returns the name of a specified file or folder.
ParentFolder Property
Returns the folder object for the parent of the specified file or folder.
Path Property
Returns the path for a specified file, folder, or drive.
RootFolder Property
Returns a Folder object representing the root folder of a specified drive.
SerialNumber Property
Returns the decimal serial number used to uniquely identify a disk volume.
ShareName Property
Returns the network share name for a specified drive.
ShortName Property
Returns the short name used by programs that require the earlier 8.3 naming convention.
ShortPath Property
Returns the short path used by programs that require the earlier 8.3 file naming convention.
Size Property
For files, returns the size, in bytes, of the specified file. For folders, returns the size, in bytes, of all files and subfolders contained in the folder.
SubFolders Property
Returns a Folders collection consisting of all folders contained in a specified folder, including those with hidden and system file attributes set.
TotalSize Property
Returns the total space, in bytes, of a drive or network share.
Type Property
Returns information about the type of a file or folder.
VolumeName Property
Sets or returns the volume name of the specified drive.
Related Sections
Scripting Run-Time Reference
List of elements that make up Scripting Run-Time Reference.
FileSystemObject Basics
A guide to the fundamentals of the FileSystemObject.

2001 Microsoft Corporation. All rights reserved.


Build: Topic Version 5.6.9309.1546
Scripting Runtime Library

AtEndOfLine Property
Returns true if the file pointer is positioned immediately before the end-of-line marker in a TextStream file; false if it is not. Read-only.
object.AtEndOfLine

The object is always the name of a TextStream object.


Remarks
The AtEndOfLine property applies only to TextStream files that are open for reading; otherwise, an error occurs.
The following code illustrates the use of the AtEndOfLine property:
[JScript]
function GetALine(filespec)
{
var fso, a, s, ForReading;
ForReading = 1, s = "";
fso = new ActiveXObject("Scripting.FileSystemObject");
a = fso.OpenTextFile(filespec, ForReading, false);
while (!a.AtEndOfLine)
{
s += a.Read(1);
}
a.Close( );
return(s);
}
[VBScript]
Function ReadEntireFile(filespec)
Const ForReading = 1
Dim fso, theFile, retstring
Set fso = CreateObject("Scripting.FileSystemObject")
Set theFile = fso.OpenTextFile(filespec, ForReading, False)
Do While theFile.AtEndOfLine <> True
retstring = theFile.Read(1)
Loop
theFile.Close
ReadEntireFile = retstring
End Function

See Also
AtEndOfStream Property
Applies To: TextStream Object

2001 Microsoft Corporation. All rights reserved.


Build: Topic Version 5.6.9309.1546
Scripting Runtime Library

AtEndOfStream Property
Returns true if the file pointer is at the end of a TextStream file; false if it is not. Read-only.
object.AtEndOfStream

The object is always the name of a TextStream object.


Remarks
The AtEndOfStream property applies only to TextStream files that are open for reading, otherwise, an error occurs.

The following code illustrates the use of the AtEndOfStream property:


[JScript]
function GetALine(filespec)
{
var fso, f, s, ForReading;
ForReading = 1, s = "";
fso = new ActiveXObject("Scripting.FileSystemObject");
f = fso.OpenTextFile(filespec, ForReading, false);
while (!f.AtEndOfStream)
s += f.ReadLine( );
f.Close( );
return(s);
}
[VBScript]
Function ReadEntireFile(filespec)
Const ForReading = 1
Dim fso, theFile, retstring
Set fso = CreateObject("Scripting.FileSystemObject")
Set theFile = fso.OpenTextFile(filespec, ForReading, False)
Do While theFile.AtEndOfStream <> True
retstring = theFile.ReadLine
Loop
theFile.Close
ReadEntireFile = retstring
End Function

See Also
AtEndOfLine Property
Applies To: TextStream Object

2001 Microsoft Corporation. All rights reserved.


Build: Topic Version 5.6.9309.1546
Scripting Runtime Library

Attributes Property
Sets or returns the attributes of files or folders. Read/write or read-only, depending on the attribute.
object.Attributes [= newattributes]

Arguments
object
Required. Always the name of a File or Folder object.
newattributes
Optional. If provided, newattributes is the new value for the attributes of the specified object.
Settings
The newattributes argument can have any of the following values or any logical combination of the following values:
Constant
Normal
ReadOnly
Hidden
System
Volume
Directory
Archive
Alias
Compressed

Value
0
1
2
4
8
16
32
64
128

Description
Normal file. No attributes are set.
Read-only file. Attribute is read/write.
Hidden file. Attribute is read/write.
System file. Attribute is read/write.
Disk drive volume label. Attribute is read-only.
Folder or directory. Attribute is read-only.
File has changed since last backup. Attribute is read/write.
Link or shortcut. Attribute is read-only.
Compressed file. Attribute is read-only.

Remarks
The following code illustrates the use of the Attributes property with a file:
[JScript]
function ToggleArchiveBit(filespec)
{
var fso, f, r, s;
fso = new ActiveXObject("Scripting.FileSystemObject");
f = fso.GetFile(filespec)
if (f.attributes && 32)
{
f.attributes = f.attributes - 32;
s = "Archive bit is cleared.";
}
else
{
f.attributes = f.attributes + 32;
s =
"Archive bit is set.";
}
return(s);
}
[VBScript]
Function ToggleArchiveBit(filespec)
Dim fso, f
Set fso = CreateObject("Scripting.FileSystemObject")
Set f = fso.GetFile(filespec)
If f.attributes and 32 Then
f.attributes = f.attributes - 32
ToggleArchiveBit = "Archive bit is cleared."
Else
f.attributes = f.attributes + 32
ToggleArchiveBit = "Archive bit is set."
End If
End Function

See Also
DateCreated Property | DateLastAccessed Property | DateLastModified Property | Drive Property | Files Property | IsRootFolder Property | Name Property | ParentFolder Property | Path Property | ShortName Property | ShortPath
Property | Size Property | SubFolders Property | Type Property
Applies To: File Object | Folder Object

2001 Microsoft Corporation. All rights reserved.


Build: Topic Version 5.6.9309.1546
Scripting Runtime Library

AvailableSpace Property
Returns the amount of space available to a user on the specified drive or network share.
object.AvailableSpace

The object is always a Drive object.


Remarks
The value returned by the AvailableSpace property is typically the same as that returned by the FreeSpace property. Differences may occur between the two for computer systems that support quotas.
The following code illustrates the use of the AvailableSpace property:
[JScript]
function ShowAvailableSpace(drvPath)
{
var fso, d, s;
fso = new ActiveXObject("Scripting.FileSystemObject");
d = fso.GetDrive(fso.GetDriveName(drvPath));
s = "Drive " + drvPath.toUpperCase() + " - ";
s += d.VolumeName + "<br>";
s += "Available Space: " + d.AvailableSpace/1024 + " Kbytes";
return(s);
}
[VBScript]
Function ShowAvailableSpace(drvPath)
Dim fso, d, s
Set fso = CreateObject("Scripting.FileSystemObject")
Set d = fso.GetDrive(fso.GetDriveName(drvPath))
s = "Drive " & UCase(drvPath) & " - "
s = s & d.VolumeName
& "<BR>"
s = s & "Available Space: " & FormatNumber(d.AvailableSpace/1024, 0)
s = s & " Kbytes"
ShowAvailableSpace = s
End Function

See Also
DriveLetter Property | DriveType Property | FileSystem Property | FreeSpace Property | IsReady Property | Path Property | RootFolder Property | SerialNumber Property | ShareName Property | TotalSize Property | VolumeName
Property
Applies To: Drive Object

2001 Microsoft Corporation. All rights reserved.


Build: Topic Version 5.6.9309.1546
Scripting Runtime Library

Column Property
Read-only property that returns the column number of the current character position in a TextStream file.
object.Column

The object is always the name of a TextStream object.


Remarks
After a newline character has been written, but before any other character is written, Column is equal to 1.
The following examples illustrates the use of the Column property:
[JScript]
function GetColumn()
{
var fso, f, m;
var ForReading = 1, ForWriting = 2;
fso = new ActiveXObject("Scripting.FileSystemObject");
f = fso.OpenTextFile("c:\\testfile.txt", ForWriting, true);
f.Write("Hello World!");
f.Close();
f = fso.OpenTextFile("c:\\testfile.txt", ForReading);
m = f.ReadLine();
return(f.Column);
}
[VBScript]
Function GetColumn
Const ForReading = 1, ForWriting = 2
Dim fso, f, m
Set fso = CreateObject("Scripting.FileSystemObject")
Set f = fso.OpenTextFile("c:\testfile.txt", ForWriting, True)
f.Write "Hello world!"
f.Close
Set f = fso.OpenTextFile("c:\testfile.txt", ForReading)
m =
f.ReadLine
GetColumn = f.Column
End Function

See Also
Line Property
Applies To: TextStream Object

2001 Microsoft Corporation. All rights reserved.


Build: Topic Version 5.6.9309.1546
Scripting Runtime Library

CompareMode Property
Sets and returns the comparison mode for comparing string keys in a Dictionary object.
object.CompareMode[ = compare]

Arguments
object
Required. Always the name of a Dictionary object.
compare
Optional. If provided, compare is a value representing the comparison mode. Acceptable values are 0 (Binary), 1 (Text), 2 (Database). Values greater than 2 can be used to refer to comparisons using specific Locale IDs
(LCID).
Remarks
An error occurs if you try to change the comparison mode of a Dictionary object that already contains data.
The following example illustrates the use of the CompareMode property:
[JScript]function TestCompareMode(key)
{
// Create some variables.
var a, d;
var BinaryCompare = 0, TextCompare = 1;
d = new ActiveXObject("Scripting.Dictionary");
// Set Compare mode to Text.
d.CompareMode = TextCompare;
// Add some keys and items.
d.Add("a", "Athens");
d.Add("b", "Belgrade");
d.Add("c", "Cairo");
return(d.Item(key));
}
[VBScript
Dim d
Set d = CreateObject("Scripting.Dictionary")
d.CompareMode = vbTextCompare
d.Add "a", "Athens"
' Add some keys and items.
d.Add "b", "Belgrade"
d.Add "c", "Cairo"
d.Add "B", "Baltimore"
' Add method fails on this line because the
' letter b already exists in the Dictionary.

See Also
Key Property
Applies To: Dictionary Object

2001 Microsoft Corporation. All rights reserved.


Build: Topic Version 5.6.9309.1546
Scripting Runtime Library

DateLastAccessed Property
Returns the date and time that the specified file or folder was last accessed. Read-only.
object.DateLastAccessed

The object is always a File or Folder object.


Remarks
The following code illustrates the use of the DateLastAccessed property with a file:
[JScript]
function ShowFileAccessInfo(filespec)
{
var fso, f, s;
fso = new ActiveXObject("Scripting.FileSystemObject");
f = fso.GetFile(filespec);
s = filespec.toUpperCase() + "<br>";
s += "Created: " + f.DateCreated + "<br>";
s += "Last Accessed: " + f.DateLastAccessed + "<br>";
s += "Last Modified: " + f.DateLastModified;
return(s);
}
[VBScript]
Function ShowFileAccessInfo(filespec)
Dim fso, f, s
Set fso = CreateObject("Scripting.FileSystemObject")
Set f = fso.GetFile(filespec)
s = UCase(filespec) & "<BR>"
s = s & "Created: " & f.DateCreated & "<BR>"
s = s & "Last Accessed: " & f.DateLastAccessed & "<BR>"
s = s & "Last Modified: " & f.DateLastModified
ShowFileAccessInfo = s
End Function

Note This method depends on the underlying operating system for its behavior. If the operating system does not support providing time information, none will be returned.
See Also
Attributes Property | DateCreated Property | DateLastModified Property | Drive Property | Files Property | IsRootFolder Property | Name Property | ParentFolder Property | Path Property | ShortName Property | ShortPath
Property | Size Property | SubFolders Property | Type Property
Applies To: File Object | Folder Object

2001 Microsoft Corporation. All rights reserved.


Build: Topic Version 5.6.9309.1546
Scripting Runtime Library

DateLastModified Property
Returns the date and time that the specified file or folder was last modified. Read-only.
object.DateLastModified

The object is always a File or Folder object.


Remarks
The following code illustrates the use of the DateLastModified property with a file:
[JScript]
function ShowFileAccessInfo(filespec)
{
var fso, f, s;
fso = new ActiveXObject("Scripting.FileSystemObject");
f = fso.GetFile(filespec);
s = filespec.toUpperCase() + "<br>";
s += "Created: " + f.DateCreated + "<br>";
s += "Last Accessed: " + f.DateLastAccessed + "<br>";
s += "Last Modified: " + f.DateLastModified;
return(s);
}
[VBScript]
Function ShowFileAccessInfo(filespec)
Dim fso, f, s
Set fso = CreateObject("Scripting.FileSystemObject")
Set f = fso.GetFile(filespec)
s = UCase(filespec) & "<BR>"
s = s & "Created: " & f.DateCreated & "<BR>"
s = s & "Last Accessed: " & f.DateLastAccessed & "<BR>"
s = s & "Last Modified: " & f.DateLastModified
ShowFileAccessInfo = s
End Function

See Also
Attributes Property | DateCreated Property | DateLastAccessed Property | Drive Property | Files Property | IsRootFolder Property | Name Property | ParentFolder Property | Path Property | ShortName Property | ShortPath
Property | Size Property | SubFolders Property | Type Property
Applies To: File Object | Folder Object

2001 Microsoft Corporation. All rights reserved.


Build: Topic Version 5.6.9309.1546
Scripting Runtime Library

Drive Property
Returns the drive letter of the drive on which the specified file or folder resides. Read-only.
object.Drive

The object is always a File or Folder object.


Remarks
The following code illustrates the use of the Drive property:
[JScript]
function ShowFileAccessInfo(filespec)
{
var fso, f, s;
fso = new ActiveXObject("Scripting.FileSystemObject");
f = fso.GetFile(filespec);
s = f.Name + " on Drive " + f.Drive + "<br>";
s += "Created: " + f.DateCreated + "<br>";
s += "Last Accessed: " + f.DateLastAccessed + "<br>";
s += "Last Modified: " + f.DateLastModified;
return(s);
}
[VBScript]
Function ShowFileAccessInfo(filespec)
Dim fso, f, s
Set fso = CreateObject("Scripting.FileSystemObject")
Set f = fso.GetFile(filespec)
s = f.Name & " on Drive " & UCase(f.Drive) & "<BR>"
s = s & "Created: " & f.DateCreated & "<BR>"
s = s & "Last Accessed: " & f.DateLastAccessed & "<BR>"
s = s & "Last Modified: " & f.DateLastModified
ShowFileAccessInfo = s
End Function

See Also
Attributes Property | DateCreated Property | DateLastAccessed Property | DateLastModified Property | Files Property | IsRootFolder Property | Name Property | ParentFolder Property | Path Property | ShortName Property |
ShortPath Property | Size Property | SubFolders Property | Type Property
Applies To: File Object | Folder Object

2001 Microsoft Corporation. All rights reserved.


Build: Topic Version 5.6.9309.1546
Scripting Runtime Library

DriveLetter Property
Returns the drive letter of a physical local drive or a network share. Read-only.
object.DriveLetter

The object is always a Drive object.


Remarks

The DriveLetter property returns a zero-length string ("") if the specified drive is not associated with a drive letter, for example, a network share that has not been mapped to a drive letter.
The following code illustrates the use of the DriveLetter property:
[JScript]
function ShowDriveLetter(drvPath)
{
var fso, d, s;
fso = new ActiveXObject("Scripting.FileSystemObject");
d = fso.GetDrive(fso.GetDriveName(drvPath));
s = "Drive " + d.DriveLetter.toUpperCase( ) + ": - ";
s += d.VolumeName + "<br>";
s += "Available Space: " + d.AvailableSpace/1024 + " Kbytes";
return(s);
}
[VBScript]
Function ShowDriveLetter(drvPath)
Dim fso, d, s
Set fso = CreateObject("Scripting.FileSystemObject")
Set d = fso.GetDrive(fso.GetDriveName(drvPath))
s = "Drive " & d.DriveLetter & ": - "
s = s & d.VolumeName & "<BR>"
s = s & "Free Space: " & FormatNumber(d.FreeSpace/1024, 0)
s = s & " Kbytes"
ShowDriveLetter = s
End Function

See Also
AvailableSpace Property | DriveType Property | FileSystem Property | FreeSpace Property | IsReady Property | Path Property | RootFolder Property | SerialNumber Property | ShareName Property | TotalSize Property |
VolumeName Property
Applies To: Drive Object

2001 Microsoft Corporation. All rights reserved.


Build: Topic Version 5.6.9309.1546
Scripting Runtime Library

Drives Property
Returns a Drives collection consisting of all Drive objects available on the local machine.
object.Drives

The object is always a FileSystemObject.


Remarks
Removable-media drives need not have media inserted for them to appear in the Drives collection.
[JScript]
You can iterate the members of the Drives collection using the Enumerator object and the for statement:
[JScript]
function ShowDriveList()
{
var fso, s, n, e, x;
fso = new ActiveXObject("Scripting.FileSystemObject");
e = new Enumerator(fso.Drives);
s = "";
for (; !e.atEnd(); e.moveNext())
{
x = e.item();
s = s + x.DriveLetter;
s += " - ";
if (x.DriveType == 3)
n = x.ShareName;
else if (x.IsReady)
n = x.VolumeName;
else
n = "[Drive not ready]";
s +=
n + "<br>";
}
return(s);
}

[VBScript]
You can iterate the members of the Drives collection using a For Each...Next construct as illustrated in the following code:
[VBScript]
Function ShowDriveList
Dim fso, d, dc, s, n
Set fso = CreateObject("Scripting.FileSystemObject")
Set dc = fso.Drives
For Each d in dc
n = ""
s = s & d.DriveLetter & " - "
If d.DriveType = 3 Then
n = d.ShareName
ElseIf d.IsReady Then
n = d.VolumeName
End If
s = s & n & "<BR>"
Next
ShowDriveList = s
End Function

See Also
Drives Collection | Files Property | SubFolders Property
Applies To: FileSystemObject Object

2001 Microsoft Corporation. All rights reserved.


Build: Topic Version 5.6.9309.1546

Scripting Runtime Library

DriveType Property
Returns a value indicating the type of a specified drive.
object.DriveType

The object is always a Drive object.


Remarks
The following code illustrates the use of the DriveType property:
[JScript]
function ShowDriveType(drvpath)
{
var fso, d, s, t;
fso = new ActiveXObject("Scripting.FileSystemObject");
d = fso.GetDrive(drvpath);
switch (d.DriveType)
{
case 0: t = "Unknown"; break;
case 1: t = "Removable"; break;
case 2: t = "Fixed"; break;
case 3: t = "Network"; break;
case 4: t = "CD-ROM"; break;
case 5: t = "RAM Disk"; break;
}
s = "Drive " + d.DriveLetter + ": - " + t;
return(s);
}
[VBScript]
Function ShowDriveType(drvpath)
Dim fso, d, t
Set fso = CreateObject("Scripting.FileSystemObject")
Set d = fso.GetDrive(drvpath)
Select Case d.DriveType
Case 0: t = "Unknown"
Case 1: t = "Removable"
Case 2: t = "Fixed"
Case 3: t = "Network"
Case 4: t = "CD-ROM"
Case 5: t = "RAM Disk"
End Select
ShowDriveType = "Drive " & d.DriveLetter & ": - " & t
End Function

See Also
AvailableSpace Property | DriveLetter Property | FileSystem Property | FreeSpace Property | IsReady Property | Path Property | RootFolder Property | SerialNumber Property | ShareName Property | TotalSize Property |
VolumeName Property
Applies To: Drive Object

2001 Microsoft Corporation. All rights reserved.


Build: Topic Version 5.6.9309.1546
Scripting Runtime Library

FileSystem Property
Returns the type of file system in use for the specified drive.
object.FileSystem

The object is always a Drive object.


Remarks
Available return types include FAT, NTFS, and CDFS.
The following code illustrates the use of the FileSystem property:
[JScript]
function ShowFileSystemType(drvPath)
{
var fso,d, s;
fso = new ActiveXObject("Scripting.FileSystemObject");
d = fso.GetDrive(drvPath);
s = d.FileSystem;
return(s);
}
[VBScript]
Function ShowFileSystemType(drvspec)
Dim fso,d
Set fso = CreateObject("Scripting.FileSystemObject")
Set d = fso.GetDrive(drvspec)
ShowFileSystemType = d.FileSystem
End Function

See Also
AvailableSpace Property | DriveLetter Property | DriveType Property | FreeSpace Property | IsReady Property | Path Property | RootFolder Property | SerialNumber Property | ShareName Property | TotalSize Property |
VolumeName Property
Applies To: Drive Object

2001 Microsoft Corporation. All rights reserved.


Build: Topic Version 5.6.9309.1546
Scripting Runtime Library

FreeSpace Property
Returns the amount of free space available to a user on the specified drive or network share. Read-only.

object.FreeSpace

The object is always a Drive object.


Remarks
The value returned by the FreeSpace property is typically the same as that returned by the AvailableSpace property. Differences may occur between the two for computer systems that support quotas.
The following code illustrates the use of the FreeSpace property:
[JScript]
function ShowFreeSpace(drvPath)
{
var fso, d, s;
fso = new ActiveXObject("Scripting.FileSystemObject");
d = fso.GetDrive(fso.GetDriveName(drvPath));
s = "Drive " + drvPath.toUpperCase( ) + " - ";
s += d.VolumeName + "<br>";
s += "Free Space: " + d.FreeSpace/1024 + " Kbytes";
return(s);
}
[VBScript]
Function ShowFreeSpace(drvPath)
Dim fso, d, s
Set fso = CreateObject("Scripting.FileSystemObject")
Set d = fso.GetDrive(fso.GetDriveName(drvPath))
s = "Drive " & UCase(drvPath) & " - "
s = s & d.VolumeName
& "<BR>"
s = s & "Free Space: " & FormatNumber(d.FreeSpace/1024, 0)
s = s & " Kbytes"
ShowFreeSpace = s
End Function

See Also
AvailableSpace Property | DriveLetter Property | DriveType Property | FileSystem Property | IsReady Property | Path Property | RootFolder Property | SerialNumber Property | ShareName Property | TotalSize Property |
VolumeName Property
Applies To: Drive Object

2001 Microsoft Corporation. All rights reserved.


Build: Topic Version 5.6.9309.1546
Scripting Runtime Library

IsReady Property
Returns True if the specified drive is ready; False if it is not.
object.IsReady

The object is always a Drive object.


Remarks
For removable-media drives and CD-ROM drives, IsReady returns True only when the appropriate media is inserted and ready for access.
The following code illustrates the use of the IsReady property:
[JScript]
function ShowDriveInfo(drvpath)
{
var fso, d, s, t;
fso = new ActiveXObject("Scripting.FileSystemObject")
d = fso.GetDrive(drvpath)
switch (d.DriveType)
{
case 0: t = "Unknown"; break;
case 1: t = "Removable"; break;
case 2: t = "Fixed"; break;
case 3: t = "Network"; break;
case 4: t = "CD-ROM"; break;
case 5: t = "RAM Disk"; break;
}
s = "Drive " + d.DriveLetter + ": - " + t;
if (d.IsReady)
s += "<br>" + "Drive is Ready.";
else
s += "<br>" + "Drive is not Ready.";
return(s);
}
[VBScript]
Function ShowDriveInfo(drvpath)
Dim fso, d, s, t
Set fso = CreateObject("Scripting.FileSystemObject")
Set d = fso.GetDrive(drvpath)
Select Case d.DriveType
Case 0: t = "Unknown"
Case 1: t = "Removable"
Case 2: t = "Fixed"
Case 3: t = "Network"
Case 4: t = "CD-ROM"
Case 5: t = "RAM Disk"
End Select
s = "Drive " & d.DriveLetter & ": - " & t
If d.IsReady Then
s = s & "<BR>" & "Drive is Ready."
Else
s = s & "<BR>" & "Drive is not Ready."
End If
ShowDriveInfo = s
End Function

See Also
AvailableSpace Property | DriveLetter Property | DriveType Property | FileSystem Property | FreeSpace Property | Path Property | RootFolder Property | SerialNumber Property | ShareName Property | TotalSize Property |
VolumeName Property
Applies To: Drive Object

2001 Microsoft Corporation. All rights reserved.

Build: Topic Version 5.6.9309.1546


Scripting Runtime Library

IsRootFolder Property
Returns True if the specified folder is the root folder; False if it is not.
object.IsRootFolder

The object is always a Folder object.


Remarks
The following code illustrates the use of the IsRootFolder property:
[JScript]
function DisplayLevelDepth(pathspec)
{
var fso, f, n, s = "";
fso = new ActiveXObject("Scripting.FileSystemObject");
f = fso.GetFolder(pathspec);
n = 0;
if (f.IsRootFolder)
s = "The specified folder is the root folder."
else
{
do
{
f = f.ParentFolder;
n++;
}
while (!f.IsRootFolder)
s = "The specified folder is nested " + n + " levels deep."
}
return(s);
}
[VBScript]
Function DisplayLevelDepth(pathspec)
Dim fso, f, n
Set fso = CreateObject("Scripting.FileSystemObject")
Set f = fso.GetFolder(pathspec)
If f.IsRootFolder Then
DisplayLevelDepth = "The specified folder is the root folder."
Else
Do Until f.IsRootFolder
Set f = f.ParentFolder
n = n + 1
Loop
DisplayLevelDepth = "The specified folder is nested " & n & " levels deep."
End If
End Function

See Also
Attributes Property | DateCreated Property | DateLastAccessed Property | DateLastModified Property | Drive Property | Files Property | Name Property | ParentFolder Property | Path Property | ShortName Property | ShortPath
Property | Size Property | SubFolders Property | Type Property
Applies To: Folder Object

2001 Microsoft Corporation. All rights reserved.


Build: Topic Version 5.6.9309.1546
Scripting Runtime Library

Line Property
Read-only property that returns the current line number in a TextStream file.
object.Line

The object is always the name of a TextStream object.


Remarks
After a file is initially opened and before anything is written, Line is equal to 1.
The following example illustrates the use of the Line property:
[JScript]
function GetLine()
{
var fso, f, r
var ForReading = 1, ForWriting = 2;
fso = new ActiveXObject("Scripting.FileSystemObject")
f = fso.OpenTextFile("c:\\textfile.txt", ForWriting, true)
f.WriteLine("Hello world!");
f.WriteLine("JScript is fun");
f.Close();
f = fso.OpenTextFile("c:\\textfile.txt", ForReading);
r =
f.ReadAll();
return(f.Line);
}
[VBScript]
Function GetLine
Const ForReading = 1, ForWriting = 2
Dim fso, f, ra
Set fso = CreateObject("Scripting.FileSystemObject")
Set f = fso.OpenTextFile("c:\testfile.txt", ForWriting, True)
f.Write "Hello world!" & vbCrLf & "VB Script is fun!" & vbCrLf
Set f = fso.OpenTextFile("c:\testfile.txt", ForReading)
ra =
f.ReadAll
GetLine = f.Line
End Function

See Also
Column Property
Applies To: TextStream Object

2001 Microsoft Corporation. All rights reserved.


Build: Topic Version 5.6.9309.1546
Scripting Runtime Library

Name Property
Sets or returns the name of a specified file or folder. Read/write.
object.Name [= newname]

Arguments
object
Required. Always the name of a File or Folder object.
newname
Optional. If provided, newname is the new name of the specified object.
Remarks
The following code illustrates the use of the Name property:
[JScript]
function ShowFileAccessInfo(filespec)
{
var fso, f, s;
fso = new ActiveXObject("Scripting.FileSystemObject");
f = fso.GetFile(filespec);
s = f.Name + " on Drive " + f.Drive + "<br>";
s += "Created: " + f.DateCreated + "<br>";
s += "Last Accessed: " + f.DateLastAccessed + "<br>";
s += "Last Modified: " + f.DateLastModified;
return(s);
}
[VBScript]
Function ShowFileAccessInfo(filespec)
Dim fso, f, s
Set fso = CreateObject("Scripting.FileSystemObject")
Set f = fso.GetFile(filespec)
s = f.Name & " on Drive " & UCase(f.Drive) & "<BR>"
s = s & "Created: " & f.DateCreated & "<BR>"
s = s & "Last Accessed: " & f.DateLastAccessed & "<BR>"
s = s & "Last Modified: " & f.DateLastModified
ShowFileAccessInfo = s
End Function

See Also
Attributes Property | DateCreated Property | DateLastAccessed Property | DateLastModified Property | Drive Property | Files Property | IsRootFolder Property | ParentFolder Property | Path Property | ShortName Property |
ShortPath Property | Size Property | SubFolders Property | Type Property
Applies To: File Object | Folder Object

2001 Microsoft Corporation. All rights reserved.


Build: Topic Version 5.6.9309.1546
Scripting Runtime Library

ParentFolder Property
Returns the folder object for the parent of the specified file or folder. Read-only.
object.ParentFolder

The object is always a File or Folder object.


Remarks
The following code illustrates the use of the ParentFolder property with a file:
[JScript]
function ShowFileAccessInfo(filespec)
{
var fso, f, s;
fso = new ActiveXObject("Scripting.FileSystemObject");
f = fso.GetFile(filespec);
s = f.Name + " in " + f.ParentFolder + "<br>";
s += "Created: " + f.DateCreated + "<br>";
s += "Last Accessed: " + f.DateLastAccessed + "<br>";
s += "Last Modified: " + f.DateLastModified;
return(s);
}
[VBScript]
Function ShowFileAccessInfo(filespec)
Dim fso, f, s
Set fso = CreateObject("Scripting.FileSystemObject")
Set f = fso.GetFile(filespec)
s = UCase(f.Name) & " in " & UCase(f.ParentFolder) & "<BR>"
s = s & "Created: " & f.DateCreated & "<BR>"
s = s & "Last Accessed: " & f.DateLastAccessed & "<BR>"
s = s & "Last Modified: " & f.DateLastModified
ShowFileAccessInfo = s
End Function

See Also
Attributes Property | DateCreated Property | DateLastAccessed Property | DateLastModified Property | Drive Property | Files Property | IsRootFolder Property | Name Property | Path Property | ShortName Property | ShortPath
Property | Size Property | SubFolders Property | Type Property
Applies To: File Object | Folder Object

2001 Microsoft Corporation. All rights reserved.


Build: Topic Version 5.6.9309.1546
Scripting Runtime Library

Path Property
Returns the path for a specified file, folder, or drive.
object.Path

The object is always a File, Folder, or Drive object.


Remarks
For drive letters, the root drive is not included. For example, the path for the C drive is C:, not C:\.
The following code illustrates the use of the Path property with a File object:
[JScript]
function ShowFileAccessInfo(filespec)
{
var fso, d, f, s;
fso = new ActiveXObject("Scripting.FileSystemObject");
f = fso.GetFile(filespec);
s = f.Path.toUpperCase() + "<br>";
s += "Created: " + f.DateCreated + "<br>";
s += "Last Accessed: " + f.DateLastAccessed + "<br>";
s += "Last Modified: " + f.DateLastModified
return(s);
}
[VBScript]
Function ShowFileAccessInfo(filespec)
Dim fso, d, f, s
Set fso = CreateObject("Scripting.FileSystemObject")
Set f = fso.GetFile(filespec)
s = UCase(f.Path) & "<BR>"
s = s & "Created: " & f.DateCreated & "<BR>"
s = s & "Last Accessed: " & f.DateLastAccessed & "<BR>"
s = s & "Last Modified: " & f.DateLastModified
ShowFileAccessInfo = s
End Function

See Also
Attributes Property | AvailableSpace Property | DateCreated Property | DateLastAccessed Property | DateLastModified Property | Drive Property | DriveLetter Property | DriveType Property | Files Property | FileSystem Property
| FreeSpace Property | IsReady Property | IsRootFolder Property | Name Property | ParentFolder Property | RootFolder Property | SerialNumber Property | ShareName Property | ShortName Property | ShortPath Property | Size
Property | SubFolders Property | TotalSize Property | Type Property | VolumeName Property
Applies To: Drive Object | File Object | Folder Object

2001 Microsoft Corporation. All rights reserved.


Build: Topic Version 5.6.9309.1546
Scripting Runtime Library

RootFolder Property
Returns a Folder object representing the root folder of a specified drive. Read-only.
object.RootFolder

The object is always a Drive object.


Remarks
All the files and folders contained on the drive can be accessed using the returned Folder object.
The following example illustrates the use of the RootFolder property:
[JScript]
function GetRootFolder(drv)
{
var fso,d;
fso = new ActiveXObject("Scripting.FileSystemObject");
if (fso.DriveExists(drv))
{
d = fso.GetDrive(drv);
return(d.RootFolder);
}
else
return(false);
}
[VBScript]
Function ShowRootFolder(drvspec)
Dim fso, f
Set fso = CreateObject("Scripting.FileSystemObject")
Set f = fso.GetDrive(drvspec)
ShowRootFolder = f.RootFolder
End Function

See Also
AvailableSpace Property | DriveLetter Property | DriveType Property | FileSystem Property | FreeSpace Property | IsReady Property | Path Property | SerialNumber Property | ShareName Property | TotalSize Property |
VolumeName Property
Applies To: Drive Object

2001 Microsoft Corporation. All rights reserved.


Build: Topic Version 5.6.9309.1546
Scripting Runtime Library

SerialNumber Property
Returns the decimal serial number used to uniquely identify a disk volume.
object.SerialNumber

The object is always a Drive object.

Remarks
You can use the SerialNumber property to ensure that the correct disk is inserted in a drive with removable media.
The following code illustrates the use of the SerialNumber property:
[JScript]
function ShowDriveInfo(drvpath){
var fso, d, s, t;
fso = new ActiveXObject("Scripting.FileSystemObject");
d = fso.GetDrive(fso.GetDriveName(fso.GetAbsolutePathName(drvpath)));
switch (d.DriveType)
{
case 0: t = "Unknown"; break;
case 1: t = "Removable"; break;
case 2: t = "Fixed"; break;
case 3: t = "Network"; break;
case 4: t = "CD-ROM"; break;
case 5: t = "RAM Disk"; break;
}
s = "Drive " + d.DriveLetter + ": - " + t;
s += "<br>" + "SN: " + d.SerialNumber;
return(s);
}
[VBScript]
Function ShowDriveInfo(drvpath)
Dim fso, d, s, t
Set fso = CreateObject("Scripting.FileSystemObject")
Set d = fso.GetDrive(fso.GetDriveName(fso.GetAbsolutePathName(drvpath)))
Select Case d.DriveType
Case 0: t = "Unknown"
Case 1: t = "Removable"
Case 2: t = "Fixed"
Case 3: t = "Network"
Case 4: t = "CD-ROM"
Case 5: t = "RAM Disk"
End Select
s = "Drive " & d.DriveLetter & ": - " & t
s = s & "<BR>" & "SN: " & d.SerialNumber
ShowDriveInfo = s
End Function

2001 Microsoft Corporation. All rights reserved.


Build: Topic Version 5.6.9309.1546
Scripting Runtime Library

ShareName Property
Returns the network share name for a specified drive.
object.ShareName

The object is always a Drive object.


Remarks
If object is not a network drive, the ShareName property returns a zero-length string ("").
The following code illustrates the use of the ShareName property:
[JScript]
function ShowDriveInfo(drvpath)
{
var fso, d, s;
fso = new ActiveXObject("Scripting.FileSystemObject");
d = fso.GetDrive(fso.GetDriveName(fso.GetAbsolutePathName(drvpath)));
s = "Drive " + d.DriveLetter + ": - " + d.ShareName;
return(s);
}
[VBScript]
Function ShowDriveInfo(drvpath)
Dim fso, d
Set fso = CreateObject("Scripting.FileSystemObject")
Set d = fso.GetDrive(fso.GetDriveName(fso.GetAbsolutePathName(drvpath)))
ShowDriveInfo = "Drive " & d.DriveLetter & ": - " & d.ShareName
End Function

See Also
AvailableSpace Property | DriveLetter Property | DriveType Property | FileSystem Property | FreeSpace Property | IsReady Property | Path Property | RootFolder Property | SerialNumber Property | TotalSize Property |
VolumeName Property
Applies To: Drive Object

2001 Microsoft Corporation. All rights reserved.


Build: Topic Version 5.6.9309.1546
Scripting Runtime Library

ShortName Property
Returns the short name used by programs that require the earlier 8.3 naming convention.
object.ShortName

The object is always a File or Folder object.


Remarks
The following code illustrates the use of the ShortName property with a File object:
[JScript]
function ShowShortName(filespec)
{
var fso, f, s;
fso = new ActiveXObject("Scripting.FileSystemObject");
f = fso.GetFile(filespec);

s = "The short name for " + "" + f.Name;


s += "" + "<br>";
s += "is: " + "" + f.ShortName + "";
return(s);
}
[VBScript]
Function ShowShortName(filespec)
Dim fso, f, s
Set fso = CreateObject("Scripting.FileSystemObject")
Set f = fso.GetFile(filespec)
s = "The short name for "
& UCase(f.Name) & "<BR>"
s = s & "is: " & f.ShortName
ShowShortName = s
End Function

See Also
Attributes Property | DateCreated Property | DateLastAccessed Property | DateLastModified Property | Drive Property | Files Property | IsRootFolder Property | Name Property | ParentFolder Property | Path Property | ShortPath
Property | Size Property | SubFolders Property | Type Property
Applies To: File Object | Folder Object

2001 Microsoft Corporation. All rights reserved.


Build: Topic Version 5.6.9309.1546
Scripting Runtime Library

ShortPath Property
Returns the short path used by programs that require the earlier 8.3 file naming convention.
object.ShortPath

The object is always a File or Folder object.


Remarks
The following code illustrates the use of the ShortName property with a File object:
[JScript]
function ShowShortPath(filespec)
{
var fso, f, s;
fso = new ActiveXObject("Scripting.FileSystemObject");
f = fso.GetFile(filespec);
s = "The short path for " + "" + f.Name;
s += "" + "<br>";
s += "is: " + "" + f.ShortPath + "";
return(s);
}
[VBScript]
Function ShowShortName(filespec)
Dim fso, f, s
Set fso = CreateObject("Scripting.FileSystemObject")
Set f = fso.GetFile(filespec)
s = "The short name for "
& UCase(f.Name) & "<BR>"
s = s & "is: " & f.ShortName
ShowShortName = s
End Function

See Also
Attributes Property | DateCreated Property | DateLastAccessed Property | DateLastModified Property | Drive Property | Files Property | IsRootFolder Property | Name Property | ParentFolder Property | Path Property | ShortName
Property | Size Property | SubFolders Property | Type Property
Applies To: File Object | Folder Object

2001 Microsoft Corporation. All rights reserved.


Build: Topic Version 5.6.9309.1546
Scripting Runtime Library

Size Property
For files, returns the size, in bytes, of the specified file. For folders, returns the size, in bytes, of all files and subfolders contained in the folder.
object.Size

The object is always a File or Folder object.


Remarks
The following code illustrates the use of the Size property with a Folder object:
[JScript]
function ShowFolderSize(filespec)
{
var fso, f, s;
fso = new ActiveXObject("Scripting.FileSystemObject");
f = fso.GetFolder(filespec);
s = f.Name + " uses " + f.size + " bytes.";
return(s);
}
[VBScript]
Function ShowFolderSize(filespec)
Dim fso, f, s
Set fso = CreateObject("Scripting.FileSystemObject")
Set f = fso.GetFolder(filespec)
s = UCase(f.Name) & " uses " & f.size & " bytes."
ShowFolderSize = s
End Function

See Also
Attributes Property | DateCreated Property | DateLastAccessed Property | DateLastModified Property | Drive Property | Files Property | IsRootFolder Property | Name Property | ParentFolder Property | Path Property | ShortName
Property | ShortPath Property | SubFolders Property | Type Property

Applies To: File Object | Folder Object

2001 Microsoft Corporation. All rights reserved.


Build: Topic Version 5.6.9309.1546
Scripting Runtime Library

SubFolders Property
Returns a Folders collection consisting of all folders contained in a specified folder, including those with hidden and system file attributes set.
object.SubFolders

The object is always a Folder object.


Remarks
The following code illustrates the use of the SubFolders property:
[JScript]
function ShowFolderList(folderspec)
{
var fso, f, fc, s;
fso = new ActiveXObject("Scripting.FileSystemObject");
f = fso.GetFolder(folderspec);
fc = new Enumerator(f.SubFolders);
s = "";
for (;!fc.atEnd(); fc.moveNext())
{
s += fc.item();
s += "<br>";
}
return(s);
}
[VBScript]
Function ShowFolderList(folderspec)
Dim fso, f, f1, s, sf
Set fso = CreateObject("Scripting.FileSystemObject")
Set f = fso.GetFolder(folderspec)
Set sf = f.SubFolders
For Each f1 in sf
s = s & f1.name
s = s & "<BR>"
Next
ShowFolderList = s
End Function

See Also
Attributes Property | DateCreated Property | DateLastAccessed Property | DateLastModified Property | Drive Property | Files Property | IsRootFolder Property | Name Property | ParentFolder Property | Path Property | ShortName
Property | ShortPath Property | Size Property | Type Property
Applies To: Folder Object

2001 Microsoft Corporation. All rights reserved.


Build: Topic Version 5.6.9309.1546
Scripting Runtime Library

TotalSize Property
Returns the total space, in bytes, of a drive or network share.
object.TotalSize

The object is always a Drive object.


Remarks
The following code illustrates the use of the TotalSize property:
[JScript]
function SpaceReport(drvPath)
{
var fso, d, s;
fso = new ActiveXObject("Scripting.FileSystemObject");
d = fso.GetDrive(fso.GetDriveName(drvPath));
s = "Drive " + drvPath + " - ";
s += d.VolumeName + "<br>";
s += "Total Space: "+ d.TotalSize/1024 + " Kbytes <br>";
s += "Free Space:
" + d.FreeSpace/1024 + " Kbytes";
return(s);
}
[VBScript]
Function ShowSpaceInfo(drvpath)
Dim fso, d, s
Set fso = CreateObject("Scripting.FileSystemObject")
Set d = fso.GetDrive(fso.GetDriveName(fso.GetAbsolutePathName(drvpath)))
s = "Drive " & d.DriveLetter & ":"
s = s & vbCrLf
s = s & "Total Size: " & FormatNumber(d.TotalSize/1024, 0) & " Kbytes"
s = s & vbCrLf
s = s & "Available: " & FormatNumber(d.AvailableSpace/1024, 0) & " Kbytes"
ShowSpaceInfo = s
End Function

See Also
AvailableSpace Property | DriveLetter Property | DriveType Property | FileSystem Property | FreeSpace Property | IsReady Property | Path Property | RootFolder Property | SerialNumber Property | ShareName Property |
VolumeName Property
Applies To: Drive Object

2001 Microsoft Corporation. All rights reserved.

Build: Topic Version 5.6.9309.1546


Scripting Runtime Library

Type Property
Returns information about the type of a file or folder. For example, for files ending in .TXT, "Text Document" is returned.
object.Type

The object is always a File or Folder object.


Remarks
The following code illustrates the use of the Type property to return a folder type. In this example, try providing the path of the Recycle Bin or other unique folder to the procedure.
[JScript]
function ShowFileType(filespec)
{
var fso, f, s;
fso = new ActiveXObject("Scripting.FileSystemObject");
if (fso.FolderExists(filespec))
f = fso.GetFolder(filespec);
else if (fso.FileExists(filespec))
f = fso.GetFile(filespec);
else
s = "File or Folder does not exist.";
s = f.Name + " is a " + f.Type;
return(s);
}
[VBScript]
Function ShowFolderType(filespec)
Dim fso, f, s
Set fso = CreateObject("Scripting.FileSystemObject")
Set f = fso.GetFolder(filespec)
s = UCase(f.Name) & " is a " & f.Type
ShowFolderType = s
End Function

See Also
Attributes Property | DateCreated Property | DateLastAccessed Property | DateLastModified Property | Drive Property | Files Property | IsRootFolder Property | Name Property | ParentFolder Property | Path Property | ShortName
Property | ShortPath Property | Size Property | SubFolders Property
Applies To: File Object | Folder Object

2001 Microsoft Corporation. All rights reserved.


Build: Topic Version 5.6.9309.1546
Scripting Runtime Library

VolumeName Property
Sets or returns the volume name of the specified drive. Read/write.
object.VolumeName [= newname]

Arguments
object
Required. Always the name of a Drive object.
newname
Optional. If provided, newname is the new name of the specified object.
Remarks
The following code illustrates the use of the VolumeName property:
[JScript]
function SpaceReport(drvPath)
{
var fso, d, s;
fso = new ActiveXObject("Scripting.FileSystemObject");
d = fso.GetDrive(fso.GetDriveName(drvPath));
s = "Drive " + drvPath + " - ";
s += d.VolumeName + "<br>";
s += "Total Space: "+ d.TotalSize/1024 + " Kbytes <br>";
s += "Free Space:
" + d.FreeSpace/1024 + " Kbytes";
return(s);
}
[VBScript]
Function ShowVolumeInfo(drvpath)
Dim fso, d, s
Set fso = CreateObject("Scripting.FileSystemObject")
Set d = fso.GetDrive(fso.GetDriveName(fso.GetAbsolutePathName(drvpath)))
s = "Drive " & d.DriveLetter & ": - " & d.VolumeName
ShowVolumeInfo = s
End Function

See Also
AvailableSpace Property | DriveLetter Property | DriveType Property | FileSystem Property | FreeSpace Property | IsReady Property | Path Property | RootFolder Property | SerialNumber Property | ShareName Property |
TotalSize Property
Applies To: Drive Object

2001 Microsoft Corporation. All rights reserved.


Build: Topic Version 5.6.9309.1546
Scripting Runtime Library

FileSystemObject Methods
In This Section

Add Method (Dictionary)


Adds a key and item pair to a Dictionary object.
Add Method (Folders)
Adds a new folder to a Folders collection.
BuildPath Method
Appends a name to an existing path.
Close Method
Closes an open TextStream file.
Copy Method
Copies a specified file or folder from one location to another.
CopyFile Method
Copies one or more files from one location to another.
CopyFolder Method
Recursively copies a folder from one location to another.
CreateFolder Method
Creates a folder.
CreateTextFile Method
Creates a specified file name and returns a TextStream object that can be used to read from or write to the file.
Delete Method
Deletes a specified file or folder.
DeleteFile Method
Deletes a specified file.
DeleteFolder Method
Deletes a specified folder and its contents.
DrivesExists Method
Returns true if the specified drive exists; false if it does not.
Exists Method
Returns true if a specified key exists in the Dictionary object, false if it does not.
FileExists Method
Returns true if a specified file exists; false if it does not.
FolderExists Method
Returns true if a specified folder exists; false if it does not.
GetAbsolutePathName Method
Returns a complete and unambiguous path from a provided path specification.
GetBaseName Method
Returns a string containing the base name of the last component, less any file extension, in a path.
GetDrive Method
Returns a Drive object corresponding to the drive in a specified path.
GetDriveName Method
Returns a string containing the name of the drive for a specified path.
GetExtensionName Method
Returns a string containing the extension name for the last component in a path.
GetFile Method
Returns a File object corresponding to the file in a specified path.
GetFileName Method
Returns the last component of specified path that is not part of the drive specification.
GetFileVersion Method
Returns the version number of a specified file.
GetFolder Method
Returns a Folder object corresponding to the folder in a specified path.
GetParentFolderName Method
Returns a string containing the name of the parent folder of the last component in a specified path.
GetSpecialFolder Method
Returns the special folder object specified.
GetTempName Method
Returns a randomly generated temporary file or folder name that is useful for performing operations that require a temporary file or folder.
Items Method
Returns an array containing all the items in a Dictionary object.
Keys Method
Returns an array containing all existing keys in a Dictionary object.
Move Method
Moves a specified file or folder from one location to another.
MoveFile Method
Moves one or more files from one location to another.
MoveFolder Method
Moves one or more folders from one location to another.
OpenAsTextStream Method
Opens a specified file and returns a TextStream object that can be used to read from, write to, or append to the file.
OpenTextFile Method
Opens a specified file and returns a TextStream object that can be used to read from, write to, or append to the file.
Read Method
Reads a specified number of characters from a TextStream file and returns the resulting string.
ReadAll Method
Reads an entire TextStream file and returns the resulting string.
ReadLine Method
Reads an entire line (up to, but not including, the newline character) from a TextStream file and returns the resulting string.
Remove Method
Removes a key, item pair from a Dictionary object.
RemoveAll Method
Removes all key, item pairs from a Dictionary object.
Skip Method
Skips a specified number of characters when reading a TextStream file.
SkipLine
Skips the next line when reading a TextStream file.
Write Method
Writes a specified string to a TextStream file.
WriteBlankLines Method
Writes a specified number of newline characters to a TextStream file.
WriteLine Method
Writes a specified string and newline character to a TextStream file.
Related Sections
Scripting Run-Time Reference
List of elements that make up Scripting Run-Time Reference.
FileSystemObject Basics
A guide to the fundamentals of the FileSystemObject.

2001 Microsoft Corporation. All rights reserved.


Build: Topic Version 5.6.9309.1546
Scripting Runtime Library

Add Method (Folders)


Adds a new folder to a Folders collection.

object.Add (folderName)

Arguments
object
Required. Always the name of a Folders collection.
folderName
Required. The name of the new Folder being added.
Remarks
The following example illustrates the use of the Add method to create a new folder.
[JScript]
function AddNewFolder(path,folderName)
{
var fso, f, fc, nf;
fso = new ActiveXObject("Scripting.FileSystemObject");
f = fso.GetFolder(path);
fc = f.SubFolders;
if (folderName != "" )
nf = fc.Add(folderName);
else
nf = fc.Add("New Folder");
}
[VBScript]
Sub AddNewFolder(path, folderName)
Dim fso, f, fc, nf
Set fso = CreateObject("Scripting.FileSystemObject")
Set f = fso.GetFolder(path)
Set fc = f.SubFolders
If folderName <> "" Then
Set nf = fc.Add(folderName)
Else
Set nf = fc.Add("New Folder")
End If
End Sub

An error occurs if the folderName already exists.


See Also
Add Method (Dictionary)
Applies To: Folders Collection

2001 Microsoft Corporation. All rights reserved.


Build: Topic Version 5.6.9309.1546
Scripting Runtime Library

BuildPath Method
Appends a name to an existing path.
object.BuildPath(path, name)

Arguments
object
Required. Always the name of a FileSystemObject.
path
Required. Existing path to which name is appended. Path can be absolute or relative and need not specify an existing folder.
name
Required. Name being appended to the existing path.
Remarks
The BuildPath method inserts an additional path separator between the existing path and the name, only if necessary.
The following example illustrates use of the BuildPath method.
[JScript]
function GetBuildPath(path)
{
var fso, newpath;
fso = new ActiveXObject("Scripting.FileSystemObject");
newpath = fso.BuildPath(path, "New
Folder");
return(newpath);
}
[VBScript]
Function GetBuildPath(path)
Dim fso, newpath
Set fso = CreateObject("Scripting.FileSystemObject")
newpath = fso.BuildPath(path, "Sub Folder")
GetBuildPath = newpath
End Function

See Also
GetAbsolutePathName Method | GetBaseName Method | GetDriveName Method | GetExtensionName Method | GetFileName Method | GetParentFolderName Method | GetTempName Method
Applies To: FileSystemObject Object

2001 Microsoft Corporation. All rights reserved.


Build: Topic Version 5.6.9309.1546
Scripting Runtime Library

Close Method
Closes an open TextStream file.
object.Close( );

The object is always the name of a TextStream object.

Remarks
The following example illustrates use of the Close method.
[JScript]
var fso;
fso = new ActiveXObject("Scripting.FileSystemObject");
a = fso.CreateTextFile("c:\\testfile.txt", true);
a.WriteLine("This is a test.");
a.Close();
[VBScript]
Sub CreateAFile
Dim fso, MyFile
Set fso = CreateObject("Scripting.FileSystemObject")
Set MyFile = fso.CreateTextFile("c:\testfile.txt", True)
MyFile.WriteLine("This is a test.")
MyFile.Close
End Sub

2001 Microsoft Corporation. All rights reserved.


Build: Topic Version 5.6.9309.1546
Scripting Runtime Library

Copy Method
Copies a specified file or folder from one location to another.
object.Copy( destination[, overwrite] );

Arguments
object
Required. Always the name of a File or Folder object.
destination
Required. Destination where the file or folder is to be copied. Wildcard characters are not allowed.
overwrite
Optional. Boolean value that is True (default) if existing files or folders are to be overwritten; False if they are not.
Remarks
The results of the Copy method on a File or Folder are identical to operations performed using FileSystemObject.CopyFile or FileSystemObject.CopyFolder where the file or folder referred to by object is passed as an
argument. You should note, however, that the alternative methods are capable of copying multiple files or folders.
Example
The following example illustrates the use of the Copy method.
[JScript]
var fso, f;
fso = new ActiveXObject("Scripting.FileSystemObject");
f = fso.CreateTextFile("c:\\testfile.txt", true);
f.WriteLine("This is a test.");
f.Close();
f = fso.GetFile("c:\\testfile.txt");
f.Copy("c:\\windows\\desktop\\test2.txt");
[VBScript]
Dim fso, MyFile
Set fso = CreateObject("Scripting.FileSystemObject")
Set MyFile = fso.CreateTextFile("c:\testfile.txt", True)
MyFile.WriteLine("This is a test.")
MyFile.Close
Set MyFile = fso.GetFile("c:\testfile.txt")
MyFile.Copy ("c:\windows\desktop\test2.txt")

See Also
CopyFile Method | CopyFolder Method | Delete Method | Move Method | OpenAsTextStream Method
Applies To: File Object | Folder Object

2001 Microsoft Corporation. All rights reserved.


Build: Topic Version 5.6.9309.1546
Scripting Runtime Library

CopyFile Method
Copies one or more files from one location to another.
object.CopyFile ( source, destination[, overwrite] )

Arguments
object
Required. The object is always the name of a FileSystemObject.
source
Required. Character string file specification, which can include wildcard characters, for one or more files to be copied.
destination
Required. Character string destination where the file or files from source are to be copied. Wildcard characters are not allowed.
overwrite
Optional. Boolean value that indicates if existing files are to be overwritten. If true, files are overwritten; if false, they are not. The default is true. Note that CopyFile will fail if destination has the read-only attribute set,
regardless of the value of overwrite.
Remarks
Wildcard characters can only be used in the last path component of the source argument. For example, you can use:
[JScript]
fso = new ActiveXObject("Scripting.FileSystemObject");
fso.CopyFile ("c:\\mydocuments\\letters\\*.doc", "c:\\tempfolder\\")
[VBScript]
FileSystemObject.CopyFile "c:\mydocuments\letters\*.doc", "c:\tempfolder\"

But you cannot use:

[JScript]
fso = new ActiveXObject("Scripting.FileSystemObject");
fso.CopyFile ("c:\\mydocuments\\*\\R1???97.xls", "c:\\tempfolder")
[VBScript]
FileSystemObject.CopyFile "c:\mydocuments\*\R1???97.xls", "c:\tempfolder"

If source contains wildcard characters or destination ends with a path separator (\), it is assumed that destination is an existing folder in which to copy matching files. Otherwise, destination is assumed to be the name of a file to
create. In either case, three things can happen when an individual file is copied.

If destination does not exist, source gets copied. This is the usual case.
If destination is an existing file, an error occurs if overwrite is false. Otherwise, an attempt is made to copy source over the existing file.
If destination is a directory, an error occurs.

An error also occurs if a source using wildcard characters doesn't match any files. The CopyFile method stops on the first error it encounters. No attempt is made to roll back or undo any changes made before an error occurs.
See Also
Copy Method | CopyFolder Method | CreateTextFile Method | DeleteFile Method | MoveFile Method
Applies To: FileSystemObject Object

2001 Microsoft Corporation. All rights reserved.


Build: Topic Version 5.6.9309.1546
Scripting Runtime Library

CopyFolder Method
Recursively copies a folder from one location to another.
object.CopyFolder ( source, destination[, overwrite] );

Arguments
object
Required. Always the name of a FileSystemObject.
source
Required. Character string folder specification, which can include wildcard characters, for one or more folders to be copied.
destination
Required. Character string destination where the folder and subfolders from source are to be copied. Wildcard characters are not allowed.
overwrite
Optional. Boolean value that indicates if existing folders are to be overwritten. If true, files are overwritten; if false, they are not. The default is true.
Remarks
Wildcard characters can only be used in the last path component of the source argument. For example, you can use:
[JScript]
fso = new ActiveXObject("Scripting.FileSystemObject");
fso.CopyFolder ("c:\\mydocuments\\letters\\*", "c:\\tempfolder\\")
[VBScript]
FileSystemObject.CopyFolder "c:\mydocuments\letters\*", "c:\tempfolder\"

But you cannot use:


[JScript]
fso = new ActiveXObject("Scripting.FileSystemObject");
fso.CopyFolder ("c:\\mydocuments\\*\\*", "c:\\tempfolder\\")
[VBScript]
FileSystemObject.CopyFolder "c:\mydocuments\*\*", "c:\tempfolder\"

If source contains wildcard characters or destination ends with a path separator (\), it is assumed that destination is an existing folder in which to copy matching folders and subfolders. Otherwise, destination is assumed to be the
name of a folder to create. In either case, four things can happen when an individual folder is copied.

If destination does not exist, the source folder and all its contents gets copied. This is the usual case.
If destination is an existing file, an error occurs.
If destination is a directory, an attempt is made to copy the folder and all its contents. If a file contained in source already exists in destination, an error occurs if overwrite is false. Otherwise, it will attempt to copy the file
over the existing file.
If destination is a read-only directory, an error occurs if an attempt is made to copy an existing read-only file into that directory and overwrite is false.

An error also occurs if a source using wildcard characters doesn't match any folders.
The CopyFolder method stops on the first error it encounters. No attempt is made to roll back any changes made before an error occurs.
See Also
CopyFile Method | Copy Method | CreateFolder Method | DeleteFolder Method | MoveFolder Method
Applies To: FileSystemObject Object

2001 Microsoft Corporation. All rights reserved.


Build: Topic Version 5.6.9309.1546
Scripting Runtime Library

CreateFolder Method
Creates a folder.
object.CreateFolder(foldername)

Arguments
object
Required. Always the name of a FileSystemObject.
foldername
Required. String expression that identifies the folder to create.
Remarks
An error occurs if the specified folder already exists.
The following code illustrates how to use the CreateFolder method to create a folder.

[JScript]
var fso = new ActiveXObject("Scripting.FileSystemObject");
var a = fso.CreateFolder("c:\\new folder");
[VBScript]
Function CreateFolderDemo
Dim fso, f
Set fso = CreateObject("Scripting.FileSystemObject")
Set f = fso.CreateFolder("c:\New Folder")
CreateFolderDemo = f.Path
End Function

See Also
CopyFolder Method | DeleteFolder Method | MoveFolder Method
Applies To: FileSystemObject Object

2001 Microsoft Corporation. All rights reserved.


Build: Topic Version 5.6.9309.1546
Scripting Runtime Library

CreateTextFile Method
Creates a specified file name and returns a TextStream object that can be used to read from or write to the file.
object.CreateTextFile(filename[, overwrite[, unicode]])

Arguments
object
Required. Always the name of a FileSystemObject or Folder object.
filename
Required. String expression that identifies the file to create.
overwrite
Optional. Boolean value that indicates whether you can overwrite an existing file. The value is true if the file can be overwritten, false if it can't be overwritten. If omitted, existing files are not overwritten.
unicode
Optional. Boolean value that indicates whether the file is created as a Unicode or ASCII file. The value is true if the file is created as a Unicode file, false if it's created as an ASCII file. If omitted, an ASCII file is
assumed.
Remarks
The following code illustrates how to use the CreateTextFile method to create and open a text file.
[JScript]
var fso = new ActiveXObject("Scripting.FileSystemObject");
var a = fso.CreateTextFile("c:\\testfile.txt", true);
a.WriteLine("This is a test.");
a.Close();
[VBScript]
Sub CreateAfile
Dim fso, MyFile
Set fso = CreateObject("Scripting.FileSystemObject")
Set MyFile = fso.CreateTextFile("c:\testfile.txt", True)
MyFile.WriteLine("This is a test.")
MyFile.Close
End Sub

If the overwrite argument is false, or is not provided, for a filename that already exists, an error occurs.
See Also
CreateFolder Method | OpenAsTextStream Method | OpenTextFile Method
Applies To: FileSystemObject Object | Folder Object

2001 Microsoft Corporation. All rights reserved.


Build: Topic Version 5.6.9309.1546
Scripting Runtime Library

DateCreated Property
Returns the date and time that the specified file or folder was created. Read-only.
object.DateCreated

The object is always a File or Folder object.


Remarks
The following code illustrates the use of the DateCreated property with a file:
[JScript]
function ShowFileInfo(filespec)
{
var fso, f, s;
fso = new ActiveXObject("Scripting.FileSystemObject");
f = fso.GetFile(filespec);
s = "Created: " + f.DateCreated;
return(s);
}
[VBScript]
Function ShowFileInfo(filespec)
Dim fso, f
Set fso = CreateObject("Scripting.FileSystemObject")
Set f = fso.GetFile(filespec)
ShowFileInfo = "Created: " & f.DateCreated
End Function

See Also
Attributes Property | DateLastAccessed Property | DateLastModified Property | Drive Property | Files Property | IsRootFolder Property | Name Property | ParentFolder Property | Path Property | ShortName Property | ShortPath
Property | Size Property | SubFolders Property | Type Property
Applies To: File Object | Folder Object

2001 Microsoft Corporation. All rights reserved.


Build: Topic Version 5.6.9309.1546
Scripting Runtime Library

Delete Method
Deletes a specified file or folder.
object.Delete( force );

Arguments
object
Required. Always the name of a File or Folder object.
force
Optional. Boolean value that is True if files or folders with the read-only attribute set are to be deleted; False (default) if they are not.
Remarks
An error occurs if the specified file or folder does not exist.
The results of the Delete method on a File or Folder are identical to operations performed using FileSystemObject.DeleteFile or FileSystemObject.DeleteFolder.
The Delete method does not distinguish between folders that have contents and those that do not. The specified folder is deleted regardless of whether or not it has contents.
The following example illustrates the use of the Delete method.
[JScript]
var fso, f;
fso = new ActiveXObject("Scripting.FileSystemObject");
f = fso.CreateTextFile("c:\\testfile.txt", true);
f.WriteLine("This is a test.");
f.Close();
f = fso.GetFile("c:\\testfile.txt");
f.Delete();
[VBScript]
Dim fso, MyFile
Set fso = CreateObject("Scripting.FileSystemObject")
Set MyFile = fso.CreateTextFile("c:\testfile.txt", True)
MyFile.WriteLine("This is a test.")
MyFile.Close
Set MyFile = fso.GetFile("c:\testfile.txt")
MyFile.Delete

See Also
Copy Method | DeleteFile Method | DeleteFolder Method | Move Method | OpenAsTextStream Method
Applies To: File Object | Folder Object

2001 Microsoft Corporation. All rights reserved.


Build: Topic Version 5.6.9309.1546
Scripting Runtime Library

DeleteFile Method
Deletes a specified file.
object.DeleteFile ( filespec[, force] );

Arguments
object
Required. Always the name of a FileSystemObject.
filespec
Required. The name of the file to delete. The filespec can contain wildcard characters in the last path component.
force
Optional. Boolean value that is true if files with the read-only attribute set are to be deleted; false (default) if they are not.
Remarks
An error occurs if no matching files are found. The DeleteFile method stops on the first error it encounters. No attempt is made to roll back or undo any changes that were made before an error occurred.
The following example illustrates the use of the DeleteFile method.
[JScript]
function DeleteFile(filespec)
{
var fso;
fso = new ActiveXObject("Scripting.FileSystemObject");
fso.DeleteFile(filespec);
}
[VBScript]
Sub DeleteAFile(filespec)
Dim fso
Set fso = CreateObject("Scripting.FileSystemObject")
fso.DeleteFile(filespec)
End Sub

See Also
CopyFile Method | CreateTextFile Method | Delete Method | DeleteFolder Method | MoveFile Method
Applies To: FileSystemObject Object

2001 Microsoft Corporation. All rights reserved.


Build: Topic Version 5.6.9309.1546
Scripting Runtime Library

DeleteFolder Method
Deletes a specified folder and its contents.
object.DeleteFolder ( folderspec[, force] );

Arguments
object
Required. Always the name of a FileSystemObject.
folderspec
Required. The name of the folder to delete. The folderspec can contain wildcard characters in the last path component.
force
Optional. Boolean value that is true if folders with the read-only attribute set are to be deleted; false (default) if they are not.
Remarks
The DeleteFolder method does not distinguish between folders that have contents and those that do not. The specified folder is deleted regardless of whether or not it has contents.
An error occurs if no matching folders are found. The DeleteFolder method stops on the first error it encounters. No attempt is made to roll back or undo any changes that were made before an error occurred.
The following example illustrates the use of the DeleteFolder method.
[JScript]
function DeleteFolder(folderspec)
{
var fso;
fso = new ActiveXObject("Scripting.FileSystemObject");
fso.DeleteFolder(folderspec);
}
[VBScript]
Sub DeleteAFolder(filespec)
Dim fso
Set fso = CreateObject("Scripting.FileSystemObject")
fso.DeleteFolder(filespec)
End Sub

See Also
CopyFolder Method | CreateFolder Method | Delete Method | DeleteFile Method | MoveFolder Method
Applies To: FileSystemObject Object

2001 Microsoft Corporation. All rights reserved.


Build: Topic Version 5.6.9309.1546
Scripting Runtime Library

DriveExists Method
Returns True if the specified drive exists; False if it does not.
object.DriveExists(drivespec)

Arguments
object
Required. Always the name of a FileSystemObject.
drivespec
Required. A drive letter or a complete path specification.
Remarks
For drives with removable media, the DriveExists method returns true even if there are no media present. Use the IsReady property of the Drive object to determine if a drive is ready.
The following example illustrates the use of the DriveExists method.
[JScript]
function ReportDriveStatus(drv)
{
var fso, s = "";
fso = new ActiveXObject("Scripting.FileSystemObject");
if (fso.DriveExists(drv))
s += "Drive " + drv + " exists.";
else
s += "Drive " + drv + " doesn't exist.";
return(s);
}
[VBScript]
Function ReportDriveStatus(drv)
Dim fso, msg
Set fso = CreateObject("Scripting.FileSystemObject")
If fso.DriveExists(drv) Then
msg = ("Drive " & UCase(drv) & " exists.")
Else
msg = ("Drive " & UCase(drv) & " doesn't exist.")
End If
ReportDriveStatus = msg
End Function

See Also
Drive Object | Drives Collection | FileExists Method | FolderExists Method | GetDrive Method | GetDriveName Method | IsReady Property
Applies To: FileSystemObject Object

2001 Microsoft Corporation. All rights reserved.


Build: Topic Version 5.6.9309.1546
Scripting Runtime Library

FileExists Method
Returns True if a specified file exists; False if it does not.
object.FileExists(filespec)

Arguments
object
Required. Always the name of a FileSystemObject.
filespec
Required. The name of the file whose existence is to be determined. A complete path specification (either absolute or relative) must be provided if the file isn't expected to exist in the current folder.
The following example illustrates the use of the FileExists method.
[JScript]
function ReportFileStatus(filespec)
{
var fso, s = filespec;
fso = new ActiveXObject("Scripting.FileSystemObject");
if (fso.FileExists(filespec))
s += " exists.";
else
s += " doesn't exist.";
return(s);
}
[VBScript]
Function ReportFileStatus(filespec)
Dim fso, msg
Set fso = CreateObject("Scripting.FileSystemObject")
If (fso.FileExists(filespec)) Then
msg = filespec & " exists."
Else
msg = filespec & " doesn't exist."
End If
ReportFileStatus = msg
End Function

See Also
DriveExists Method | FolderExists Method | GetFile Method | GetFileName Method
Applies To: FileSystemObject Object

2001 Microsoft Corporation. All rights reserved.


Build: Topic Version 5.6.9309.1546
Scripting Runtime Library

Files Property
Returns a Files collection consisting of all File objects contained in the specified folder, including those with hidden and system file attributes set.
object.Files

The object is always a Folder object.


Remarks
The following code illustrates the use of the Files property:
[JScript]
function ShowFolderFileList(folderspec)
{
var fso, f, fc, s;
fso = new ActiveXObject("Scripting.FileSystemObject");
f = fso.GetFolder(folderspec);
fc = new Enumerator(f.files);
s = "";
for (; !fc.atEnd(); fc.moveNext())
{
s += fc.item();
s += "<br>";
}
return(s);
}
[VBScript]Function ShowFileList(folderspec)
Dim fso, f, f1, fc, s
Set fso = CreateObject("Scripting.FileSystemObject")
Set f = fso.GetFolder(folderspec)
Set fc = f.Files
For Each f1 in fc
s = s & f1.name
s = s &
"<BR>"
Next
ShowFileList = s
End Function

See Also
Attributes Property | DateCreated Property | DateLastAccessed Property | DateLastModified Property | Drive Property | IsRootFolder Property | Name Property | ParentFolder Property | Path Property | ShortName Property |
ShortPath Property | Size Property | SubFolders Property | Type Property
Applies To: Folder Object

2001 Microsoft Corporation. All rights reserved.


Build: Topic Version 5.6.9309.1546
Scripting Runtime Library

FolderExists Method
Returns True if a specified folder exists; False if it does not.
object.FolderExists(folderspec)

Arguments
object
Required. Always the name of a FileSystemObject.
folderspec
Required. The name of the folder whose existence is to be determined. A complete path specification (either absolute or relative) must be provided if the folder isn't expected to exist in the current folder.
The following example illustrates the use of the FileExists method.

[JScript]
function ReportFolderStatus(fldr)
{
var fso, s = fldr;
fso = new ActiveXObject("Scripting.FileSystemObject");
if (fso.FolderExists(fldr))
s += " exists.";
else
s += " doesn't exist.";
return(s);
}
[VBScript]
Function ReportFolderStatus(fldr)
Dim fso, msg
Set fso = CreateObject("Scripting.FileSystemObject")
If (fso.FolderExists(fldr)) Then
msg = fldr & " exists."
Else
msg = fldr & " doesn't exist."
End If
ReportFolderStatus = msg
End Function

See Also
DriveExists Method | FileExists Method | GetFolder Method | GetParentFolderName Method
Applies To: FileSystemObject Object

2001 Microsoft Corporation. All rights reserved.


Build: Topic Version 5.6.9309.1546
Scripting Runtime Library

GetAbsolutePathName Method
Returns a complete and unambiguous path from a provided path specification.
object.GetAbsolutePathName(pathspec)

Arguments
object
Required. Always the name of a FileSystemObject.
pathspec
Required. Path specification to change to a complete and unambiguous path.
Remarks
A path is complete and unambiguous if it provides a complete reference from the root of the specified drive. A complete path can only end with a path separator character (\) if it specifies the root folder of a mapped drive.
Assuming the current directory is c:\mydocuments\reports, the following table illustrates the behavior of the GetAbsolutePathName method.
pathspec
"c:"
"c:.."
"c:\\"
"c:*.*\\may97"
"region1"
"c:\\..\\..\\mydocuments"

Returned path
"c:\mydocuments\reports"
"c:\mydocuments"
"c:\"
"c:\mydocuments\reports\*.*\may97"
"c:\mydocuments\reports\region1"
"c:\mydocuments"

The following example illustrates the use of the GetAbsolutePathName method.


function ShowAbsolutePath(path)
{
var fso, s= "";
fso = new ActiveXObject("Scripting.FileSystemObject");
s += fso.GetAbsolutePathName(path);
return(s);
}

See Also
GetBaseName Method | GetDrive Method | GetDriveName Method | GetExtensionName Method | GetFile Method | GetFileName Method | GetFileVersion Method | GetFolder Method | GetParentFolderName Method |
GetSpecialFolder Method | GetTempName Method
Applies To: FileSystemObject Object

2001 Microsoft Corporation. All rights reserved.


Build: Topic Version 5.6.9309.1546
Scripting Runtime Library

GetBaseName Method
Returns a string containing the base name of the last component, less any file extension, in a path.
object.GetBaseName(path)

Arguments
object
Required. Always the name of a FileSystemObject.
path
Required. The path specification for the component whose base name is to be returned.
Remarks
The GetBaseName method returns a zero-length string ("") if no component matches the path argument.
Note The GetBaseName method works only on the provided path string. It does not attempt to resolve the path, nor does it check for the existence of the specified path.
The following example illustrates the use of the GetBaseName method.
[JScript]

function ShowBaseName(filespec)
{
var fso, s = "";
fso = new ActiveXObject("Scripting.FileSystemObject");
s += fso.GetBaseName(filespec);
return(s);
}
[VBScript]
Function GetTheBase(filespec)
Dim fso
Set fso = CreateObject("Scripting.FileSystemObject")
GetTheBase = fso.GetBaseName(filespec)
End Function

See Also
GetAbsolutePathName Method | GetDrive Method | GetDriveName Method | GetExtensionName Method | GetFile Method | GetFileName Method | GetFileVersion Method | GetFolder Method | GetParentFolderName Method |
GetSpecialFolder Method | GetTempName Method
Applies To: FileSystemObject Object

2001 Microsoft Corporation. All rights reserved.


Build: Topic Version 5.6.9309.1546
Scripting Runtime Library

GetDrive Method
Returns a Drive object corresponding to the drive in a specified path.
object.GetDrive ( drivespec );

Arguments
object
Required. Always the name of a FileSystemObject.
drivespec
Required. The drivespec argument can be a drive letter (c), a drive letter with a colon appended (c:), a drive letter with a colon and path separator appended (c:\), or any network share specification (\\computer2\share1).
Remarks
For network shares, a check is made to ensure that the share exists.
An error occurs if drivespec does not conform to one of the accepted forms or does not exist.
To call the GetDrive method on a normal path string, use the following sequence to get a string that is suitable for use as drivespec:
[JScript]
DriveSpec = GetDriveName(GetAbsolutePathName(Path))

[JScript]
The following example illustrates the use of the GetDrive method.
[JScript]
function ShowFreeSpace(drvPath)
{
var fso, d, s ="";
fso = new ActiveXObject("Scripting.FileSystemObject");
d = fso.GetDrive(fso.GetDriveName(drvPath));
s = "Drive " + drvPath.toUpperCase( ) + " - ";
s += d.VolumeName + "<br>";
s += "Free Space: " + d.FreeSpace/1024 + " Kbytes";
return(s);
}
[VBScript]
DriveSpec = GetDriveName(GetAbsolutePathName(Path))

[VBScript]
The following example illustrates use of the GetDrive method:
[VBScript]
Function ShowFreeSpace(drvPath)
Dim fso, d, s
Set fso = CreateObject("Scripting.FileSystemObject")
Set d = fso.GetDrive(fso.GetDriveName(drvPath))
s = "Drive " & UCase(drvPath) & " - "
s = s & d.VolumeName
& "<BR>"
s = s & "Free Space: " & FormatNumber(d.FreeSpace/1024, 0)
s = s & " Kbytes"
ShowFreeSpace = s
End Function

See Also
GetAbsolutePathName Method | GetBaseName Method | GetDriveName Method | GetExtensionName Method | GetFile Method | GetFileName Method | GetFileVersion Method | GetFolder Method | GetParentFolderName
Method | GetSpecialFolder Method | GetTempName Method
Applies To: FileSystemObject Object

2001 Microsoft Corporation. All rights reserved.


Build: Topic Version 5.6.9309.1546
Scripting Runtime Library

GetDriveName Method
Returns a string containing the name of the drive for a specified path.
object.GetDriveName(path)

Arguments
object
Required. Always the name of a FileSystemObject.
path

Required. The path specification for the component whose drive name is to be returned.
Remarks
The GetDriveName method returns a zero-length string ("") if the drive can't be determined.
Note The GetDriveName method works only on the provided path string. It does not attempt to resolve the path, nor does it check for the existence of the specified path.
The following example illustrates the use of the GetDriveName method.
[JScript]
function GetDriveLetter(path)
{
var fso, s ="";
fso = new ActiveXObject("Scripting.FileSystemObject");
s += fso.GetDrive(fso.GetDriveName(fso.GetAbsolutePathName(path)));
return(s);
}
[VBScript]
Function GetAName(DriveSpec)
Dim fso
Set fso = CreateObject("Scripting.FileSystemObject")
GetAName = fso.GetDriveName(Drivespec)
End Function

See Also
GetAbsolutePathName Method | GetBaseName Method | GetDrive Method | GetExtensionName Method | GetFile Method | GetFileName Method | GetFileVersion Method | GetFolder Method | GetParentFolderName Method |
GetSpecialFolder Method | GetTempName Method
Applies To: FileSystemObject Object

2001 Microsoft Corporation. All rights reserved.


Build: Topic Version 5.6.9309.1546
Scripting Runtime Library

GetExtensionName Method
Returns a string containing the extension name for the last component in a path.
object.GetExtensionName(path)

Arguments
object
Required. Always the name of a FileSystemObject.
path
Required. The path specification for the component whose extension name is to be returned.
Remarks
For network drives, the root directory (\) is considered to be a component.
The GetExtensionName method returns a zero-length string ("") if no component matches the path argument.
The following example illustrates the use of the GetExtensionName method.
[JScript]
function ShowExtensionName(filespec)
{
var fso, s = "";
fso = new ActiveXObject("Scripting.FileSystemObject");
s += fso.GetExtensionName(filespec);
return(s);
}
[VBScript]
Function GetAnExtension(DriveSpec)
Dim fso
Set fso = CreateObject("Scripting.FileSystemObject")
GetAnExtension = fso.GetExtensionName(Drivespec)
End Function

See Also
GetAbsolutePathName Method | GetBaseName Method | GetDrive Method | GetDriveName Method | GetFile Method | GetFileName Method | GetFileVersion Method | GetFolder Method | GetParentFolderName Method |
GetSpecialFolder Method | GetTempName Method
Applies To: FileSystemObject Object

2001 Microsoft Corporation. All rights reserved.


Build: Topic Version 5.6.9309.1546
Scripting Runtime Library

GetFile Method
Returns a File object corresponding to the file in a specified path.
object.GetFile(filespec)

Arguments
object
Required. Always the name of a FileSystemObject.
filespec
Required. The filespec is the path (absolute or relative) to a specific file.
Remarks
An error occurs if the specified file does not exist.
The following example illustrates the use of the GetFile method.
[JScript]

function ShowFileAccessInfo(filespec)
{
var fso, f, s;
fso = new ActiveXObject("Scripting.FileSystemObject");
f = fso.GetFile(filespec);
s = f.Path.toUpperCase() + "<br>";
s += "Created: " + f.DateCreated + "<br>";
s += "Last Accessed: " + f.DateLastAccessed + "<br>";
s += "Last Modified: " + f.DateLastModified
return(s);
}
[VBScript]
Function ShowFileAccessInfo(filespec)
Dim fso, f, s
Set fso = CreateObject("Scripting.FileSystemObject")
Set f = fso.GetFile(filespec)
s = f.Path & "<br>"
s = s & "Created: " & f.DateCreated & "<br>"
s = s & "Last Accessed: " & f.DateLastAccessed & "<br>"
s = s & "Last Modified: " & f.DateLastModified
ShowFileAccessInfo = s
End Function

See Also
GetAbsolutePathName Method | GetBaseName Method | GetDrive Method | GetDriveName Method | GetExtensionName Method | GetFileName Method | GetFileVersion Method | GetFolder Method | GetParentFolderName
Method | GetSpecialFolder Method | GetTempName Method
Applies To: FileSystemObject Object

2001 Microsoft Corporation. All rights reserved.


Build: Topic Version 5.6.9309.1546
Scripting Runtime Library

GetFileName Method
Returns the last component of specified path that is not part of the drive specification.
object.GetFileName(pathspec)

Arguments
object
Required. Always the name of a FileSystemObject.
pathspec
Required. The path (absolute or relative) to a specific file.
Remarks
The GetFileName method returns a zero-length string ("") if pathspec does not end with the named component.
Note The GetFileName method works only on the provided path string. It does not attempt to resolve the path, nor does it check for the existence of the specified path.
The following example illustrates the use of the GetFileName method.
[JScript]
function ShowFileName(filespec)
{
var fso, s = "";
fso = new ActiveXObject("Scripting.FileSystemObject");
s += fso.GetFileName(filespec);
return(s);
}
[VBScript]
Function GetAName(DriveSpec)
Dim fso
Set fso = CreateObject("Scripting.FileSystemObject")
GetAName = fso.GetFileName(DriveSpec)
End Function

See Also
GetAbsolutePathName Method | GetBaseName Method | GetDrive Method | GetDriveName Method | GetExtensionName Method | GetFile Method | GetFileVersion Method | GetFolder Method | GetParentFolderName Method |
GetSpecialFolder Method | GetTempName Method
Applies To: FileSystemObject Object

2001 Microsoft Corporation. All rights reserved.


Build: Topic Version 5.6.9309.1546
Scripting Runtime Library

GetFileVersion Method
Returns the version number of a specified file.
object.GetFileVersion(pathspec)

Arguments
object
Required. Always the name of a FileSystemObject.
pathspec
Required. The path (absolute or relative) to a specific file.
Remarks
The GetFileVersion method returns a zero-length string ("") if pathspec does not end with the named component.
Note The GetFileVersion method works only on the provided path string. It does not attempt to resolve the path, nor does it check for the existence of the specified path.
The following example illustrates the use of the GetFileVersion method.
[JScript]
function ShowFileName(filespec){
var fso, s = "";

fso = new ActiveXObject("Scripting.FileSystemObject");


s += fso.GetFileVersion(filespec);
return(s);
}
[VBScript]
Function GetVersion(DriveSpec)
Dim fso, temp
Set fso = CreateObject("Scripting.FileSystemObject")
temp = fso.GetFileVersion(pathspec)
If Len(temp) Then
GetVersion = temp
Else
GetVersion = "No version information available."
End If
End Function

See Also
GetAbsolutePathName Method | GetBaseName Method | GetDrive Method | GetDriveName Method | GetExtensionName Method | GetFile Method | GetFileName Method | GetFolder Method | GetParentFolderName Method |
GetSpecialFolder Method | GetTempName Method
Applies To: FileSystemObject Object

2001 Microsoft Corporation. All rights reserved.


Build: Topic Version 5.6.9309.1546
Scripting Runtime Library

GetFolder Method
Returns a Folder object corresponding to the folder in a specified path.
object.GetFolder(folderspec)

Arguments
object
Required. Always the name of a FileSystemObject.
folderspec
Required. The folderspec is the path (absolute or relative) to a specific folder.
Remarks
An error occurs if the specified folder does not exist.
The following example illustrates the use of the GetFolder method.
[JScript]
function ShowFolderList(folderspec)
{
var fso, f, fc, s;
fso = new ActiveXObject("Scripting.FileSystemObject");
f = fso.GetFolder(folderspec);
fc = new Enumerator(f.SubFolders);
s = "";
for (; !fc.atEnd(); fc.moveNext())
{
s += fc.item();
s += "<br>";
}
return(s);
}
[VBScript]
Sub AddNewFolder(path, folderName)
Dim fso, f, fc, nf
Set fso = CreateObject("Scripting.FileSystemObject")
Set f = fso.GetFolder(path)
Set fc = f.SubFolders
If folderName <> "" Then
Set nf = fc.Add(folderName)
Else
Set nf = fc.Add("New Folder")
End If
End Sub

See Also
GetAbsolutePathName Method | GetBaseName Method | GetDrive Method | GetDriveName Method | GetExtensionName Method | GetFile Method | GetFileName Method | GetFileVersion Method | GetParentFolderName
Method | GetSpecialFolder Method | GetTempName Method
Applies To: FileSystemObject Object

2001 Microsoft Corporation. All rights reserved.


Build: Topic Version 5.6.9309.1546
Scripting Runtime Library

GetParentFolderName Method
Returns a string containing the name of the parent folder of the last component in a specified path.
object.GetParentFolderName(path)

Arguments
object
Required. Always the name of a FileSystemObject.
path
Required. The path specification for the component whose parent folder name is to be returned.
Remarks
The GetParentFolderName method returns a zero-length string ("") if there is no parent folder for the component specified in the path argument.
Note The GetParentFolderName method works only on the provided path string. It does not attempt to resolve the path, nor does it check for the existence of the specified path.
The following example illustrates the use of the GetParentFolderName method.

[JScript]
function ShowParentFolderName(filespec)
{
var fso, s = "";
fso = new ActiveXObject("Scripting.FileSystemObject");
s += fso.GetParentFolderName(filespec);
return(s);
}
[VBScript]
Function GetTheParent(DriveSpec)
Dim fso
Set fso = CreateObject("Scripting.FileSystemObject")
GetTheParent = fso.GetParentFolderName(Drivespec)
End Function

See Also
GetAbsolutePathName Method | GetBaseName Method | GetDrive Method | GetDriveName Method | GetExtensionName Method | GetFile Method | GetFileName Method | GetFileVersion Method | GetFolder Method |
GetSpecialFolder Method | GetTempName Method
Applies To: FileSystemObject Object

2001 Microsoft Corporation. All rights reserved.


Build: Topic Version 5.6.9309.1546
Scripting Runtime Library

GetSpecialFolder Method
Returns the special folder object specified.
object.GetSpecialFolder(folderspec)

Arguments
object
Required. Always the name of a FileSystemObject.
folderspec
Required. The name of the special folder to be returned. Can be any of the constants shown in the Settings section.
Settings
The folderspec argument can have any of the following values:
Constant
WindowsFolder
SystemFolder
TemporaryFolder

Value
0
1
2

Description
The Windows folder contains files installed by the Windows operating system.
The System folder contains libraries, fonts, and device drivers.
The Temp folder is used to store temporary files. Its path is found in the TMP environment variable.

The following example illustrates the use of the GetSpecialFolder method.


[JScript]
var fso, tempfile;
fso = new ActiveXObject("Scripting.FileSystemObject");
function CreateTempFile()
{
var tfolder, tfile, tname, fname, TemporaryFolder = 2;
tfolder = fso.GetSpecialFolder(TemporaryFolder);
tname = fso.GetTempName();
tfile = tfolder.CreateTextFile(tname);
return(tfile);
}
tempfile = CreateTempFile();
tempfile.writeline("Hello World");
tempfile.close();
[VBScript]
Dim fso, tempfile
Set fso = CreateObject("Scripting.FileSystemObject")
Function CreateTempFile
Dim tfolder, tname, tfile
Const TemporaryFolder = 2
Set tfolder = fso.GetSpecialFolder(TemporaryFolder)
tname = fso.GetTempName
Set tfile = tfolder.CreateTextFile(tname)
Set CreateTempFile = tfile
End Function
Set tempfile = CreateTempFile
tempfile.WriteLine "Hello World"
tempfile.Close

See Also
GetAbsolutePathName Method | GetBaseName Method | GetDrive Method | GetDriveName Method | GetExtensionName Method | GetFile Method | GetFileName Method | GetFileVersion Method | GetFolder Method |
GetParentFolderName Method | GetTempName Method
Applies To: FileSystemObject Object

2001 Microsoft Corporation. All rights reserved.


Build: Topic Version 5.6.9309.1546
Scripting Runtime Library

GetTempName Method
Returns a randomly generated temporary file or folder name that is useful for performing operations that require a temporary file or folder.
object.GetTempName ( );

The optional object is always the name of a FileSystemObject.


Remarks
The GetTempName method does not create a file. It provides only a temporary file name that can be used with CreateTextFile to create a file.
The following example illustrates the use of the GetTempName method.

[JScript]
var fso, tempfile;
fso = new ActiveXObject("Scripting.FileSystemObject");
function CreateTempFile()
{
var tfolder, tfile, tname, fname, TemporaryFolder = 2;
tfolder = fso.GetSpecialFolder(TemporaryFolder);
tname = fso.GetTempName();
tfile = tfolder.CreateTextFile(tname);
return(tfile);
}
tempfile = CreateTempFile();
tempfile.writeline("Hello World");
tempfile.close();
[VBScript]
Dim fso, tempfile
Set fso = CreateObject("Scripting.FileSystemObject")
Function CreateTempFile
Dim tfolder, tname, tfile
Const TemporaryFolder = 2
Set tfolder = fso.GetSpecialFolder(TemporaryFolder)
tname = fso.GetTempName
Set tfile = tfolder.CreateTextFile(tname)
Set CreateTempFile = tfile
End Function
Set tempfile = CreateTempFile
tempfile.WriteLine "Hello World"
tempfile.Close

See Also
GetAbsolutePathName Method | GetBaseName Method | GetDrive Method | GetDriveName Method | GetExtensionName Method | GetFile Method | GetFileName Method | GetFileVersion Method | GetFolder Method |
GetParentFolderName Method | GetSpecialFolder Method
Applies To: FileSystemObject Object

2001 Microsoft Corporation. All rights reserved.


Build: Topic Version 5.6.9309.1546
Scripting Runtime Library

Move Method
Moves a specified file or folder from one location to another.
object.Move( destination );

Arguments
object
Required. Always the name of a File or Folder object.
destination
Required. Destination where the file or folder is to be moved. Wildcard characters are not allowed.
Remarks
The results of the Move method on a File or Folder are identical to operations performed using FileSystemObject.MoveFile or FileSystemObject.MoveFolder. You should note, however, that the alternative methods are
capable of moving multiple files or folders.
See Also
Copy Method | Delete Method | MoveFile Method | MoveFolder Method | OpenAsTextStream Method
Applies To: File Object | Folder Object

2001 Microsoft Corporation. All rights reserved.


Build: Topic Version 5.6.9309.1546
Scripting Runtime Library

MoveFile Method
Moves one or more files from one location to another.
object.MoveFile ( source, destination );

Arguments
object
Required. Always the name of a FileSystemObject.
source
Required. The path to the file or files to be moved. The source argument string can contain wildcard characters in the last path component only.
destination
Required. The path where the file or files are to be moved. The destination argument can't contain wildcard characters.
Remarks
If source contains wildcards or destination ends with a path separator (\), it is assumed that destination specifies an existing folder in which to move the matching files. Otherwise, destination is assumed to be the name of a
destination file to create. In either case, three things can happen when an individual file is moved:

If destination does not exist, the file gets moved. This is the usual case.
If destination is an existing file, an error occurs.
If destination is a directory, an error occurs.

An error also occurs if a wildcard character that is used in source doesn't match any files. The MoveFile method stops on the first error it encounters. No attempt is made to roll back any changes made before the error occurs.
Note This method allows moving files between volumes only if supported by the operating system.
The following example illustrates the use of the MoveFile method:
[JScript]
function MoveFile2Desktop(filespec)
{
var fso;

fso = new ActiveXObject("Scripting.FileSystemObject");


fso.MoveFile(filespec, "c:\\windows\\desktop\\");
}
[VBScript]
Sub MoveAFile(Drivespec)
Dim fso
Set fso = CreateObject("Scripting.FileSystemObject")
fso.MoveFile Drivespec, "c:\windows\desktop\"
End Sub

See Also
CopyFile Method | DeleteFile Method | GetFile Method | GetFileName Method | Move Method | MoveFolder Method | OpenTextFile Method
Applies To: FileSystemObject Object

2001 Microsoft Corporation. All rights reserved.


Build: Topic Version 5.6.9309.1546
Scripting Runtime Library

MoveFolder Method
Moves one or more folders from one location to another.
object.MoveFolder ( source, destination );

Arguments
object
Required. Always the name of a FileSystemObject.
source
Required. The path to the folder or folders to be moved. The source argument string can contain wildcard characters in the last path component only.
destination
Required. The path where the folder or folders are to be moved. The destination argument can't contain wildcard characters.
Remarks
If source contains wildcards or destination ends with a path separator (\), it is assumed that destination specifies an existing folder in which to move the matching files. Otherwise, destination is assumed to be the name of a
destination folder to create. In either case, three things can happen when an individual folder is moved:

If destination does not exist, the folder gets moved. This is the usual case.
If destination is an existing file, an error occurs.
If destination is a directory, an error occurs.

An error also occurs if a wildcard character that is used in source doesn't match any folders. The MoveFolder method stops on the first error it encounters. No attempt is made to roll back any changes made before the error
occurs.
Important This method allows moving folders between volumes only if supported by the operating system.
The following example illustrates the use of the MoveFolder method:
[JScript]
function MoveFldr2Desktop(fldrspec)
{
var fso;
fso = new ActiveXObject("Scripting.FileSystemObject");
fso.MoveFolder(fldrspec, "c:\\windows\\desktop\\");
}
[VBScript]
Sub MoveAFolder(Drivespec)
Dim fso
Set fso = CreateObject("Scripting.FileSystemObject")
fso.MoveFolder Drivespec, "c:\windows\desktop\"
End Sub

See Also
CopyFile Method | DeleteFile Method | GetFile Method | GetFileName Method | Move Method | MoveFile Method | OpenTextFile Method
Applies To: FileSystemObject Object

2001 Microsoft Corporation. All rights reserved.


Build: Topic Version 5.6.9309.1546
Scripting Runtime Library

OpenAsTextStream Method
Opens a specified file and returns a TextStream object that can be used to read from, write to, or append to the file.
object.OpenAsTextStream([iomode, [format]])

Arguments
object
Required. Always the name of a File object.
iomode
Optional. Indicates input/output mode. Can be one of three constants: ForReading, ForWriting, or ForAppending.
format
Optional. One of three Tristate values used to indicate the format of the opened file. If omitted, the file is opened as ASCII.
Settings
The iomode argument can have any of the following settings:
Constant
ForReading
ForWriting
ForAppending

Value
1
2
8

Description
Open a file for reading only. You can't write to this file.
Open a file for writing. If a file with the same name exists, its previous contents are overwritten.
Open a file and write to the end of the file.

The format argument can have any of the following settings:


Constant

Value

Description

TristateUseDefault -2
TristateTrue
-1
TristateFalse
0

Opens the file using the system default.


Opens the file as Unicode.
Opens the file as ASCII.

Remarks
The OpenAsTextStream method provides the same functionality as the OpenTextFile method of the FileSystemObject. In addition, the OpenAsTextStream method can be used to write to a file.
The following code illustrates the use of the OpenAsTextStream method:
[JScript]
function TextStreamTest( )
{
var fso, f, ts, s;
var ForReading = 1, ForWriting = 2, ForAppending = 8;
var TristateUseDefault = -2, TristateTrue = -1, TristateFalse = 0;
fso = new ActiveXObject("Scripting.FileSystemObject");
fso.CreateTextFile( "test1.txt" );
// Create a file.
f = fso.GetFile("test1.txt");
ts = f.OpenAsTextStream(ForWriting, TristateUseDefault);
ts.Write( "Hello World" );
ts.Close( );
ts = f.OpenAsTextStream(ForReading, TristateUseDefault);
s = ts.ReadLine( );
ts.Close( );
return(s);
}
[VBScript]
Function TextStreamTest
Const ForReading = 1, ForWriting = 2, ForAppending = 8
Const TristateUseDefault = -2, TristateTrue = -1, TristateFalse = 0
Dim fso, f, ts
Set fso = CreateObject("Scripting.FileSystemObject")
fso.CreateTextFile "test1.txt"
' Create a file.
Set f = fso.GetFile("test1.txt")
Set ts = f.OpenAsTextStream(ForWriting, TristateUseDefault)
ts.Write "Hello World"
ts.Close
Set ts = f.OpenAsTextStream(ForReading, TristateUseDefault)
TextStreamTest = ts.ReadLine
ts.Close
End Function

See Also
Copy Method | CreateTextFile Method | Delete Method | Move Method | OpenTextFile Method
Applies To: File Object

2001 Microsoft Corporation. All rights reserved.


Build: Topic Version 5.6.9309.1546
Scripting Runtime Library

OpenTextFile Method
Opens a specified file and returns a TextStream object that can be used to read from, write to, or append to the file.
object.OpenTextFile(filename[, iomode[, create[, format]]])

Arguments
object
Required. Object is always the name of a FileSystemObject.
filename
Required. String expression that identifies the file to open.
iomode
Optional. Can be one of three constants: ForReading, ForWriting, or ForAppending.
create
Optional. Boolean value that indicates whether a new file can be created if the specified filename doesn't exist. The value is True if a new file is created, False if it isn't created. If omitted, a new file isn't created.
format
Optional. One of three Tristate values used to indicate the format of the opened file. If omitted, the file is opened as ASCII.
Settings
The iomode argument can have any of the following settings:
Constant
ForReading
ForWriting
ForAppending

Value
Description
1
Open a file for reading only. You can't write to this file.
2
Open a file for writing.
8
Open a file and write to the end of the file.

The format argument can have any of the following settings:


Value
Description
TristateTrue
Open the file as Unicode.
TristateFalse
Open the file as ASCII.
TristateUseDefault Open the file using the system default.
Remarks
The following code illustrates the use of the OpenTextFile method to open a file for appending text:
[JScript]
var fs, a, ForAppending;
ForAppending = 8;
fs = new ActiveXObject("Scripting.FileSystemObject");
a = fs.OpenTextFile("c:\\testfile.txt", ForAppending, false);
...
a.Close();
[VBScript]
Sub OpenTextFileTest
Const ForReading = 1, ForWriting = 2, ForAppending = 8
Dim fso, f
Set fso = CreateObject("Scripting.FileSystemObject")
Set f = fso.OpenTextFile("c:\testfile.txt", ForWriting, True)
f.Write "Hello world!"
f.Close
End Sub

See Also

CreateTextFile Method | OpenAsTextStream Method


Applies To: FileSystemObject Object

2001 Microsoft Corporation. All rights reserved.


Build: Topic Version 5.6.9309.1546
Scripting Runtime Library

Read Method
Reads a specified number of characters from a TextStream file and returns the resulting string.
object.Read(characters)

Arguments
object
Required. Always the name of a TextStream object.
characters
Required. Number of characters you want to read from the file.
The following example illustrates how to use the Read method to read a six character header from a file and return the resulting string:
[JScript]
function GetHeader()
{
var fso, f;
var ForReading = 1, ForWriting = 2;
fso = new ActiveXObject("Scripting.FileSystemObject");
f = fso.OpenTextFile("c:\\testfile.txt", ForWriting, true);
f.Write("Header");
f.Write("1234567890987654321");
f.Close();
f = fso.OpenTextFile("c:\\testfile.txt", ForReading);
return(f.Read(6));
}
[VBScript]
Function ReadTextFileTest
Const ForReading = 1, ForWriting = 2, ForAppending = 8
Dim fso, f, Msg
Set fso = CreateObject("Scripting.FileSystemObject")
Set f = fso.OpenTextFile("c:\testfile.txt", ForWriting, True)
f.Write "Hello world!"
Set f = fso.OpenTextFile("c:\testfile.txt", ForReading)
ReadTextFileTest = f.Read(5)
End Function

See Also
ReadAll Method | ReadLine Method | Skip Method | SkipLine Method
Applies To: TextStream Object

2001 Microsoft Corporation. All rights reserved.


Build: Topic Version 5.6.9309.1546
Scripting Runtime Library

ReadAll Method
Reads an entire TextStream file and returns the resulting string.
object.ReadAll( );

The object is always the name of a TextStream object.


Remarks
For large files, using the ReadAll method wastes memory resources. Other techniques should be used to input a file, such as reading a file line by line.
The following example illustrates the use of the ReadAll method:
[JScript]
function GetEverything()
{
var fso, f;
var ForReading = 1, ForWriting = 2;
fso = new ActiveXObject("Scripting.FileSystemObject");
f = fso.OpenTextFile("c:\\testfile.txt", ForWriting, true);
f.Write("Header");
f.Write("1234567890987654321");
f.Close();
f = fso.OpenTextFile("c:\\testfile.txt", ForReading);
return(f.ReadAll());
}
[VBScript]
Function ReadAllTextFile
Const ForReading = 1, ForWriting = 2
Dim fso, f
Set fso = CreateObject("Scripting.FileSystemObject")
Set f = fso.OpenTextFile("c:\testfile.txt", ForWriting, True)
f.Write "Hello world!"
Set f = fso.OpenTextFile("c:\testfile.txt", ForReading)
ReadAllTextFile =
f.ReadAll
End Function

See Also
Read Method | ReadLine Method | Skip Method | SkipLine Method
Applies To: TextStream Object

2001 Microsoft Corporation. All rights reserved.


Build: Topic Version 5.6.9309.1546

Scripting Runtime Library

ReadLine Method
Reads an entire line (up to, but not including, the newline character) from a TextStream file and returns the resulting string.
object.ReadLine( )

The object argument is always the name of a TextStream object.


Remarks
The following example illustrates the use of the Line property:
[JScript]
function GetLine()
{
var fso, f, r;
var ForReading = 1, ForWriting = 2;
fso = new ActiveXObject("Scripting.FileSystemObject");
f = fso.OpenTextFile("c:\\testfile.txt", ForWriting, true);
f.WriteLine("Hello world!");
f.WriteLine("JScript is fun");
f.Close();
f = fso.OpenTextFile("c:\\testfile.txt", ForReading);
r = f.ReadLine();
return(r);
}
[VBScript]
Function ReadLineTextFile
Const ForReading = 1, ForWriting = 2
Dim fso, MyFile
Set fso = CreateObject("Scripting.FileSystemObject")
Set MyFile = fso.OpenTextFile("c:\testfile.txt", ForWriting, True)
MyFile.WriteLine "Hello world!"
MyFile.WriteLine "The quick brown fox"
MyFile.Close
Set MyFile = fso.OpenTextFile("c:\testfile.txt", ForReading)
ReadLineTextFile = MyFile.ReadLine
' Returns "Hello world!"
End Function

See Also
Read Method | ReadAll Method | Skip Method | SkipLine Method
Applies To: TextStream Object

2001 Microsoft Corporation. All rights reserved.


Build: Topic Version 5.6.9309.1546
Scripting Runtime Library

Skip Method
Skips a specified number of characters when reading a TextStream file.
object.Skip(characters)

Arguments
object
Required. Always the name of a TextStream object.
characters
Required. Number of characters to skip when reading a file.
Remarks
Skipped characters are discarded.
The following example illustrates the use of the Skip method:
[JScript]
function SkipDemo()
{
var fso, f, r;
var ForReading = 1, ForWriting = 2;
fso = new ActiveXObject("Scripting.FileSystemObject")
f = fso.OpenTextFile("c:\\testfile.txt", ForWriting, true);
f.WriteLine("Hello world!");
f.WriteLine("JScript is fun");
f.Close();
f = fso.OpenTextFile("c:\\testfile.txt", ForReading);
f.Skip(6);
r = f.ReadLine();
return(r);
}
[VBScript]
Function SkipTextFile
Const ForReading = 1, ForWriting = 2
Dim fso, f
Set fso = CreateObject("Scripting.FileSystemObject")
Set f = fso.OpenTextFile("c:\testfile.txt", ForWriting, True)
f.Write "Hello world!"
Set f = fso.OpenTextFile("c:\testfile.txt", ForReading)
f.Skip(6)
SkipTextFile =
f.ReadLine
End Function

See Also
Close Method | Read Method | ReadAll Method | ReadLine Method | SkipLine Method | Write Method | WriteLine Method | WriteBlankLines Method
Applies To: TextStream Object

2001 Microsoft Corporation. All rights reserved.


Build: Topic Version 5.6.9309.1546
Scripting Runtime Library

SkipLine Method
Skips the next line when reading a TextStream file.
object.SkipLine( )

The object is always the name of a TextStream object.


Remarks
The following examples illustrates the use of the SkipLine method:
[JScript]
function SkipLineDemo()
{
var fso, f, r
var ForReading = 1, ForWriting = 2;
fso = new ActiveXObject("Scripting.FileSystemObject")
f = fso.OpenTextFile("c:\\testfile.txt", ForWriting, true)
f.WriteLine("Hello world!");
f.WriteLine("JScript is fun");
f.Close();
f = fso.OpenTextFile("c:\\testfile.txt", ForReading);
f.SkipLine();
r = f.ReadLine();
return(r);
}
[VBScript]
Function SkipLineInFile
Const ForReading = 1, ForWriting = 2
Dim fso, f
Set fso = CreateObject("Scripting.FileSystemObject")
Set f = fso.OpenTextFile("c:\testfile.txt", ForWriting, True)
f.Write "Hello world!" & vbCrLf & "VB Script is fun!"
Set f = fso.OpenTextFile("c:\testfile.txt", ForReading)
f.SkipLine
SkipLineInFile = f.ReadLine
End Function

See Also
Read Method | ReadAll Method | ReadLine Method | Skip Method
Applies To: TextStream Object

2001 Microsoft Corporation. All rights reserved.


Build: Topic Version 5.6.9309.1546
Scripting Runtime Library

Write Method
Writes a specified string to a TextStream file.
object.Write(string)

Arguments
object
Required. Always the name of a TextStream object.
string
Required. The text you want to write to the file.
Remarks
Specified strings are written to the file with no intervening spaces or characters between each string. Use the WriteLine method to write a newline character or a string that ends with a newline character.
The following example illustrates the use of the Write method:
[JScript]
function WriteDemo()
{
var fso, f, r
var ForReading = 1, ForWriting = 2;
fso = new ActiveXObject("Scripting.FileSystemObject")
f = fso.OpenTextFile("c:\\testfile.txt", ForWriting, true)
f.Write("Hello world!");
f.Close();
f = fso.OpenTextFile("c:\\testfile.txt", ForReading);
r = f.ReadLine();
return(r);
}
[VBScript]
Function WriteToFile
Const ForReading = 1, ForWriting = 2
Dim fso, f
Set fso = CreateObject("Scripting.FileSystemObject")
Set f = fso.OpenTextFile("c:\testfile.txt", ForWriting, True)
f.Write "Hello world!"
Set f = fso.OpenTextFile("c:\testfile.txt", ForReading)
WriteToFile =
f.ReadLine
End Function

See Also
WriteBlankLines Method | WriteLine Method
Applies To: TextStream Object

2001 Microsoft Corporation. All rights reserved.


Build: Topic Version 5.6.9309.1546
Scripting Runtime Library

WriteBlankLines Method
Writes a specified number of newline characters to a TextStream file.

object.WriteBlankLines(lines)

Arguments
object
Required. Always the name of a TextStream object.
lines
Required. Number of newline characters you want to write to the file.
Remarks
The following example illustrates the use of the WriteBlankLines method:
[JScript]
function WriteBlanksDemo()
{
var fso, f, r;
var ForReading = 1, ForWriting = 2;
fso = new ActiveXObject("Scripting.FileSystemObject");
f = fso.OpenTextFile("c:\\testfile.txt", ForWriting, true);
f.Write("Hello world!");
f.WriteBlankLines(2);
f.Write("JScript is fun!");
f.Close();
f = fso.OpenTextFile("c:\\testfile.txt", ForReading);
r = f.ReadAll();
return(r);
}
[VBScript]
Function WriteBlankLinesToFile
Const ForReading = 1, ForWriting = 2
Dim fso, f
Set fso = CreateObject("Scripting.FileSystemObject")
Set f = fso.OpenTextFile("c:\testfile.txt", ForWriting, True)
f.WriteBlankLines 2
f.WriteLine "Hello World!"
Set f = fso.OpenTextFile("c:\testfile.txt", ForReading)
WriteBlankLinesToFile = f.ReadAll
End Function

See Also
Write Method | WriteLine Method
Applies To: TextStream Object

2001 Microsoft Corporation. All rights reserved.


Build: Topic Version 5.6.9309.1546
Scripting Runtime Library

WriteLine Method
Writes a specified string and newline character to a TextStream file.
object.WriteLine([string])

Arguments
object
Required. Always the name of a TextStream object.
string
Optional. The text you want to write to the file. If omitted, a newline character is written to the file.
Remarks
The following example illustrates use of the WriteLine method:
[JScript]
var fso, f;
fso = new ActiveXObject("Scripting.FileSystemObject");
f = fso.CreateTextFile("c:\\testfile.txt", true);
f.WriteLine("This is a test.");
f.Close();
[VBScript]
Function WriteLineToFile
Const ForReading = 1, ForWriting = 2
Dim fso, f
Set fso = CreateObject("Scripting.FileSystemObject")
Set f = fso.OpenTextFile("c:\testfile.txt", ForWriting, True)
f.WriteLine "Hello world!"
f.WriteLine "VBScript is fun!"
Set f = fso.OpenTextFile("c:\testfile.txt", ForReading)
WriteLineToFile = f.ReadAll
End Function

See Also
Write Method | WriteBlankLines Method
Applies To: TextStream Object

2001 Microsoft Corporation. All rights reserved.


Build: Topic Version 5.6.9309.1546
Scripting Runtime Library

FileSystemObject Objects
In This Section
Dictionary Object
Object that stores data key, item pairs.
Drive Object
Provides access to the properties of a particular disk drive or network share.
File Object
Provides access to all the properties of a file.
FileSystemObject Object

Provides access to a computer's file system.


Folder Object
Provides access to all the properties of a folder.
TextStream Object
Facilitates sequential access to file.
Related Sections
Scripting Run-Time Reference
List of elements that make up Scripting Run-Time Reference.
FileSystemObject Basics
A guide to the fundamentals of the FileSystemObject.
FileSystemObject Collections
List of collections you can use with the FileSystemObject object model.

2001 Microsoft Corporation. All rights reserved.


Build: Topic Version 5.6.9309.1546
Scripting Runtime Library

Drive Object
Provides access to the properties of a particular disk drive or network share.
Remarks
The following code illustrates the use of the Drive object to access drive properties:
[JScript]
function ShowFreeSpace(drvPath)
{
var fso, d, s;
fso = new ActiveXObject("Scripting.FileSystemObject");
d = fso.GetDrive(fso.GetDriveName(drvPath));
s = "Drive " + drvPath + " - " ;
s += d.VolumeName + "<br>";
s += "Free Space: " + d.FreeSpace/1024 + " Kbytes";
return(s);
}
[VBScript]
Function ShowFreeSpace(drvPath)
Dim fso, d, s
Set fso = CreateObject("Scripting.FileSystemObject")
Set d = fso.GetDrive(fso.GetDriveName(drvPath))
s = "Drive " & UCase(drvPath) & " - "
s = s & d.VolumeName
& "<BR>"
s = s & "Free Space: " & FormatNumber(d.FreeSpace/1024, 0)
s = s & " Kbytes"
ShowFreeSpace = s
End Function

Methods
The Drive object has no methods.
Properties
AvailableSpace Property | DriveLetter Property | DriveType Property | FileSystem Property | FreeSpace Property | IsReady Property | Path Property | RootFolder Property | SerialNumber Property | ShareName Property |
TotalSize Property | VolumeName Property
See Also
Drives Collection | File Object | Files Collection | Folder Object | Folders Collection | GetDrive Method

2001 Microsoft Corporation. All rights reserved.


Build: Topic Version 5.6.9309.1546
Scripting Runtime Library

File Object
Provides access to all the properties of a file.
Remarks
The following code illustrates how to obtain a File object and how to view one of its properties.
[JScript]
function ShowFileInfo(filespec)
{
var fso, f, s;
fso = new ActiveXObject("Scripting.FileSystemObject");
f = fso.GetFile(filespec);
s = f.DateCreated;
return(s);
}
[VBScript]
Function ShowDateCreated(filespec)
Dim fso, f
Set fso = CreateObject("Scripting.FileSystemObject")
Set f = fso.GetFile(filespec)
ShowDateCreated = f.DateCreated
End Function

Methods
Copy Method | Delete Method | Move Method | OpenAsTextStream Method
Properties
Attributes Property | DateCreated Property | DateLastAccessed Property | DateLastModified Property | Drive Property | Name Property | ParentFolder Property | Path Property | ShortName Property | ShortPath Property | Size
Property | Type Property
See Also

Drive Object | Drives Collection | Files Collection | Folder Object | Folders Collection

2001 Microsoft Corporation. All rights reserved.


Build: Topic Version 5.6.9309.1546
Scripting Runtime Library

FileSystemObject Object
Provides access to a computer's file system.
Remarks
[JScript]
The following code illustrates how the FileSystemObject is used to return a TextStream object that can be read from or written to:
[JScript]
var fso = new ActiveXObject("Scripting.FileSystemObject");
var a = fso.CreateTextFile("c:\\testfile.txt", true);
a.WriteLine("This is a test.");
a.Close();

[JScript]
In the example code, the ActiveXObject object is assigned to the FileSystemObject (fso). The CreateTextFile method then creates the file as a TextStream object (a), and the WriteLine method writes a line of text to the
created text file. The Close method flushes the buffer and closes the file.
[VBScript]
The following code illustrates how the FileSystemObject is used to return a TextStream object that can be read from or written to:
[VBScript]
Dim fso, MyFile
Set fso = CreateObject("Scripting.FileSystemObject")
Set MyFile = fso.CreateTextFile("c:\testfile.txt", True)
MyFile.WriteLine("This is a test.")
MyFile.Close

[VBScript]
In the preceding code, the CreateObject function returns the FileSystemObject (fso). The CreateTextFile method then creates the file as a TextStream object (a) and the WriteLine method writes a line of text to the created
text file. The Close method flushes the buffer and closes the file.
Methods
BuildPath Method | CopyFile Method | CopyFolder Method | CreateFolder Method | CreateTextFile Method | DeleteFile Method | DeleteFolder Method | DriveExists Method | FileExists Method | FolderExists Method |
GetAbsolutePathName Method | GetBaseName Method | GetDrive Method | GetDriveName Method | GetExtensionName Method | GetFile Method | GetFileName Method | GetFolder Method | GetParentFolderName Method |
GetSpecialFolder Method | GetTempName Method | MoveFile Method | MoveFolder Method | OpenTextFile Method
Properties
Drives Property
See Also
Dictionary Object | Drive Object | Drives Collection | File Object | Files Collection | Folder Object | Folders Collection | TextStream Object

2001 Microsoft Corporation. All rights reserved.


Build: Topic Version 5.6.9309.1546
Scripting Runtime Library

Folder Object
Provides access to all the properties of a folder.
Remarks
The following code illustrates how to obtain a Folder object and how to return one of its properties:
[JScript]
function ShowFolderInfo(folderspec)
{
var fso, folder, s;
fso = new ActiveXObject("Scripting.FileSystemObject");
folder = fso.GetFolder(folderspec);
s = folder.DateCreated;
return(s);
}
[VBScript]
Function ShowDateCreated(folderspec)
Dim fso, f
Set fso = CreateObject("Scripting.FileSystemObject")
Set f = fso.GetFolder(folderspec)
ShowDateCreated = f.DateCreated
End Function

Methods
Copy Method | Delete Method | Move Method | OpenAsTextStream Method
Properties
Attributes Property | DateCreated Property | DateLastAccessed Property | DateLastModified Property | Drive Property | Files Property | IsRootFolder Property | Name Property | ParentFolder Property | Path Property | ShortName
Property | ShortPath Property | Size Property | SubFolders Property | Type Property
See Also
Drive Object | Drives Collection | File Object | Files Collection | Folders Collection

2001 Microsoft Corporation. All rights reserved.


Build: Topic Version 5.6.9309.1546
Scripting Runtime Library

TextStream Object
Facilitates sequential access to file.
TextStream.{property

| method( )}

The property and method arguments can be any of the properties and methods associated with the TextStream object. Note that in actual usage, TextStream is replaced by a variable placeholder representing the TextStream
object returned from the FileSystemObject.
Remarks
In the following code, a is the TextStream object returned by the CreateTextFile method on the FileSystemObject:
[JScript]
var fso = new ActiveXObject("Scripting.FileSystemObject");
var a = fso.CreateTextFile("c:\\testfile.txt", true);
a.WriteLine("This is a test.");
a.Close();
[VBScript]
Dim fso, MyFile
Set fso = CreateObject("Scripting.FileSystemObject")
Set MyFile= fso.CreateTextFile("c:\testfile.txt", True)
MyFile.WriteLine("This is a test.")
MyFile.Close

WriteLine and Close are two methods of the TextStream object.


Methods
Close Method | Read Method | ReadAll Method | ReadLine Method | Skip Method | SkipLine Method | Write Method | WriteBlankLines Method | WriteLine Method
Properties
AtEndOfLine Property | AtEndOfStream Property | Column Property | Line Property
See Also
Dictionary Object | FileSystemObject Object

2001 Microsoft Corporation. All rights reserved.


Build: Topic Version 5.6.9309.1546
Scripting Runtime Library

FileSystemObject Collections
In This Section
Drives Collection
Read-only collection of all available drives.
Files Collection
Collection of all File objects within a folder.
Folders Collection
Collection of all Folder objects contained within a Folder object.
Related Sections
Scripting Run-Time Reference
List of elements that make up Scripting Run-Time Reference.
FileSystemObject Basics
A guide to the fundamentals of the FileSystemObject.

2001 Microsoft Corporation. All rights reserved.


Build: Topic Version 5.6.9309.1546
Scripting Runtime Library

Drives Collection
Read-only collection of all available drives.
Remarks
Removable-media drives need not have media inserted for them to appear in the Drives collection.
[JScript]
The following example illustrates how to get the Drives collection using the Drives property and iterate the collection using the Enumerator object:
[JScript]
function ShowDriveList()
{
var fso, s, n, e, x;
fso = new ActiveXObject("Scripting.FileSystemObject");
e = new Enumerator(fso.Drives);
s = "";
for (; !e.atEnd(); e.moveNext())
{
x = e.item();
s = s + x.DriveLetter;
s += " - ";
if (x.DriveType == 3)
n = x.ShareName;
else if (x.IsReady)
n = x.VolumeName;
else

n = "[Drive not ready]";


s +=
n + "<br>";
}
return(s);
}

[VBScript]
The following code illustrates how to get the Drives collection and iterate the collection using the For Each...Next statement:
[VBScript]
Function ShowDriveList
Dim fso, d, dc, s, n
Set fso = CreateObject("Scripting.FileSystemObject")
Set dc = fso.Drives
For Each d in dc
n = ""
s = s & d.DriveLetter & " - "
If d.DriveType = Remote Then
n = d.ShareName
ElseIf d.IsReady Then
n = d.VolumeName
End If
s = s & n & "<BR>"
Next
ShowDriveList = s
End Function

Methods
The Drives collection has no methods.
Properties
Count Property | Item Property
See Also
Drive Object | Drives Property | File Object | Files Collection | Folder Object | Folders Collection

2001 Microsoft Corporation. All rights reserved.


Build: Topic Version 5.6.9309.1546
Scripting Runtime Library

Files Collection
Collection of all File objects within a folder.
Remarks
[JScript]
The following example illustrates how to get a Files collection and iterate the collection using the Enumerator object and the for statement:
[JScript]
function ShowFolderFileList(folderspec)
{
var fso, f, f1, fc, s;
fso = new ActiveXObject("Scripting.FileSystemObject");
f = fso.GetFolder(folderspec);
fc = new Enumerator(f.files);
s = "";
for (; !fc.atEnd(); fc.moveNext())
{
s += fc.item();
s += "<br>";
}
return(s);
}

[VBScript]
The following code illustrates how to get a Files collection and iterate the collection using the For Each...Next statement:
[VBScript]
Function ShowFolderList(folderspec)
Dim fso, f, f1, fc, s
Set fso = CreateObject("Scripting.FileSystemObject")
Set f = fso.GetFolder(folderspec)
Set fc = f.Files
For Each f1 in fc
s = s & f1.name
s = s & "<BR>"
Next
ShowFolderList = s
End Function

Methods
The Files collection has no methods.
Properties
Count Property | Item Property
See Also
Drive Object | Drives Collection | File Object | Folder Object | Folders Collection

2001 Microsoft Corporation. All rights reserved.


Build: Topic Version 5.6.9309.1546
Scripting Runtime Library

Folders Collection

Collection of all Folder objects contained within a Folder object.


Remarks
[JScript]
The following example illustrates how to get a Folders collection and how to iterate the collection using the Enumerator object and the for statement:
[JScript]
function ShowFolderList(folderspec)
{
var fso, f, fc, s;
fso = new ActiveXObject("Scripting.FileSystemObject");
f = fso.GetFolder(folderspec);
fc = new Enumerator(f.SubFolders);
s = "";
for (; !fc.atEnd(); fc.moveNext())
{
s += fc.item();
s += "<br>";
}
return(s);
}

[VBScript]
The following code illustrates how to get a Folders collection and how to iterate the collection using the For Each...Next statement:
[VBScript]
Function ShowFolderList(folderspec)
Dim fso, f, f1, fc, s
Set fso = CreateObject("Scripting.FileSystemObject")
Set f = fso.GetFolder(folderspec)
Set fc = f.SubFolders
For Each f1 in fc
s = s & f1.name
s = s &
"<BR>"
Next
ShowFolderList = s
End Function

Methods
Add Method (Folders)
Properties
Count Property | Item Property
See Also
Drive Object | Drives Collection | File Object | Files Collection | Folder Object | SubFolders Property

2001 Microsoft Corporation. All rights reserved.


Build: Topic Version 5.6.9309.1546
Windows Script Host

Windows Script Host


In This Section
Getting Started
WSH Basics
Running Your Scripts
Basic Windows Script Host Tasks
Security and Windows Script Host
Reference

2001 Microsoft Corporation. All rights reserved.


Build: Topic Version 5.6.9309.1546
Windows Script Host

Getting Started
In This Section
What's New in WSH
Description of the new features in WSH 5.6.
Document Conventions
Description of the syntax and conventions used in WSH 5.6 help documentation.
Related Sections
WSH Reference
List of elements that make up WSH Reference.
WSH Basics
Learn the basics of WSH.

2001 Microsoft Corporation. All rights reserved.


Build: Topic Version 5.6.9309.1546
Windows Script Host

What's New In WSH 5.6


Several areas of functionality have been addressed in this latest version of the Windows Script Host (version 5.6).

Argument handling has been improved Handling and documenting command line arguments is simpler. The process of integrating your scripts with other command line scripts has been simplified, and it is easier to
create scripts that can supply the user with help information. Refer to the following table for information on the WSH language features that connect you to this new functionality.
To Learn About
See
Grouping your script's switches together.
<runtime> Element
Defining your script's named switches.
<named> Element
Defining your script's unnamed switches.
<unnamed> Element
Making your script self-documenting.
<example> Element
<description> Element
Sharing the environment of the current process (IOW, WSH) with a Exec Method
spawned process.
Accessing the standard streams programmatically.
Exec Method

Accessing environment variables programmatically.

WshScriptExec Object
Environment Property
WshEnvironment Object
ExpandEnvironmentStrings Method

Remove Method
Determining whether a spawned script process is currently running. Status Property (WshScriptExec)
Accessing the spawned script process's StdIn input stream.
StdIn Property (WshScriptExec)
Accessing the spawned script process's StdOut output stream.
StdOut Property (WshScriptExec)
Accessing the spawned script process' StdErr output stream.
StdErr Property (WshScriptExec)
Terminating a spawned script process.
Terminate Method (WshScriptExec)
Accessing the named command-line script arguments.
WshNamed Object
Determining whether a specific key value exists in the WshNamed Exists Method
object.
Determining the number of switches in the WshNamed or
Count Method
WshUnnamed objects.
You can run scripts remotely You can load scripts onto several remote computer systems and start them all running simultaneously. While a remote script is running, you can check its progress. After it has finished,
you can ensure that it ran correctly or determine the cause of its premature termination. There is a new dispatch object used to create remote WSH objects the Controller object. In addition, there is a new object that
represents an instance of a running script the Remote WSH object.
To Learn About
See
Creating a remote script object the remote WSH interface.
WshController Object
Creating a remote script object using remote WSH interface.
CreateScript Method
Creating a remote script object getting a handle.
WshRemote Object
Starting a remote script process.
Execute Method
Determining whether a remote script is currently running.
Status Property (WshRemote)
Determining why a remote script terminated.
Description Property (WshRemoteError)
Identifying which statement in your remote script caused it to terminate. Line Property (WshRemoteError)
Accessing error information after a remote script terminates.
WshRemoteError Object
Identifying the character in the line of code that contained the error.
Character Property
Identifying the error number representing a script error.
Number Property
Identifying the source of the script error.
Source Property
Identifying the line of source code that caused an error.
SourceText Property
Handling remote object events.
Start Event
End Event

Error Event
When you start new processes, you can treat them as objects You determine the status of spawned processes and access their standard I/O streams.
To Learn About
See
Spawning a process.
Exec Method
Accessing the object that represents running processes. WshScriptExec Object
Accessing process status information.
Status Property (WshScriptExec)
Accessing the standard I/O streams.
StdOut Property (WshScriptExec)
StdIn Property (WshScriptExec)
StdErr Property (WshScriptExec)
You can access the current working directory You can determine/modify the active process's current working directory.
To Learn About
See
Accessing the active directory information. CurrentDirectory Property
Security issues unique to scripts have been addressed A new security model makes distributing and running scripts safer.
To Learn About
See
Script signing and verification. Security and Windows Script Host

2001 Microsoft Corporation. All rights reserved.


Build: Topic Version 5.6.9309.1546
Windows Script Host

Upgrading Windows Script Host


If you are currently using Windows 2000 or Windows ME, you have version 2.0 of WSH installed on your computer system. If you are running Windows 95, 98, or Windows NT 4.0, you have version 1.0. To upgrade to WSH
5.6, visit the Microsoft Windows Script Technologies Web site at (http://msdn.microsoft.com/scripting/).
Note

The latest version of WSHis 5.6 due to a file versioning issue that was easiest to resolve by skipping some version numbers.

2001 Microsoft Corporation. All rights reserved.


Build: Topic Version 5.6.9309.1546
Windows Script Host

Document Conventions
Throughout the Windows Script Host 5.6 Help documentation, different fonts, weights, and colors are used to draw your attention to text of interest.
Examples of Text Styles

Type of Information
Sample
WScript.Echo "Hello from VBScript"
Code snippets appear in Courier blue
WScript.Echo
"Hello
from
VBScript"
Featured elements in code snippets appear bolded in Courier blue
Keywords appear bolded
in the Script tab within the Properties dialog
Links appear underlined
WshNetwork Object
Pop-up links appear italicized, and underlined
<?job error="flag" debug="flag" ?>

2001 Microsoft Corporation. All rights reserved.


Build: Topic Version 5.6.9309.1546
Windows Script Host

WSH Version Information


The following table lists the version of Windows Script Host implemented by Microsoft host applications.
Host Application
Microsoft Windows 98
x
Microsoft Windows NT 4 Option Pack x
Microsoft Windows 2000

1.0

2.0

5.6

The following table lists Windows Script Host language elements and the version in which they were introduced.
Language Element
<?job ?> Element
<?XML ?> Element
AddPrinterConnection Method
x
AddWindowsPrinterConnection Method
AppActivate Method
Arguments Property
x
AtEndOfLine Property
AtEndOfStream Property
Character Property
Close Method
Column Property
ComputerName Property
x
ConnectObject Method
Count Method
x
CreateObject Method
x
CreateScript Method
CreateShortcut Method
x
Description Property
x
Description Property (WshRemote)
DisconnectObject Method
x
Echo Method
x
EnumNetworkDrives Method
x
EnumPrinterConnections Method
x
Environment Property
x
Error Property (WshRemote)
<example> Element
Exec Method
Execute Method
Exists Method
ExitCode Property
ExpandEnvironmentStrings Method
x
FullName Property
x
GetObject Method
x
GetResource Method
HotKey Property
x
IconLocation Property
x
Item Property
x
Item Property (WshNamed)
Item Property (WshUnnamed)
<job> Element
Length Property
x
Line Property
Line Property (WshRemote)
LogEvent Method
MapNetworkDrive Method
x
Name Property
x
<named> Element
Number Property
<object> Element
<package> Element
Path Property
x
Popup Method
x
ProcessID Property
Quit Method
x
Read Method
ReadAll Method
ReadLine Method
<reference> Element
RegDelete Method
x
RegRead Method
x
RegWrite Method
x
Remove Method
x
RemoveNetworkDrive Method
x
RemovePrinterConnection Method
x
<resource> Element
Run Method
x
<runtime> Element
Save Method
x
<script> Element
ScriptFullName Property
x
ScriptName Property
x
SendKeys Method
SetDefaultPrinter Method
x

1.0

2.0

5.6

X
X
X
X
X
X
x
X
X
x

x
x
x
x
x
x

x
x
x

x
x
x

x
x
x
x

x
x
x
x
x

x
x

ShowUsage Method
Skip Method
SkipLine Method
Sleep Method
Source Property
SourceText Property
SpecialFolders Property
Status Property (WshRemote)
Status Property (WshScriptExec)
StdErr Property
StdErr Property (WshScriptExec)
StdIn Property
StdIn Property (WshScriptExec)
StdOut Property
StdOut Property (WshScriptExec)
TargetPath Property
Terminate Method (WshScriptExec)
<usage> Element
UserDomain Property
UserName Property
Version Property
WindowStyle Property
WorkingDirectory Property
Write Method
WriteBlankLines Method
WriteLine Method
WScript Object
WshArguments Object
WshController Object
WshEnvironment Object
WshNamed Object
WshNetwork Object
WshRemote Object
WshRemoteError Object
WshScriptExec Object
WshShell Object
WshShortcut Object
WshSpecialFolders Object
WshUnnamed Object
WshUrlShortcut Object

x
x
x
x
x
x
x
x
x
x
x
x
x
x
x
x
x
x
x
x
x
x
x
x
x
x
x
x
x
x
x
x
x
x
x
x
x
x
x
x

2001 Microsoft Corporation. All rights reserved.


Build: Topic Version 5.6.9309.1546
Windows Script Host

Windows Script Host Basics


Microsoft Windows Script Host (WSH) is a language-independent scripting host for Windows Script compatible scripting engines. It brings simple, powerful, and flexible scripting to the Windows 32-bit platform, allowing
you to run scripts from both the Windows desktop and the command prompt.
Windows Script Host is ideal for non-interactive scripting needs, such as logon scripting, administrative scripting, and machine automation.
In the Section
What Is WSH?
General overview of Windows Script Host
Hosting Environments and Script Engines
About the WSH Host environment and the script engines you can use
Creating Scripts that Can Be Used with WSH
How to create a WSH-compatible script
Windows Script Host Object Model
A roadmap to the architecture

2001 Microsoft Corporation. All rights reserved.


Build: Topic Version 5.6.9309.1546
Windows Script Host

What Is WSH?
Windows Script Host (WSH) is a Windows administration tool.
WSH creates an environment for hosting scripts. That is, when a script arrives at your computer, WSH plays the part of the host it makes objects and services available for the script and provides a set of guidelines within
which the script is executed. Among other things, Windows Script Host manages security and invokes the appropriate script engine.
WSH is language-independent for WSH-compliant scripting engines. It brings simple, powerful, and flexible scripting to the Windows platform, allowing you to run scripts from both the Windows desktop and the command
prompt.
Windows Script Host is ideal for noninteractive scripting needs, such as logon scripting, administrative scripting, and machine automation.

WSH Objects and Services


Windows Script Host provides several objects for direct manipulation of script execution, as well as helper functions for other actions. Using these objects and services, you can accomplish tasks such as the following:

Print messages to the screen


Run basic functions such as CreateObject and GetObject
Map network drives
Connect to printers
Retrieve and modify environment variables
Modify registry keys

Where Is WSH?
Windows Script Host is built into Microsoft Windows 98, 2000, and Millennium Editions. If you are running Windows 95, you can download Windows Script Host 5.6 from the Microsoft Windows Script Technologies Web site

(http://msdn.microsoft.com/scripting).
Note You can also go to the website listed above to upgrade your current engines. The version of WSH in Windows 98, 2000, and Millennium Editions is either version 1.0 or 2.0. You must upgrade to version 5.6
to get the new features.
See Also
Windows Script Host Object Model | CreateObject | GetObject

2001 Microsoft Corporation. All rights reserved.


Build: Topic Version 5.6.9309.1546
Windows Script Host

Scripts and Automating Windows


Computers are wonderful tools that perform repetitive tasks. But what if you need to perform a series of repetitive tasks? The answer lies in scripting.

What Is a Script?
A script is a program written in a scripting language, such as JScript and VBScript. Alternative script languages include Rexx, Python, and Perl. When compared to programming languages such as C++ and Visual Basic,
scripting languages are better suited to creating short applications that provide quick solutions to small problems.

Automating Windows
In many cases, scripts are used to automate manual tasks, much like a macro. Scripts are well suited for:

Manipulating the Windows environment


Running other programs
Automating logon procedures
Sending key sequences to an application

For example, if you have several similar tasks, you can write one generalized script that can handle all of them.
You can write scripts that start an action in response to an event. You can write scripts that keep a running tally of events and trigger some action only when certain criteria are met.
Scripts are also useful for nonrepetitive tasks as well. If a task requires you to do many things in sequence, you can turn that sequence of tasks into just one task by scripting it.
See Also
Types of Script Files

2001 Microsoft Corporation. All rights reserved.


Build: Topic Version 5.6.9309.1546
Windows Script Host

Types of Script Files


Stand-alone scripts come in several varieties, and each has its own extension. The following table is a list of some common types.
Extension
.bat
.asp
.html
.js
.vbs
.wsf
.wsh

Script Type
MS-DOS batch file
ASP page
HTML file
JScript file
VBScript file
Windows Script Host file
Windows Script Host files

Description
MS-DOS operating system batch file
Active Server Page file
Web page
Windows script
Windows script
Container or project file for a Windows script; supported by WSH 2.0 and later.
Property file for a script file; supported by WSH 1.0 and later.

Each script type is suited to different application needs, and each has strengths and weaknesses. The script type you choose depends on your needs.
Still, there are certain scenarios where you could divide your overall problem into several smaller parts, writing a separate script for each part with each script written in the most suitable scripting language.
This is where Windows Script Host files (WSF files) are useful. WSF files may include other script files as part of the script. Consequently, multiple WSF files can reference libraries of useful functions, which may be created
and stored in a single place.
See Also
Windows Script Host Object Model

2001 Microsoft Corporation. All rights reserved.


Build: Topic Version 5.6.9309.1546
Windows Script Host

Hosting Environments and Script Engines


Scripts are often embedded in Web pages, either in an HTML page (on the client side) or in an ASP page (on the server side). In the case of a script embedded in an HTML page, the engine component that interprets and runs the
script code is loaded by the Web browser, such as Internet Explorer. In the case of a script embedded in an ASP page, the engine that interprets and runs the script code is built into Internet Information Services (IIS).
Windows Script Host executes scripts that exist outside an HTML or ASP page and that stand on their own as text files.

Available Script Engines


Generally, you write scripts in either Microsoft JScript or VBScript, the two script engines that ship with Microsoft Windows 98, 2000 and Millennium Editions. You can use other script engines, such as Perl, REXX, and
Python, with Windows Script Host.
Note

For more information, see MicrosoftDeveloper Network (MSDN) (http://msdn.microsoft.com/workshop/languages/clinic/vbsvjs.asp).

A stand-alone script written in JScript has the .js extension; a stand-alone script written in VBScript has the .vbs extension. These extensions are registered with Windows. When you run one of these types of files, Windows

starts Windows Script Host, which invokes the associated script engine to interpret and run the file.
Note

If you need to run another engine, thatengine must be registered properly.

2001 Microsoft Corporation. All rights reserved.


Build: Topic Version 5.6.9309.1546
Windows Script Host

Creating Scripts that Can Be Used by WSH


A Windows script is a text file. You can create a script with any text editor as long as you save your script with a WSH-compatible script extension (.js, vbs, or .wsf).
The most commonly available text editor is already installed on your computer Notepad. You can also use your favorite HTML editor, Microsoft Visual C++, or Visual InterDev.
To create a script with Notepad
1.
2.
3.
4.
5.

Start Notepad.
Write your script. For example purposes, type WScript.Echo("Hello World!");
Save this text file with a .js extension (instead of the default .txt extension). For example, Hello.js.
Navigate to the file you just saved, and double-click it.
Windows Script Host invokes the JScript engine and runs your script. In the example, a message box is displayed with the message "Hello World!"

2001 Microsoft Corporation. All rights reserved.


Build: Topic Version 5.6.9309.1546
Windows Script Host

Dividing Scripts into Reusable Parts


To simplify your script writing, you can divide a script into more than one part. With this approach, you would create a .wsf file and use it as the starting point of execution. The other parts could be .js or .vbs files. You would
reference these files from the .wsf file.
This approach makes your code more robust because it isolates pieces of it, allowing you to debug one piece at a time. It also makes your code reusable because it allows you to create functions that can be called again and again.

2001 Microsoft Corporation. All rights reserved.


Build: Topic Version 5.6.9309.1546
Windows Script Host

Windows Script Host Object Model


The Windows Script Host object model consists of 14 objects. The root object is the WScript object.
The illustration that follows represents the Windows Script Host Object Model hierarchy. Click an object in the diagram to see its associated Help topic.

The Windows Script Host object model provides a logical, systematic way to perform many administrative tasks. The set of COM interfaces it provides can be placed into two main categories:

Script Execution and Troubleshooting


This set of interfaces allows scripts to perform basic manipulation of the Windows Script Host, output messages to the screen, and perform basic COM functions such as CreateObject and GetObject.

Helper Functions
Helper functions are properties and methods for performing actions, such as mapping network drives, connecting to printers, retrieving and modifying environment variables, and manipulating registry keys. Administrators
can also use the Windows Script Host helper functions to create simple logon scripts.

WSH Objects and Associated Tasks


The following table is a list of the WSH objects and the typical tasks associated with them.
Object
Wscript

What you can do with this object


Set and retrieve command line arguments
Determine the name of the script file
Determine the host file name (wscript.exe or cscript.exe)
Determine the host version information
Create, connect to, and disconnect from COM objects
Sink events
Stop a script's execution programmatically
Output information to the default output device (for example, a dialog box or the command line)
Access the entire set of command-line arguments
Access the set of named command-line arguments
Access the set of unnamed command-line arguments
Connect to and disconnect from network shares and network printers
Map and unmap network shares
Access information about the currently logged-on user

WshArguments
WshNamed
WshUnnamed
WshNetwork

WshController
WshRemote

Create a remote script process using the Controller method CreateScript()


Remotely administer computer systems on a computer network
Programmatically manipulate other programs/scripts
Access the error information available when a remote script (a WshRemote object) terminates as a result of a script error
Run a program locally
Manipulate the contents of the registry
Create a shortcut
Access a system folder
Manipulate environment variables (such as WINDIR, PATH, or PROMPT)
Programmatically create a shortcut
Access any of the Windows Special Folders
Programmatically create a shortcut to an Internet resource
Access any of the environment variables (such as WINDIR, PATH, or PROMPT)
Determine status and error information about a script run with Exec()

WshRemote Error
WshShell

WshShortcut
WshSpecialfolders
WshURLShortcut
WshEnvironment
WshScriptExec

Access the StdIn, StdOut, and StdErr channels


In addition to the object interfaces provided by Windows Script Host, administrators can use any ActiveX control that exposes automation interfaces to perform various tasks on the Windows platform. For example,
administrators can write scripts to manage the Windows Active Directory Service Interface (ADSI).

2001 Microsoft Corporation. All rights reserved.


Build: Topic Version 5.6.9309.1546
Windows Script Host

Running Your Scripts


There are three ways to run your scripts.

In the Windows environment, double-click the icon of the script (you run script files the same way you run regular executable files).
In the Windows environment, click the Start button, and then click Run. In the Open field of the Run dialog box, type the full path of the script, and click OK.
From the command line, type the name of the script.

See Also
Running Scripts with WScript.exe | Running Scripts with CScript.exe | What to Include to Run a Script | Drag and Drop Support

2001 Microsoft Corporation. All rights reserved.


Build: Topic Version 5.6.9309.1546
Windows Script Host

Using Windows Script Files (.wsf)


A Windows script (*.wsf) file is a text document containing Extensible Markup Language (XML) code. It incorporates several features that offer you increased scripting flexibility. Because Windows script files are not enginespecific, they can contain script from any Windows Script compatible scripting engine. They act as a container.
With .wsf files, you can take advantage of the following features as you create your scripts:
.wsf files support
Include statements
Multiple engines
Type libraries
Tools
Multiple jobs in one file

You can
Incorporate functions from VBScript or JScript files into your Windows Script Host project.
Use more than one scripting language per file.
Add constants to your code.
Edit files with any XML editor.
Store all of your code in a single location.

Include Statements
If you have .js and .vbs files from previous Windows Script Host projects, a .wsf file enables you to use them with Windows Script Host. A .wsf file encapsulates a library of functions that can in turn be used by multiple .wsf
files.
The following example shows a .wsf file that includes a JScript file (fso.js), plus a VBScript function that calls a function (GetFreeSpace) in the included file. The contents of fso.js are also shown.
<job id="IncludeExample">
<script language="JScript" src="FSO.JS"/>
<script language="VBScript">
' Get the free space for drive C.
s = GetFreeSpace("c:")
WScript.Echo s
<sScript>
</job>

The fso.js file contains the following:


function GetFreeSpace(drvPath) {
var fs, d, s;
fs = new ActiveXObject("Scripting.FileSystemObject");
d = fs.GetDrive(fs.GetDriveName(drvPath));
s = "Drive " + drvPath + " - " ;
s += d.VolumeName;
s += " Free Space: " + d.FreeSpace/1024 + " Kbytes";
return s;
}

Multiple-Engine Support
Since one scripting language may not have all the functionality you need, Windows Script Host allows you to combine multiple languages in a single .wsf file. The following example shows a .wsf file that includes both
VBScript and PerlScript code:
<job id="PERLandVBS">
<script language="PerlScript">
sub PerlHello {
my $str = @_[0];
$WScript->Echo($str);
}
</script>
<script language="VBScript">
WScript.Echo "Hello from VBScript"
PerlHello "Hello from PERLScript"
</script>

</job>

Type Library Support


In the following example, "MyComponent" was developed with Microsoft Visual Basic 5.0. "MyComponent" defines the constant MyError with the following statement.
Public Const MyError = "You are not using MyComponent correctly"

The type library is contained in mycomponent.lib, which is installed in C:\MyComponent.


<job id="IncludeExample">
<reference progid="MyComponent.MyClass">
<script language="VBScript">
Dim MyVar
Set MyVar = CreateObject("MyComponent.MyClass")
Currentreturn = MyVar.MyMethod
If Currentreturn = False then
WScript.Echo MyError
End If
</script>
</job>

Tools Support
Since the .wsf file is in XML format, you can use any editor that supports XML to edit .wsf files. This includes text editors, such as Notepad.

Multiple Jobs in One File


Instead of keeping all your scripts in separate files, you can incorporate them all into one .wsf file and break them into several different jobs. You can then run each job separately using syntax similar to the following example,
where "MyFirstJob" is the name of the job contained in the MyScripts.wsf file.
CScript //Job:MyFirstJob MyScripts.wsf

2001 Microsoft Corporation. All rights reserved.


Build: Topic Version 5.6.9309.1546
Windows Script Host

WSH Drag and Drop Support


You can drag files onto a WSH script. The file names are translated into arguments on the command line. These file names can be displayed in a list, which you can use to manipulate files with any scripting object.
To display a script's argument list
1. Create a file and give it a name with a script extension (for example, DragDrop.vbs).
2. Add code to the script file, for example:
Set objArgs = WScript.Arguments
For I = 0 to objArgs.Count - 1
WScript.Echo objArgs(I)
Next

3. Save the file to your hard disk.


4. Drag and drop any file or files onto your saved file. In the example, the file names are echoed back to the screen.
The number of files you can drag onto a script is limited by the your system's maximum command-line length. If the total number of characters in all file names being dragged exceeds this limit, the drag and drop operation fails.

2001 Microsoft Corporation. All rights reserved.


Build: Topic Version 5.6.9309.1546
Windows Script Host

Setting and Customizing Script Properties (.wsh)


You can record specific settings for each of your individual scripts by means of a Windows Script Host control (.wsh) file. The .wsh file is a text document in which you can customize execution of one or more of your scripts. It
is created automatically when you set the properties for a supported script file.
If you create multiple .wsh files for a single script, you can tailor the way the script runs to the needs of specific groups or even individuals within an organization. For example, you could create a single logon script that is
invoked by two different .wsh files that contain different settings and parameters.
When you double-click a .wsh file or run it from the command line, CScript.exe or WScript.exe reads the .wsh file to determine the specific settings that should be used to execute the script. CScript/WScript executes the original
script, passing in the properties that are defined within the .wsh file.
To create a .wsh file for a given script
1.
2.
3.
4.

Right-click the script file in Windows Explorer.


Click Properties on the shortcut menu.
Choose the settings you want for the script.
Click OK or Apply.
A .wsh file is created with the same name as the script file you selected.

The following example illustrates a typical .wsh file:


[ScriptFile]
Path=C:\WINNT\Samples\WSH\showprop.vbs
[Options]
Timeout=0
DisplayLogo=1
BatchMode=0

The path information in the [ScriptFile] section identifies the script file that is associated with the .wsh file. The keys in the [Options] section correspond to settings in the Script tab within the Properties dialog box.
Note You must have the original script file present when executing the .wsh file. If the .wsh file fails to run the script, check the Path= information in the .wsh file to ensure that it points to the script you are
attempting to run.

2001 Microsoft Corporation. All rights reserved.

Build: Topic Version 5.6.9309.1546


Windows Script Host

Running Scripts from the Command Prompt


Windows Script Host enables you to run scripts from the command prompt. CScript.exe provides command-line switches for setting script properties.
To run scripts using CScript.exe

Type a command at the command prompt using the following syntax:


cscript [host options...] [script name] [script options and parameters]

Host Options enable or disable various Windows Script Host features. Host options are preceded by two slashes (//).Script name is the name of the script file with extension and necessary path information, for example,
d:\admin\vbscripts\chart.vbs. Script options and parameters are passed to the script. Script parameters are preceded by a single slash (/).
Each parameter is optional; however, you cannot specify script options without specifying a script name. If you do not specify parameters, CScript displays the CScript syntax and the valid host parameters.

CScript Example
Several sample scripts, which are installed along with Windows Script Host, are also available for download at (http://msdn.microsoft.com/scripting).
Suppose, for the purposes of this example, that you have copied the Chart.vbs sample script to the following folder on your computer:
c:\sample scripts\chart.vbs

You can run the script with and without a logo as follows.
To run a script with or without a logo
1. Start the MS-DOS command prompt.
2. Enter the following commands at the command prompt (modify accordingly if your sample scripts are located in a different folder):
cscript //logo c:\"sample scripts"\chart.vbs
cscript //nologo c:\"sample scripts"\chart.VBScript

See Also
Running Scripts from Windows | What to Include to Run a Script | WScript.exe and CScript.exe Options

2001 Microsoft Corporation. All rights reserved.


Build: Topic Version 5.6.9309.1546
Windows Script Host

Running Scripts from Windows


Windows Script Host enables you to run scripts from Windows. WScript.exe provides a Windows-based dialog box for setting script properties. Using WScript.exe, you can run scripts under Windows in the following ways.
Whether you use WScript or CScript, you still run the scripts in the same manner. The difference is only in the output WScript generates windowed output, while CScript sends its output to the command window in which it
was started.
On initial installation, the default host is WScript. To change it to CScript, type the following at the command line:
cscript //h:cscript

Or, to change it from Cscript to Wscript:


wscript //h:cscript

To run a script using the default engine:


1. Double click the script in Windows Explorer or on the desktop.
2. Click Start, select Run, and enter the script name.
Note

On WindowsNT and Windows 2000 only, simply enter the script name on a command line.

To run a script using a particular engine:

Right-click the script in Windows Explorer and select Open to run in WScript or Open in MS-DOS Window (Windows 9x) or Open in Command Window (Windows NT and Windows 2000) to run in CScript.

-or

Click Start, select Run, enter "cscript" or "wscript" followed by the script name.

-or

Enter "cscript" or "wscript" on the command line, followed by the script name.

To run scripts using WScript.exe

Double-click files or icons. These can be files or icons listed in My Computer, Windows Explorer, the Find window, the Start menu, or on the desktop.

-or1. Click the Start button, and then click Run.


2. In the Open field, type the full path of the script, and then click OK. You can also type WScript followed by the full name and path of the script you want to run.
If you double-click a script file whose extension has not yet been associated with WScript.exe, the Open With dialog box appears and asks which program to use to open the file. Choose WScript and check Always use this
program to open this file to register WScript as the default application for all files with that extension.
The WScript.exe and CScript.exe properties dialog box provides the following options:
Property
Stop script after specified number of seconds.

Description
Specifies the maximum number of seconds that a script can run. The default is no limit.

Display logo when script is executed in command console.

CScript.exe equivalent: //T:nn


Displays a banner before running the script. This is the default. The opposite is //nologo.
CScript.exe equivalent: //logo or //nologo

Using the WScript.exe Properties dialog box, you can set global scripting options for all scripts that WScript runs on the local machine. You can also set options for individual scripts using a .wsf file.

See Also
Running Scripts from the Command Prompt | What to Include to Run a Script | WScript.exe and CScript.exe Options

2001 Microsoft Corporation. All rights reserved.


Build: Topic Version 5.6.9309.1546
Windows Script Host

WScript.exe and CScript.exe Options


For the most part, options listed in the following table are applicable to both WScript.exe and CScript.exe. Exceptions are noted.
Parameter
//B
//D
//E:engine
//H:CScript or //H:Wscript
//I
//Job:<JobID>
//logo
//nologo
//S
//T:nn
//U
//X
//?

Description
Batch mode; suppresses command-line display of user prompts and script errors. Default is Interactive mode.
Turns on the debugger.
Executes the script with the specified script engine.
Registers CScript.exe or WScript.exe as the default application for running scripts. If neither is specified, WScript.exe is assumed as the default.
Default. Interactive mode; allows display of user prompts and script errors Opposite of Batch mode.
Runs the specified JobID from the .wsf file.
Default. Displays a banner. Opposite of nologo.
Prevents display of an execution banner at run time. Default is logo.
Saves the current command-line options for this user.
Enables time-out: the maximum number of seconds the script can run. The default is no limit. The //T parameter prevents excessive execution of scripts by setting a timer. When
execution time exceeds the specified value, CScript interrupts the script engine using the IActiveScript::InterruptThread method and terminates the process.
Used with Windows NT and Windows 2000 to force the command line output to be in Unicode. There is no way for CScript to determine whether to output in Unicode or ANSI; it
defaults to ANSI.
Launches the program in the debugger.
Displays a brief description of and usage information for command parameters (the usage information).

2001 Microsoft Corporation. All rights reserved.


Build: Topic Version 5.6.9309.1546
Windows Script Host

What to Include to Run a Script


The information that you type when you run a script by typing its name depends on which version of Windows you are running and on the method you use to run the script.
WSH Executable File

Windows Version

Command prompt

Windows NT or 2000

Command prompt

Windows 9x or Millennium

Run command from Open box

Windows NT, 2000, 9x, or Millennium

Include
Specify the script name without the file extension. Example: myScript.
Note If you specify
the WSH executable file name, you must also include
the script's file extension. Example: cscript myScript.wsf.
Specify the script's file extension and precede the script name with the WSH
executable filename.
Example: cscript myScript.wsf
Specify the script's file extension.

See Also
Running Scripts with WScript.exe | Running Scripts with CScript.exe | Drag and Drop Support

2001 Microsoft Corporation. All rights reserved.


Build: Topic Version 5.6.9309.1546
Windows Script Host

Setting up Remote WSH


Remote WSH, which is a new technology included in WSH 5.6, provides the ability to run a script on a remote machine or machines. With Remote WSH, the script is physically copied from the local machine to the remote
machine before executing. In order to enable Remote WSH functionality, you must first set up the remote machine with the proper security settings. The steps below perform the tasks that enable Remote WSH.
Note

Both the remote and localmachines must be running Windows NT 4 SP3 or greater in order to use Remote WSH.

To enable a machine to run remote scripts


1. Install WSH V5.6 on the machine. If you are using Windows 2001 or have installed Internet Explorer 6 or greater, WSH 5.6 has already been installed.
Note

WSH 5.6 is available for download fromthe web at http://msdn.microsoft.com/scripting

2. Add yourself to the remote machine's Local Administrators group.


3. To enable Remote WSH, use Poledit.exe on the server.
Note An administrator who wants to enableRemote WSH must either acquire the Windows 2000 resource kit, or use http://msdn.microsoft.com/scripting to acquire the necessary windowsscript.adm file that
contains the WSH settings. The windowsscript.adm file must be copied to the server that sets the gapplicabel group's policies. Although it is not necessary to copy the file to the server's \WINNT\INF directory,
this is nonetheless where the default adm files are located.
Note

For more information on Poledit.exe, seethe Poledit.exe's online help system.

4. WSH should now be enabled on the machine. To test it, see Running Scripts Remotely.
See Also
Security and Windows Script Host |Running Scripts Remotely

2001 Microsoft Corporation. All rights reserved.


Build: Topic Version 5.6.9309.1546

Windows Script Host

Basic Windows Script Host Tasks


This section contains several commonly used Windows Scripting Host 5.6 scripts, which demonstrate basic functions.
Note The scripts presented inthe following tasks are virtually the same for developers using JScript or VBScript. When applicable, differences between the scripting models are noted. In addition, each task is
written in both JScript and VBScript.
In this Section

Accessing Networks
Creating an Automated Login Script
Driving Applications
Executing File Management Operations
Managing Shortcuts
Manipulating the System Registry
Running Scripts Remotely
Signing a Script
WSH and Windows Management Instrumentation (WMI)

2001 Microsoft Corporation. All rights reserved.


Build: Topic Version 5.6.9309.1546
Windows Script Host

Accessing Networks
With WSH you can easily access a network programmatically. The following tasks demonstrate some of these capabilities.
In this Section
Accessing Network Connections
Controlling Networked Printers
See Also
WSH Samples

2001 Microsoft Corporation. All rights reserved.


Build: Topic Version 5.6.9309.1546
Windows Script Host

Accessing Network Connections


The Network object enables you to access information about your network. The following scripts demonstrate how to map a network drive. In the first step, the script creates a Network Object. Next, the MapNetworkDrive
method, one of the Network object's methods, performs the mapping operation. The MapNetworkDrive method takes five arguments:

The local drive assignment (I:, for example)


The Universal Naming Convention (UNC) path to the mapped remote drive
An optional Boolean indicating whether the drive will be persistently connected
An optional user name if you want to use different credentials
An optional password for use with the alternate user name

// JScript.
var net;
net = new ActiveXObject("WScript.Network");
net.MapNetworkDrive("I:", "\\\\computer2\\public","True","jdoe","jdoepassword");
' VBScript.
Dim net
Set net = CreateObject("WScript.Network")
net.MapNetworkDrive "I:", "\\computer2\public","True","jdoe","jdoepassword"

See Also
Accessing Networks

2001 Microsoft Corporation. All rights reserved.


Build: Topic Version 5.6.9309.1546
Windows Script Host

Controlling Networked Printers


The Network object enables you to access printing devices on your network. The following scripts demonstrate the use of the Network object to control a network printer device.

Connecting to a Remote Printer


The following scripts demonstrate how to connect to a network shared printing device. In the first step, the script creates a Network Object. Next, the AddWindowsPrinterConnection method, one of the Network object's
methods, performs the connection operation. The AddWindowsPrinterConnection method takes two parameters: the name you wish to call the printer and the Universal Naming Convention (UNC) path to the printing device.
// JScript.
var net;
net = new ActiveXObject("WScript.Network");
net.AddWindowsPrinterConnection("\\\\ServerName\\PrinterName");
' VBScript.
Dim net
Set net = CreateObject("WScript.Network")
net.AddWindowsPrinterConnection "\\ServerName\PrinterName"

Setting Default Printer


The following script demonstrates how to set the desired default printing device. In the first step, the script creates a Network Object. Next, the SetDefaultPrinter method, one of the Network object's methods, performs the
operation. The SetDefaultPrinter method takes a single parameter, the name of the printer, which is either the local printer name or a remote printer name using the Universal Naming Convention (UNC) path to the printing
device.
// JScript.
var net;
net = new ActiveXObject("WScript.Network");
net.SetDefaultPrinter("\\\\ServerName\\PrinterName");
' VBScript.
Dim net
Set net = CreateObject("WScript.Network")
net.SetDefaultPrinter "\\ServerName\PrinterName"

See Also
Accessing Networks | AddWindowsPrinterConnection Method | SetDefaultPrinter Method | RemovePrinterConnection Method

2001 Microsoft Corporation. All rights reserved.


Build: Topic Version 5.6.9309.1546
Windows Script Host

Creating an Automated Login Script


With WSH you can create automated login scripts. The following example assumes that a company has two file servers (named "server1" and "server2"), and two print servers (named "printer1" and "printer2"). To balance usage
of the servers, everyone whose login name starts with A - K goes to the first file and print server, and everyone whose login name starts with L - Z goes to the second one.
Note

In Windows 9x, include a delay so user


logon takes affect.

// JScript.
var oNet, sUser, cInitial, startTime;
oNet = new ActiveXObject("WScript.Network");
// Get the user name. On Windows 98 and Windows ME, the use may not be logged
// on when the script starts running; keep checking every 1/2 a
// second until they are logged on
sUser = oNet.UserName;
startTime = new Date();
while (sUser == "")
{
var curTime = new Date();
if (curTime startTime > 30000) WScript.Quit();
WScript.Sleep(500);
sUser = oNet.UserName;
}
// Add a share for the "h" drive and the printer, based on the
// first letter of the user's name
cInitial = sUser.charAt(0).toUpperCase();
if (cInitial < "L")
{
oNet.MapNetworkDrive("h:", "\\\\server1\\users\\" + sUser);
oNet.AddWindowsPrinterConnection("\\\\printer1\\hp", "HP LaserJet 4");
}
else
{
oNet.MapNetworkDrive("h:", "\\\\server2\\users\\" + sUser);
oNet.AddWindowsPrinterConnection("\\\\printer2\\hp", "HP LaserJet 4");
}
' VBScript.
Option Explicit
Dim oNet, sUser, cInitial, startTime
' Helper object
Set oNet = CreateObject("WScript.Network")
' Get the user name. On Windows 9x, the use may not be logged
' on when the script starts running; keep checking every 1/2 a
' second until they are logged on.
sUser = oNet.UserName
startTime = Now
Do While sUser = ""
If DateDiff("s", startTime, Now) > 30 Then Wscript.Quit
Wscript.Sleep 500
sUser = oNet.UserName
Loop
' Add a share for the "h" drive and the printer, based on the
' first letter of the user's name
cInitial = UCase(Left(sUser, 1))
If (cInitial < "L") Then
oNet.MapNetworkDrive "h:", "\\server1\users\" & sUser
oNet.AddWindowsPrinterConnection "\\printer1\hp", "HP LaserJet 4"
Else
oNet.MapNetworkDrive "h:", "\\server2\users\" & sUser
oNet.AddWindowsPrinterConnection "\\printer2\hp", "HP LaserJet 4"
End If

See Also
WSH Samples

2001 Microsoft Corporation. All rights reserved.


Build: Topic Version 5.6.9309.1546
Windows Script Host

Driving Applications
With WSH you can start applications. The following scripts demonstrate some of these capabilities.

Creating a Local Server Application


Some applications, such as Microsoft Word, expose objects which can be accessed programmatically. The following script uses Word's spell checker.
// JScript.
var Word, Doc, Uncorrected, Corrected;
var wdDialogToolsSpellingAndGrammar = 828;
var wdDoNotSaveChanges = 0;

Uncorrected = "Helllo world!";


Word = new ActiveXObject("Word.Application");
Doc = Word.Documents.Add();
Word.Selection.Text = Uncorrected;
Word.Dialogs(wdDialogToolsSpellingAndGrammar).Show();
if (Word.Selection.Text.length != 1)
Corrected = Word.Selection.Text;
else
Corrected = Uncorrected;
Doc.Close(wdDoNotSaveChanges);
Word.Quit();
' VBScript.
Dim Word, Doc, Uncorrected, Corrected
Const wdDialogToolsSpellingAndGrammar = 828
Const wdDoNotSaveChanges = 0
Uncorrected = "Helllo world!"
Set Word = CreateObject("Word.Application")
Set Doc = Word.Documents.Add
Word.Selection.Text = Uncorrected
Word.Dialogs(wdDialogToolsSpellingAndGrammar).Show
If Len(Word.Selection.Text) <> 1 Then
Corrected = Word.Selection.Text
Else
Corrected = Uncorrected
End If
Doc.Close wdDoNotSaveChanges
Word.Quit

Spawning Programs with Shell.Exec Command


The Shell.Exec command provides additional capability beyond the Shell.Run method. These abilities include:

Improved environment variable passing


Ability to access the standard streams of the executable

The following VBScript sample demonstrates how to use standard streams and the Shell.Exec command to search a disk for a file name that matches a regular expression.
First, here's a small script that dumps to StdOut the full path of every file in the current directory and below:
' VBScript.
' MYDIR.VBS
Option Explicit
Dim FSO
Set FSO = CreateObject("Scripting.FileSystemObject")
DoDir FSO.GetFolder(".")
Sub DoDir(Folder)
On Error Resume Next
Dim File, SubFolder
For Each File In Folder.Files
WScript.StdOut.WriteLine File.Path
Next
For Each SubFolder in Folder.SubFolders
DoDir SubFolder
Next
End Sub

Next, this script searches StdIn for a pattern and dumps all lines that match that pattern to StdOut.
' MyGrep.VBS
Option Explicit
Dim RE, Line
If WScript.Arguments.Count = 0 Then WScript.Quit
Set RE = New RegExp
RE.IgnoreCase = True
RE.Pattern = WScript.Arguments(0)
While Not WScript.StdIn.AtEndOfStream
Line = WScript.StdIn.ReadLine
If RE.Test(Line) Then WScript.StdOut.WriteLine Line
WEnd

Together these two scripts do what we want one lists all files in a directory tree and one finds lines that match a regular expression. Now we write a third program which does two things: it uses the operating system to pipe
one program into the other, and it then pipes the result of that to its own StdOut:
// MyWhere.JS
if (WScript.Arguments.Count() == 0)
WScript.Quit();
var Pattern = WScript.Arguments(0);
var Shell = new ActiveXObject("WScript.Shell");
var Pipe = Shell.Exec("%comspec% /c \"cscript //nologo mydir.vbs | cscript //nologo mygrep.vbs " + Pattern + "\"");
while(!Pipe.StdOut.AtEndOfStream)
WScript.StdOut.WriteLine(Pipe.StdOut.ReadLine());

See Also
WSH Samples | Exec Method | Run Method

2001 Microsoft Corporation. All rights reserved.


Build: Topic Version 5.6.9309.1546
Windows Script Host

Executing File Management Operations


With WSH you can easily create, copy, move, and delete files and folders programmatically. The following tasks demonstrate these capabilities.
In this Section
Copying Files and Folders
Mapping to a Special Folders
See Also
WSH Samples

2001 Microsoft Corporation. All rights reserved.

Build: Topic Version 5.6.9309.1546


Windows Script Host

Copying Files and Folders


File system manipulation, such as copying files and folders, requires the use of the File System Object (FSO). The following scripts demonstrate the use of the FSO to copy both files and folders.

Copying Files
The following scripts demonstrate how to copy a file from one local folder to another. In the first step, the script creates a File System Object. The CopyFile method, a file system object method, performs the file copy
operation. The CopyFile method takes two parameters, the source file and the destination.
// JScript.
var FSO = WScript.CreateObject("Scripting.FileSystemObject");
FSO.CopyFile("c:\\COMPlusLog.txt", "c:\\x\\");
' VBScript.
Dim FSO
Set FSO = CreateObject("Scripting.FileSystemObject")
FSO.CopyFile "c:\COMPlusLog.txt", "c:\x\"

Copying Folders
The following script demonstrates how to copy the contents of one local folder to another folder on the local machine.
Note

The destination folder must already existfor this method to succeed. For information on how to create a directory using WSH, see CreateFolder Method.

In the first step, the script creates a File System Object. The CopyFolder method, a file system object method, performs the folder copy operation. The CopyFolder method takes two parameters, the source folder and the
destination.
// JScript.
var FSO = WScript.CreateObject("Scripting.FileSystemObject");
FSO.CopyFolder("c:\\x", "c:\\y");
' VBScript.
Dim FSO
Set FSO = CreateObject("Scripting.FileSystemObject")
FSO.CopyFolder "c:\x", "c:\y"

See Also
Executing File Management Operations | FileSystemObject | CopyFile Method | CopyFolder Method | CreateFolder Method | MoveFolder Method

2001 Microsoft Corporation. All rights reserved.


Build: Topic Version 5.6.9309.1546
Windows Script Host

Mapping to a Special Folder


Mapping special folders, such as the My Documents desktop folder, requires the use of the Shell object. The following scripts demonstrate the use of the Shell object to create a shortcut to a folder on the desktop.
// JScript.
var Shell, DesktopPath, URL;
Shell = new ActiveXObject("WScript.Shell");
DesktopPath = Shell.SpecialFolders("Desktop");
URL = Shell.CreateShortcut(DesktopPath + "\\MSDN Scripting.url");
URL.TargetPath = "HTTP://MSDN.Microsoft.com/scripting/";
URL.Save();
' VBScript.
Dim Shell, DesktopPath, URL
Set Shell = CreateObject("WScript.Shell")
DesktopPath = Shell.SpecialFolders("Desktop")
Set URL = Shell.CreateShortcut(DesktopPath & "\MSDN Scripting.URL")
URL.TargetPath = "HTTP://MSDN.Microsoft.com/scripting/"
URL.Save

See Also
Executing File Management Operations

2001 Microsoft Corporation. All rights reserved.


Build: Topic Version 5.6.9309.1546
Windows Script Host

Managing Shortcuts
With WSH you can easily create, delete, move, and copy shortcuts programmatically. The following tasks demonstrate some of these capabilities.
In this Section
Copying a Shortcut
Creating a Shortcut
Deleting a Shortcut
Moving a Shortcut
See Also
WSH Samples

2001 Microsoft Corporation. All rights reserved.

Build: Topic Version 5.6.9309.1546


Windows Script Host

Copying a Shortcut
Copying shortcuts requires the use of the File System Object (FSO). The following scripts demonstrate the use of the File System Object to copy shortcuts.
// JScript.
Shell = new ActiveXObject("WScript.Shell");
FSO = new ActiveXObject("Scripting.FileSystemObject");
DesktopPath = Shell.SpecialFolders("Desktop") + "\\MSDN Scripting url";
MyDocumentsPath = Shell.SpecialFolders("MyDocuments") + "\\"
FSO.CopyFile(DesktopPath, MyDocumentsPath);
' VBScript.
Set Shell = CreateObject("WScript.Shell")
Set FSO = CreateObject("Scripting.FileSystemObject")
DesktopPath = Shell.SpecialFolders("Desktop") + "\MSDN Scripting.url"
MyDocumentsPath = Shell.SpecialFolders("MyDocuments") + "\\"
FSO.CopyFile DesktopPath, MyDocumentsPath

See Also
Managing Shortcuts

2001 Microsoft Corporation. All rights reserved.


Build: Topic Version 5.6.9309.1546
Windows Script Host

Creating a Shortcut
Creating shortcuts requires the use of the File Shell object. The following scripts demonstrate the use of the File Shell object to create shortcuts.
// JScript.
Shell = new ActiveXObject("WScript.Shell");
DesktopPath = Shell.SpecialFolders("Desktop");
link = Shell.CreateShortcut(DesktopPath + "\\test.lnk");
link.Arguments = "1 2 3";
link.Description = "test shortcut";
link.HotKey = "CTRL+ALT+SHIFT+X";
link.IconLocation = "foo.exe,1";
link.TargetPath = "c:\\blah\\foo.exe";
link.WindowStyle = 3;
link.WorkingDirectory = "c:\\blah";
link.Save();
' VBScript.
Set Shell = CreateObject("WScript.Shell")
DesktopPath = Shell.SpecialFolders("Desktop")
Set link = Shell.CreateShortcut(DesktopPath & "\test.lnk")
link.Arguments = "1 2 3"
link.Description = "test shortcut"
link.HotKey = "CTRL+ALT+SHIFT+X"
link.IconLocation = "foo.exe,1"
link.TargetPath = "c:\blah\foo.exe"
link.WindowStyle = 3
link.WorkingDirectory = "c:\blah"
link.Save

See Also
Managing Shortcuts

2001 Microsoft Corporation. All rights reserved.


Build: Topic Version 5.6.9309.1546
Windows Script Host

Deleting a Shortcut
Deleting shortcuts requires the use of the File System Object (FSO). The following scripts demonstrate the use of the File System Object to delete shortcuts.
// JScript.
Shell = new ActiveXObject("WScript.Shell");
FSO = new ActiveXObject("Scripting.FileSystemObject");
DesktopPath = Shell.SpecialFolders("Desktop");
FSO.DeleteFile(DesktopPath + "\\test.lnk")
' VBScript.
Set Shell = CreateObject("WScript.Shell")
Set FSO = CreateObject("Scripting.FileSystemObject")
DesktopPath = Shell.SpecialFolders("Desktop")
FSO.DeleteFile DesktopPath & "\test.lnk"

See Also
Managing Shortcuts

2001 Microsoft Corporation. All rights reserved.


Build: Topic Version 5.6.9309.1546
Windows Script Host

Moving a Shortcut
Moving shortcuts requires the use of the File System Object (FSO). The following scripts demonstrate the use of the File System Object to move shortcuts.
// JScript.

Shell = new ActiveXObject("WScript.Shell");


FSO = new ActiveXObject("Scripting.FileSystemObject");
DesktopPath = Shell.SpecialFolders("Desktop") + "\\test.lnk";
MyDocumentsPath = Shell.SpecialFolders("MyDocuments") + "\\test.lnk";
FSO.MoveFile(DesktopPath, MyDocumentsPath);
' VBScript.
Set Shell = CreateObject("WScript.Shell")
Set FSO = CreateObject("Scripting.FileSystemObject")
DesktopPath = Shell.SpecialFolders("Desktop") & "\test.lnk"
MyDocumentsPath = Shell.SpecialFolders("MyDocuments") & "\test.lnk"
FSO.MoveFile DesktopPath, MyDocumentsPath

See Also
Managing Shortcuts

2001 Microsoft Corporation. All rights reserved.


Build: Topic Version 5.6.9309.1546
Windows Script Host

Manipulating the System Registry


With WSH you can manage the system registry. The following scripts demonstrate some of these capabilities.
// JScript.
Sh = new ActiveXObject("WScript.Shell");
key = "HKEY_CURRENT_USER\\"
Sh.RegWrite( key + "WSHTest\\", "testkeydefault");
Sh.RegWrite( key + "WSHTest\\string1", "testkeystring1");
Sh.RegWrite( key + "WSHTest\\string2", "testkeystring2", "REG_SZ");
Sh.RegWrite( key + "WSHTest\\string3", "testkeystring3", "REG_EXPAND_SZ");
Sh.RegWrite( key + "WSHTest\\int", 123, "REG_DWORD");
WScript.Echo( Sh.RegRead(key + "WSHTest\\"));
WScript.Echo ( Sh.RegRead(key + "WSHTest\\string1"));
WScript.Echo ( Sh.RegRead(key + "WSHTest\\string2"));
WScript.Echo ( Sh.RegRead(key + "WSHTest\\string3"));
WScript.Echo ( Sh.RegRead(key + "WSHTest\\int"));
Sh.RegDelete(key + "WSHTest\\");
' VBScript.
Set Sh = CreateObject("WScript.Shell")
key = "HKEY_CURRENT_USER\"
Sh.RegWrite key & "WSHTest\", "testkeydefault"
Sh.RegWrite key & "WSHTest\string1", "testkeystring1"
Sh.RegWrite key & "WSHTest\string2", "testkeystring2", "REG_SZ"
Sh.RegWrite key & "WSHTest\string3", "testkeystring3", "REG_EXPAND_SZ"
Sh.RegWrite key & "WSHTest\int", 123, "REG_DWORD"
WScript.Echo Sh.RegRead(key & "WSHTest\")
WScript.Echo Sh.RegRead(key & "WSHTest\string1")
WScript.Echo Sh.RegRead(key & "WSHTest\string2")
WScript.Echo Sh.RegRead(key & "WSHTest\string3")
WScript.Echo Sh.RegRead(key & "WSHTest\int")
Sh.RegDelete key & "WSHTest\"

See Also
WSH Samples

2001 Microsoft Corporation. All rights reserved.


Build: Topic Version 5.6.9309.1546
Windows Script Host

Running Scripts Remotely


WSH 5.6 can run scripts that reside on remote systems. The following scripts demonstrate this capability. These scripts make the assumption that the files are located on a local machine directory called "c:\wsh5.6"; change the
local path and the remote machine name as necessary.
After initially running RemoteTest.WSF on the local machine, there may be a small pause as DCOM verifies your identity. After you see the "Done" message, a file named "c:\beenhere.txt" on the remote machine indicates the
time that you executed the command (from the remote computer's clock).
// JScript.
RemoteTest.WSF
------------------------------<package>
<job>
<script language="JScript">
var oController = new ActiveXObject("WSHController");
var oProcess = oController.CreateScript("c:\\wsh5.6\\beenhere.wsf", "remmachine");
oProcess.Execute();
while (oProcess.Status != 2) WScript.Sleep(100);
WScript.Echo("Done");
</script>
</job>
</package>
------------------------------BeenHere.WSF
------------------------------<package>
<job>
<script language="JScript">
var fso = new ActiveXObject("Scripting.FileSystemObject");
var fout = fso.CreateTextFile("c:\\beenhere.txt", true);
fout.WriteLine(new Date);
fout.Close();
</script>
</job>
</package>
------------------------------' VBScript.
RemoteTest.WSF
------------------------------<package>
<job>
<script language="VBScript">
set oController = CreateObject("WSHController")
set oProcess = oController.CreateScript("c:\wsh5.6\beenhere.wsf", "remmachine")
oProcess.Execute

While oProcess.Status <> 2


WScript.Sleep 100
WEnd
WScript.Echo "Done"
</script>
</job>
</package>
------------------------------BeenHere.WSF
------------------------------<package>
<job>
<script language="VBScript">
set fso = CreateObject("Scripting.FileSystemObject")
set fout = fso.CreateTextFile("c:\beenhere.txt", true)
fout.WriteLine Now
fout.Close
</script>
</job>
</package>

See Also
WSH Samples | Setting up Remote WSH | WshRemote Object

2001 Microsoft Corporation. All rights reserved.


Build: Topic Version 5.6.9309.1546
Windows Script Host

Signing a Script
The following scripts demonstrate the creation of a signature, which is used in a verification process. The script uses the Signer Object and the SignFile method to create a digital signature.
// JScript.
<job>
<runtime>
<named name="file" helpstring="the file to sign" required="true" type="string"/>
<named name="cert" helpstring="the name of the signing certificate" required="true" type="string"/>
<named name="store" helpstring="the name of the certificate store" required="false" type="string"/>
</runtime>
<script language="JScript">
var Signer, File, Cert, Store;
if (!(WScript.Arguments.Named.Exists("cert") && WScript.Arguments.Named.Exists("file")))
{
WScript.Arguments.ShowUsage();
WScript.Quit();
}
Signer = new ActiveXObject("Scripting.Signer");
File = WScript.Arguments.Named("file");
Cert = WScript.Arguments.Named("cert");
Store = WScript.Arguments.Named("store");
Signer.SignFile(File, Cert, Store);
</script>
</job>
'VBScript
<job>
<runtime>
<named name="file" helpstring="the file to sign" required="true" type="string"/>
<named name="cert" helpstring="the name of the signing certificate" required="true" type="string"/>
<named name="store" helpstring="the name of the certificate store" required="false" type="string"/>
</runtime>
<script language="VBScript">
Dim Signer, File, Cert, Store
If Not (WScript.Arguments.Named.Exists("cert")) And WScript.Arguments.Named.Exists("file")) Then
WScript.Arguments.ShowUsage
WScript.Quit
End If
Set Signer = CreateObject("Scripting.Signer")
File = WScript.Arguments.Named("file")
Cert = WScript.Arguments.Named("cert")
Store = WScript.Arguments.Named("store")
Signer.SignFile File, Cert, Store
</script>
</job>

See Also
WSH Samples | Verifying a Script | Signing a Script

2001 Microsoft Corporation. All rights reserved.


Build: Topic Version 5.6.9309.1546
Windows Script Host

WSH and Windows Management Instrumentation (WMI)


With WSH you can easily use Windows Management Instrumentation (WMI). The following scripts demonstrate using WSH and WMI to retrieve a user's logon time via ADSI.
Note

For more information on WMI, see the WMI


SDK at (http://msdn.microsoft.com).

// JScript.
LoginProfiles = GetObject("winmgmts:").InstancesOf ("Win32_NetworkLoginProfile");
for(e = new Enumerator(LoginProfiles) ; !e.atEnd() ; e.moveNext())
{
Profile = e.item();
WScript.Echo(Profile.Name);
WScript.Echo(Profile.LastLogon);
}
' VBScript.
Set LoginProfiles = GetObject("winmgmts:").InstancesOf ("Win32_NetworkLoginProfile")
for each Profile in LoginProfiles
WScript.Echo Profile.Name
WScript.Echo Profile.LastLogon
next

See Also

Basic Windows Script Host Tasks

2001 Microsoft Corporation. All rights reserved.


Build: Topic Version 5.6.9309.1546
Windows Script Host

WSH Walkthrough
The following walkthrough describes how a typical Network Administrator or other IT professional might use WSH 5.6 to create procedures that accomplish useful tasks.
Note

The walkthrough is presented in VBScript.The process for creating these scripts is nearly the same for developers using VBScript or JScript.

During the course of this walkthrough, you will perform the following activities:

Create a script that creates a common share on several remote machines and populate it with files.
Create a script that creates a common Printing Device connection on several remote machines and establish it as the default printing device.

To complete the walkthrough, all remote machines must be properly configured to enable Remote WSH. For more information on enabling these security settings, see Setting up Remote WSH.
Note

The following code is from the sample


included in this documentation. To view the entire sample, see WSH Network Administrator Sample Script.

Create Variables and Constants


To create the necessary variables and constants
1. In your text-scripting editor, enter the variables.
Dim
Dim
Dim
Dim
Dim
Dim
Dim
Dim
Dim

FSO
Services
SecDescClass
SecDesc
Trustee
ACE
Share
InParam
Network

2. In your text-scripting editor, enter the constants, changing the values to reflect the UNC names and paths applicable to your network environment.
Const
Const
Const
Const

FolderName = "C:\Public"
AdminServer = "\\AdminMachine"
ShareName = "Pubs"
PrinterShare = "\\CorpPrinters\PrinterShare"

Connecting to a printer and setting it as default


To connect the machine to a common printing device

In your text-scripting editor, enter the code that creates a printing device. This code uses the Network variable and PrinterShare constant initialized in the previous step.
Set Network = CreateObject("Wscript.Network")
Network.AddWindowsPrinterConnection PrinterShare

To set the machines default printing device

In your text-scripting editor, enter the code that sets the default printing device. This code uses the Network variable and PrinterShare constant initialized in the first step.
Network.SetDefaultPrinter PrinterShare

Creating a common share, copying files to it, and sharing it


To create a common share on the machine

In your text-scripting editor, enter the code that creates a File System Object (FSO) and creates a folder. The script verifies the existence of the folder. If the folder does not exist, the script creates it. This code uses the
FSO variable and the FolderName constant initialized in the first step.
Set FSO = CreateObject("Scripting.FileSystemObject")
If Not FSO.FolderExists(FolderName) Then
FSO.CreateFolder(FolderName)
End If

To copy files to the newly created folder

In your text-scripting editor, enter the code that creates a File System Object (FSO) and copies files from your local machine to the remote machine. This code uses the FSO variable and the FolderName constant
initialized in the first step.
Call FSO.CopyFile(AdminServer & "\Public\Images\*.*", FolderName)

To establish the newly created folder as a share with WMI

In your text-scripting editor, enter the code that creates a share using Windows Management Instrumentation (WMI). The share is established on the folder generated above. The script first connects to WMI. Next, it sets
the security impersonation level and the Windows NT privilege that lets you set Discretionary Access Control Lists (DACLs) and Security Access Control Lists (SACLs). Next, it creates a new security descriptor and sets
up a couple of Access Control Entries (ACEs) for the new share. Finally, it creates a new share with the new security descriptor. This code uses the Services, SecDescClass, SecDesc, Trustee, ACE, Share, and InParam
variables, and the FolderName, AdminShare, and ShareName constants initialized in the first step.
Note WMI is a powerful,sophisticated technology based on Web Based Enterprise Management (WBEM). WMI is primarily used for accessing and instrumenting management information in an enterprise
environment. For more information on WMI, see Microsoft Windows Management Instrumentation: Background and Overview at (http://msdn.microsoft.com/library/default.asp?
URL=/library/backgrnd/html/wmixwdm.htm).
Set Services = GetObject("WINMGMTS:{impersonationLevel=impersonate,(Security)}!" & AdminServer & "\ROOT\CIMV2")
Set SecDescClass = Services.Get("Win32_SecurityDescriptor")
Set SecDesc = SecDescClass.SpawnInstance_()
Set Trustee = Services.Get("Win32_Trustee").SpawnInstance_
Trustee.Domain = Null
Trustee.Name = "EVERYONE"
Trustee.Properties_.Item("SID") = Array(1, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0)
Set ACE = Services.Get("Win32_Ace").SpawnInstance_
ACE.Properties_.Item("AccessMask") = 2032127
ACE.Properties_.Item("AceFlags") = 3
ACE.Properties_.Item("AceType") = 0
ACE.Properties_.Item("Trustee") = Trustee
SecDesc.Properties_.Item("DACL") = Array(ACE)
Set Share = Services.Get("Win32_Share")
Set InParam = Share.Methods_("Create").InParameters.SpawnInstance_()
InParam.Properties_.Item("Access") = SecDesc
InParam.Properties_.Item("Description") = "Public Share"
InParam.Properties_.Item("Name") = ShareName

InParam.Properties_.Item("Path") = FolderName
InParam.Properties_.Item("Type") = 0
Share.ExecMethod_("Create", InParam)

Running the Completed Script


The sample included in this documentation contains a complete, executable script with all of the functionality above. See WSH Network Administrator Sample Script.
Before running the script, ensure that all remote machines have been properly configured to run remote scripts. This is accomplished with Poledit.exe on the server. For more information, see Setting up Remote WSH.
When running remote WSH, the script is copied to the remote machines. Once the remote machine's security settings have been verified and the script is successfully copied, a return indicates success or failure. If successful, the
script is then executed on the remote machines. For more information on running a remote WSH script, see Running Scripts Remotely.
See Also
Setting up Remote WSH | Accessing Networks | Running Scripts Remotely

2001 Microsoft Corporation. All rights reserved.


Build: Topic Version 5.6.9309.1546
Windows Script Host

WSH Network Administrator Sample Script


This WSH network sample demonstrates how a typical network administrator may use a script on several remote machines on the network. The sample script performs useful administrative tasks including:
Connecting the machines to a network printing device
Setting the newly connected printing device as the default printer
Creating a common public folder on the machines
Copying files to the newly created folder
Establishing the newly created folder as a share using Windows Management Instrumentation (WMI).

Note WMI is a powerful, sophisticated


technology based on Web Based Enterprise Management (WBEM). WMI is primarily used for accessing and instrumenting management information in an enterprise
environment. For more information on WMI, see Microsoft Windows Management Instrumentation: Background and Overview at (http://msdn.microsoft.com/library/default.asp?
URL=/library/backgrnd/html/wmixwdm.htm).
The Administrator must establish the necessary security settings on the remote machines. For more information, see Setting up Remote WSH. Next the administrator must copy and paste the sample into the scripting editor and
change the constants to reflect the corresponding network paths and machine names. Finally the administrator can run the script.
To run this sample
1.
2.
3.
4.

Establish the necessary security settings on the remote machines.


Copy the AdminScript.vbs script below into your scripting text editor.
Change the constants to reflect your network paths and machine names.
Replace remmachine with the applicable remote machine name and run the script:
var oController = new ActiveXObject"WSHController"
var oProcess = oController.CreateScript "c:\MyLocalDir\\AdminScript.vbs", "remmachine"
oProcess.Execute()
while (oProcess.Status != 2)
WScript.Sleep(100)
WScript.Echo"Done"

AdminScript.vbs Sample
'
'
'
'
'
'
'

Remote WSH Admin Sample

AdminScript.vbs

'
'
'
'

Note that in the interests of keeping this example code small, error
handling has been omitted. Actual production code should use
appropriate error handling as many of these operations could fail;
the disks could run out of space, for instance.

This sample code does a few common administrative tasks which a


network administrator might want to do to a number of the machines
on his or her network: it creates a public directory, populates
it with some files and shares the directory out. It also sets
up the machines default printer connection.

Option Explicit
Dim
Dim
Dim
Dim
Dim
Dim
Dim
Dim
Dim

FSO
Services
SecDescClass
SecDesc
Trustee
ACE
Share
InParam
Network

Const
Const
Const
Const

FolderName = "C:\Public"
AdminServer = "\\AdminMachine"
ShareName = "Pubs"
PrinterShare = "\\CorpPrinters\PrinterShare"

' First we add a printer to this machine and make it the default.
Set Network = CreateObject("Wscript.Network")
Network.AddWindowsPrinterConnection PrinterShare
Network.SetDefaultPrinter PrinterShare
' Next we create a folder and populate it with some files.
Set FSO = CreateObject("Scripting.FileSystemObject")
If Not FSO.FolderExists(FolderName) Then
FSO.CreateFolder(FolderName)
End If
Call FSO.CopyFile(AdminServer & "\Public\Images\*.*", FolderName)
' Make the folder into a share using WMI
' See the WMI SDK for information on how this code works.
Set Services = GetObject("WINMGMTS:{impersonationLevel=impersonate,(Security)}!" & AdminServer & "\ROOT\CIMV2")
Set SecDescClass = Services.Get("Win32_SecurityDescriptor")
Set SecDesc = SecDescClass.SpawnInstance_()
Set Trustee = Services.Get("Win32_Trustee").SpawnInstance_
Trustee.Domain = Null
Trustee.Name = "EVERYONE"
Trustee.Properties_.Item("SID") = Array(1, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0)
Set ACE = Services.Get("Win32_Ace").SpawnInstance_
ACE.Properties_.Item("AccessMask") = 2032127
ACE.Properties_.Item("AceFlags") = 3
ACE.Properties_.Item("AceType") = 0

ACE.Properties_.Item("Trustee") = Trustee
SecDesc.Properties_.Item("DACL") = Array(ACE)
Set Share = Services.Get("Win32_Share")
Set InParam = Share.Methods_("Create").InParameters.SpawnInstance_()
InParam.Properties_.Item("Access") = SecDesc
InParam.Properties_.Item("Description") = "Public Share"
InParam.Properties_.Item("Name") = ShareName
InParam.Properties_.Item("Path") = FolderName
InParam.Properties_.Item("Type") = 0
Share.ExecMethod_("Create", InParam)
' And we're done.

See Also
WSH Walkthrough | Accessing Networks | Setting up Remote WSH | Running Scripts Remotely

2001 Microsoft Corporation. All rights reserved.


Build: Topic Version 5.6.9309.1546
Windows Script Host

Security and Windows Script Host


Windows Script Host, which is a flexible tool for automating Windows, can be dangerous in the hands of someone who is bent on wreaking havoc.
To prevent abuse of Windows Script Host without stifling its power, Windows Script Host 5.6 employs a new security model.
Script users can now verify the authenticity of a script before running it. Script developers can sign their scripts to prevent unauthorized modifications. Administrators can enforce strict policies that determine which users have
privileges to run scripts locally or remotely.
In this Section
CryptoAPI Tools
Signing a Script
Signature Verification Policy
Verifying a Script
Software Restriction Policies

2001 Microsoft Corporation. All rights reserved.


Build: Topic Version 5.6.9309.1546
Windows Script Host

CryptoAPI Tools
The CryptoAPI Tools are used to create and verify digital signatures in *.exe, *.cab, *.dll, *.ocx, and script (*js, *.vbs, and *.wsf) files.
CryptoAPI Tools are used to digitally sign files to be used with Microsoft Authenticode, and to view and manage certificates, certificate revocation lists (CRLs), and certificate trust lists (CTLs). For more information on
CrptoAPI Tools, see the CryptoAPI Start Page at (http://msdn.microsoft.com/library/psdk/crypto/portalapi_3351.htm?RLD=290).
See Also
Security and Windows Script Host | Signing a Script | Verifying a Script | Signature Verification Policy

2001 Microsoft Corporation. All rights reserved.


Build: Topic Version 5.6.9309.1546
Windows Script Host

Signing a Script
Signing a script writes a digital signature block of comments in a script. The signature, which contains encoded information about the identity of the author, also encapsulates encoded information about the script itself.
Consequently, any attempt to change the script invalidates the signature.
Script signing is programmatically accomplished with the Scripting.Signer object's SignFile method.
<job>
<runtime>
<named name="file" helpstring="the file to sign" required="true" type="string"/>
<named name="cert" helpstring="the name of the signing certificate" required="true" type="string"/>
<named name="store" helpstring="the name of the certificate store" required="false" type="string"/>
</runtime>
<script language="JScript">
var Signer, File, Cert, Store;
if (!(WScript.Arguments.Named.Exists("cert") && WScript.Arguments.Named.Exists("file")))
{
WScript.Arguments.ShowUsage();
WScript.Quit();
}
Signer = new ActiveXObject("Scripting.Signer");
File = WScript.Arguments.Named("file");
Cert = WScript.Arguments.Named("cert");
if (WScript.Arguments.Named.Exists("store"))
{
Store = WScript.Arguments.Named("store");
}
else
{
Store = "";
}
Signer.SignFile(File, Cert, Store);
</script>
</job>

Note

In order to sign a script, you must have valid


a
certificate. Ask your Administrator about your certification policy or contact a commercial certification authority.

See Also
Security and Windows Script Host | Verifying a Script | Signature Verification Policy | WinTrust | Signing a Script

2001 Microsoft Corporation. All rights reserved.


Build: Topic Version 5.6.9309.1546
Windows Script Host

Software Restriction Policies


Software Restriction Policies are trust policies, which are regulations set by an administrator to restrict scripts that are not fully trusted from performing unauthorized actions within the operating system.
The following three criteria are used by Software Restriction Policies in determining a trust level:

Any signature information in the script


The path from which the script is running
File content

Software Restriction Policies define the following default containers:

Domain Administrator
Machine Administrator
Machine User
Guest User
Denied

Additionally, you can define your own custom container and set your own policies.
See Also
Security and Windows Script Host

2001 Microsoft Corporation. All rights reserved.


Build: Topic Version 5.6.9309.1546
Windows Script Host

Signature Verification Policy


In WSH, administrators have the choice to turn signature verification either on or off. If an administrator turns signature verification on, then the machine will only run scripts signed by trusted authorities. With signature
verification turned on, there are two possible scenarios:

If the trust can't be determined, then the user is prompted to confirm that the script should run.
If the trust can't be determined, then the script does not run.

If an administrator turns signature verification off, the machine permits users to run any script.
In Windows 2000, the signature verification policy is set through the Local Security Policy editor. For more information on the Local Security Policy Editor and WSH settings, see the online Windows help system.
The signature verification policy registry key is located in the following hive:
\HKEY_CURRENT_USER\SOFTWARE\Microsoft\Windows Script Host\Settings\TrustPolicy
The key is set to one of the following REG_DWORD values:

0 Run all scripts


1 Prompt user if script is untrusted
2 Run only trusted scripts

See Also
Security and Windows Script Host | Signing a Script | Verifying a Script | WinTrust

2001 Microsoft Corporation. All rights reserved.


Build: Topic Version 5.6.9309.1546
Windows Script Host

Verifying a Script
Verifying a script determines whether the script that you are about to run is from a trusted source. It also allows you to confirm the integrity of the script. WSH verifies scripts before it attempts to run them, but you may have
your own reason to verify a script.
Script verification is accomplished programmatically with the Signer object's VerifyFile method.
The VerifyFile method:

Verifies the validity of the signature.


Verifies that the signature belongs to a person who is trusted in your Trusted Publishers List.
Verifies that the script has not been changed since it was signed.
Note

Although theVerifyFile method programmatically confirms the digital signature, you should always ensure that you really trust the trusted roots in the Trusted Publishers List.

See Also
Security and Windows Script Host | Signing a Script | Signature Verification Policy | WinTrust

2001 Microsoft Corporation. All rights reserved.

Build: Topic Version 5.6.9309.1546


Windows Script Host

Reference
In this Section
XML Elements
List of WSH XML Elements.
Objects
List of WSH Objects.
Properties
List of WSH Properties.
Methods
List of WSH Methods.
Events
List of WSH Events
Error Messages
List of WSH Error Messages.
Related Sections
WSH Basics
Learn the basics of WSH.

2001 Microsoft Corporation. All rights reserved.


Build: Topic Version 5.6.9309.1546
Windows Script Host

XML Elements
In this Section
<?job?> Element
XML processing instruction that specifies attributes for error handling.
<?XML?> Element
Indicates that a file should be parsed as XML.
<description> Element
Marks the descriptive text that appears when the user runs ShowUsage() or runs the script with the /? command line switch.
<example> Element
Makes your script self documenting.
<job> Element
Marks the beginning and the end of a job within a Windows Script file (*.wsf).
<named> Element
Marks a particular named argument to the script.
<object> Element
XML element that is used in Windows Script component files and that defines objects that can be referenced by script.
<package> Element
Encloses multiple job definitions in a Windows Script Host control (.wsf) file.
<reference> Element
XML element that includes a reference to an external type library.
<resource> Element
XML element that isolates textual or numeric data that should not be hard-coded into a script.
<runtime> Element
Groups together the set of run-time arguments for a script.
<script> Element
XML element that contains script to define the behavior of a Windows Script component.
Related Sections
WSH Reference
List of elements that make up WSH Reference.
WSH Basics
Learn the basics of WSH.

2001 Microsoft Corporation. All rights reserved.


Build: Topic Version 5.6.9309.1546
Windows Script Host

<?job?> Element
Specifies attributes for error handling.
<?job error="flag" debug="flag" ?>

Arguments
error
A Boolean value. False is the default value for all attributes. Set to true to allow error messages for syntax or run-time errors in the Windows Script (.wsf) file.
Debug
A Boolean value. False is the default value for all attributes. Set to true to enable debugging. If debugging is not enabled, you will be unable to launch the script debugger for a Windows Script file.
Remarks
Although most Windows Script files normally run silently during production, you might find it useful to be notified of errors in the Windows Script (.wsf) file as you are developing it.
Example
The following example incorporates two jobs into one .wsf file that uses two different scripting languages.
<package>
<job id="DoneInVBS">
<?job debug="true"?>
<script language="VBScript">
WScript.Echo "This is VBScript"
</script>

</job>
<job id="DoneInJS">
<?job debug="true"?>
<script language="JScript">
WScript.Echo("This is JScript");
</script>
</job>
</package>

See Also
<runtime> Element | <named> Element | <description> Element | <example> Element | <object> Element | <package> Element | <resource> Element | <?XML?> Element

2001 Microsoft Corporation. All rights reserved.


Build: Topic Version 5.6.9309.1546
Windows Script Host

<?XML?> Element
Indicates that a file should be parsed as XML.
<?XML version="version" [standalone="DTDflag"] ?>

Arguments
version
A string in the form n.n specifying the XML level of the file. Use the value 1.0.
DTDflag
Optional. Boolean value indicating whether the XML file includes a reference to an external Document Type Definition (DTD). Script component XML files do not include such a reference, so the value for this attribute is
always "yes."
Remarks
This declaration must be the first element in the file and cannot be preceded by any blank lines.
The existence of this declaration puts the script component compiler into strict XML mode, where element types and attribute names are case-sensitive, attribute values are enclosed in single or double quotation marks, and all
elements are parsed. If the declaration is not included, the compiler allows syntax that is less strict.
You should include this declaration and follow XML conventions if your script component file will be edited in an editor that supports XML.
Example
The following example demonstrates the use of the <?XML?> Element:
<?XML version="1.0" standalone="yes" ?>

See Also
<runtime> Element | <named> Element | <description> Element | <example> Element | <object> Element | <package> Element | <resource> Element | <?job?> Element

2001 Microsoft Corporation. All rights reserved.


Build: Topic Version 5.6.9309.1546
Windows Script Host

<description> Element
Marks the descriptive text that is displayed when the ShowUsage method is executed or when the script is run with the /? command line switch.
<description>
This section describes the script
</description>

Remarks
Your description can be more than one line long.
Do not include quotes in your description if you do not want them to appear in the usage. All text between the description tags appears in the usage listing. This includes, among others, tabs, new lines, and special characters.
The <description> element is similar to the <example> element, except it appears at the start of the usage, whereas the <example> element appears at the end.
Example
The following script demonstrates the use of the <description> Element:
<runtime>
<description>
This script reboots a server
</description>
<!--...etc...-->
</runtime>

See Also
ShowUsage Method | <runtime> Element | <named> Element | <unnamed> Element | <example> Element

2001 Microsoft Corporation. All rights reserved.


Build: Topic Version 5.6.9309.1546
Windows Script Host

<example> Element
Provides an example of usage for the job.

<example>
Example text
</example>

Remarks
The <example> element is enclosed within the <runtime> element.
Example
The following script demonstrates the use of the <example> Element:
<job>
<runtime>
<description>This script reboots a server</description>
<named
name = "Server"
helpstring = "Server to run the script on"
type = "string"
required = "true"
/>
<example>Example: reboot.wsf /Server:scripting</example>
</runtime>
</job>

Everything between <example> and </example> tags gets picked up, including new lines and extra white space. Calling the ShowUsage method from this script results in the following output:
This script reboots a server
Usage: reboot.wsf /server:value
Options:
server : Server to run the script on
Example:
reboot.wsf /server:scripting
See Also
ShowUsage Method

2001 Microsoft Corporation. All rights reserved.


Build: Topic Version 5.6.9309.1546
Windows Script Host

<job> Element
Marks the beginning and the end of a job within a Windows Script file (*.wsf).
<job [id=JobID]>
job code
</job>

Arguments
JobID
Optional. Uniquely identifies the job within the scope of the Windows Script file.
Remarks
Each jobID within a Windows Script file must be unique.
Each script within a set of job tags is executed in sequence, from top to bottom.
A job contains one or more script blocks. A script block is any script code between a set of <script> tags. A script block can contain several scripts, and each script can be in a different scripting language.
To run a specific job or to run multiple jobs, use the //Job switch. If you specify more than one job, the jobs are executed in sequential order. (This is shown in the example below.). If you do not specify a job, only the first job is
run. If you have two or more jobs in your Windows Script file, they must be enclosed in a <package> tag.
Example
The following script example is a Windows Script file called myScript.wsf. This file contains two separate jobs, each written in a different scripting language. The first job, written in VBScript, is given the identifier
DoneInVBS. The second job, written in JScript, is given the identifier DoneInJS.
<package>
<job id="DoneInVBS">
<?job debug="true"?>
<script language="VBScript">
WScript.Echo "This is VBScript"
</script>
</job>
<job id="DoneInJS">
<?job debug="true"?>
<script language="JScript">
WScript.Echo("This is JScript");
</script>
</job>
</package>

To run the second job in the Windows Script file, myScript.wsf, type the following at the command prompt.
cscript myScript.wsf //job:DoneInJS

To run both jobs in myScript.wsf, type the following at the command prompt.
cscript myScript.wsf //job:DoneInVBS //job:DoneInJS

See Also
ShowUsage Method | <runtime> Element | <named> Element | <unnamed> Element | <description> Element | <example> Element

2001 Microsoft Corporation. All rights reserved.

Build: Topic Version 5.6.9309.1546


Windows Script Host

<named> Element
Describes a named argument for the script.
<named
name = namedname
helpstring = helpstring
type = "string|boolean|simple"
required = boolean
/>

Arguments
name
String that represents the name of the argument you are describing. Defines the argument at the command line and in the script.
helpstring
String that represents the help description for the argument. The WSH runtime provides the help description using the ShowUsage method or the /? argument.
type
Optional. Describes the type of argument, which defines how the argument will be parsed from the command line. The default value is simple.
required
Optional. A Boolean value that indicates whether an argument is required or not. Affects the display of the usage only.
Remarks
The <named> element is contained by (enclosed within) a set of runtime tags.
An argument with the name server would provide a /server argument at the command line as well as an argument named server in the WSHNamed arguments collection.
If the type is string, the argument is a string. The argument is passed to the script as /named:stringvalue.
If the type is Boolean, the argument is Boolean. The argument is passed to the script as /named+ to turn it on, or /named- to turn it off.
If the type is simple, the argument takes no additional value and is passed as just the name, /named.
Example
The following script demonstrates the use of the <named> Element:
<job>
<runtime>
<named
name="server"
helpstring="Server to access"
type="string"
required="true"
/>
<named
name="user"
helpstring="User account to use on server. Default is current account."
type="string"
required="false"
/>
<named
name="enable"
helpstring="If true (+), enables the action. A minus(-) disables."
type="boolean"
required="true"
/>
<named
name="verbose"
helpstring="If specified, output will be verbose."
type="boolean"
required="false"
/>
</runtime>
<script language="JScript">
WScript.Arguments.ShowUsage();
</script>
</job>
This will produce the following output when usage is shown:
Usage: example.wsf /server:value [/user:value] /enable[+|-] [/verbose]
Options:
server
user
enable
verbose

:
:
:
:

Server to access
User account to use on server. Default is current account.
If true (+), enables the action. A minus(-) disables.
If specified, output will be verbose.

See also
ShowUsage Method | <runtime> Element | <unnamed> Element | <description> Element | <example> Element

2001 Microsoft Corporation. All rights reserved.


Build: Topic Version 5.6.9309.1546
Windows Script Host

<object> Element
Defines objects in Windows Script (.wsf) files that can be referenced by a script.
<object id="objID" [classid="clsid:GUID" | progid="progID"] />

Arguments
objID
Required. A name that references the object in your script. Object ID values must begin with a letter and can include letters, digits, and underscores (_). The object ID must be unique throughout the scope of the Windows
Script file.
GUID
Optional. The class ID (GUID) of the object.
progID
Optional. Program ID of the object, which can be specified as an alternative to the class ID.

Remarks
The <object> element provides a way to expose objects globally for use in scripting within the Windows Script file without using functions such as CreateObject(). Using an <object> element makes the object available with
global scope and enables scripting tools to provide statement completion for the object's members.
You must specify either a classid or a progid.
Example
<job>
<obect id="fso" progid="Scripting.FileSystemObject"/>
<script language="Jscript">
var a = fso.CreateTextFile("c:\\testfile.txt", true);
a.WriteLine("This is a test.");
a.Close();
</script>
</job>

See Also
<runtime> Element | <named> Element | <description> Element | <example> Element | <package> Element

2001 Microsoft Corporation. All rights reserved.


Build: Topic Version 5.6.9309.1546
Windows Script Host

<package> Element
Encloses multiple job definitions in a Windows Script (.wsf) file.
<package>
code for one or more jobs
</package>

Remarks
The <package> element is optional when a .wsf file contains only one job.
Example
The following example incorporates two jobs into one .wsf file that uses two different scripting languages:
<package>
<job id="DoneInVBS">
<?job debug="true"?>
<script language="VBScript">
WScript.Echo "This is VBScript"
</script>
</job>
<job id="DoneInJS">
<?job debug="true"?>
<script language="JScript">
WScript.Echo("This is JScript");
</script>
</job>
</package>

See Also
<runtime> Element | <named> Element | <description> Element | <example> Element | <object> Element

2001 Microsoft Corporation. All rights reserved.


Build: Topic Version 5.6.9309.1546
Windows Script Host

<reference> Element
Includes a reference to an external type library.
<reference [object="progID"|guid="typelibGUID"] [version="version"] />

Arguments
progID
Program ID from which the type library can be derived. It can include either a version number (for example, ADO.Recordset.2.0), the explicit program ID of a type library, or the program ID of the executable (such as
a .DLL) that incorporates the type library. If you use the object attribute, you do not need to specify a version attribute because the version can be inferred from the program ID. If the object attribute is specified, you
cannot also specify a GUID attribute.
typelibGUID
The GUID of the type library to reference. If the GUID attribute is specified, you cannot also specify an object attribute.
version
Optional. Version number of the type library to use. It must be in the form <major version>[.<minor version>]. If a version is not specified, the default version is 1.0. If the object attribute is used to specify the type library
and the version is not specified, the version is derived from the registry key for the specified program ID. If none can be found, the default is 1.0.
Remarks
Referencing a type library in your Windows Script (.wsf) file enables you to use constants defined in the type library in your scripts. The <reference> element looks up and makes available the type library associated with a
specific program ID or type library name. Type library information can be available in .tlb, .olb, or .dll files.
See Also
<runtime> Element | <named> Element | <description> Element | <example> Element | <object> Element | <package> Element

2001 Microsoft Corporation. All rights reserved.


Build: Topic Version 5.6.9309.1546

Windows Script Host

<resource> Element
Isolates textual or numeric data that should not be hard-coded into a script.
<resource id="resourceID">
text or number
</resource>

Arguments
resourceID
Unique identifier for the resource within the script.
Remarks
The <resource> element allows you to isolate strings or numbers in your Windows Script (.wsf) file that you want to reference in your scripts. For example, resource elements are typically used to maintain strings that may be
localized into other languages.
To get the value of a resource, call the getResource method, passing it the ID of the resource you want to use.
Everything within the elements gets used including white space (tabs, new lines, etc.).
Example
The following code defines a resource (errNonNumeric) and returns its value if the variable upperBound is not numeric.
<resource id="errNonNumeric">
Non-numeric value passed
</resource>
<script language="VBScript">
<![CDATA[
Function getRandomNumber(upperBound)
If IsNumeric(upperBound) Then
getRandomNumber = CInt(upperBound * Rnd + 1)
Else
getRandomNumber=getResource("errNonNumeric")
End If
End Function
]]>
</script>

See Also
<runtime> Element | <named> Element | <description> Element | <example> Element | <object> Element | <package> Element | getResource Method

2001 Microsoft Corporation. All rights reserved.


Build: Topic Version 5.6.9309.1546
Windows Script Host

<runtime> Element
Groups together the set of run-time arguments for a script.
<runtime>
<named attributes etc. />
<unnamed attributes etc. />
<example>Example Text</example>

</runtime>

Remarks
The ShowUsage method uses the information enclosed by the <runtime> element to display the runtime parameters for a script.
Since the <runtime> element is enclosed within a set of job tags, the defined run-time arguments apply to that job only.
Note With version 5.6, the dataenclosed by the <runtime> element is used only for self-documentation and to format the data displayed by ShowUsage. The <runtime> element does not enforce the values set for
the arguments it contains (i.e. a "required" argument that is missing from the command line does not cause an error). If the <runtime> element is included in a .wsf file, then running the script with the "/?" argument
will show the usage and quit.
Example
The following script demonstrates the use of the <runtime> Element:
<job>
<runtime>
<named
name="server"
helpstring="The server to run the script on"
type="string"
required="true"
/>
</runtime>
<script language="JScript">
if (!WScript.Arguments.Named.Exists("server"))
{
WScript.Arguments.ShowUsage();
}
// ... some script here
</script>
</job>

See Also
ShowUsage Method | <named> Element | <unnamed> Element | <description> Element | <example> Element

2001 Microsoft Corporation. All rights reserved.


Build: Topic Version 5.6.9309.1546
Windows Script Host

<script> Element
Contains script that defines the behavior of a Windows Script (.wsf) file.
<script language="language" [src="strFile"]>
script here
</script>

Arguments
language
The name of the scripting language, such as VBScript or JScript, used in the script block.
strFile
The name of the script file to include into the script block.
Remarks
If XML validation is not enabled, the XML parser ignores all lines inside the <script> element. However, if XML validation is enabled by including the <?XML?> element at the top of the Windows Script (.wsf) file, the XML
parser can misinterpret greater than (>), less than (<), and other symbols used in script as XML delimiters.
If you are creating a file that conforms closely to XML syntax, you must ensure that characters in your script element are not treated as XML-reserved characters. To do this, enclose the actual script in a <![CDATA[ ... ]]>
section. This applies to all data blocks - <example>, <description>, and <resource>. All may need CDATA markers if <?XML?> is specified and if they include XML-reserved characters.
Note

Do not include a CDATA section unless youalso include the <?XML?> declaration.

Example
The following example incorporates two jobs into one .wsf file, using two different scripting languages:
<package>
<job id="DoneInVBS">
<?job debug="true"?>
<script language="VBScript">
WScript.Echo "This is VBScript"
</script>
</job>
<job id="DoneInJS">
<?job debug="true"?>
<script language="JScript">
WScript.Echo("This is JScript");
</script>
</job>
</package>

See Also
<runtime> Element | <named> Element | <description> Element | <example> Element | <object> Element | <package> Element | <resource> Element | <?XML?> Element

2001 Microsoft Corporation. All rights reserved.


Build: Topic Version 5.6.9309.1546
Windows Script Host

<unnamed> Element
Describes an unnamed argument for the script.
<unnamed
name
helpstring
many
required
/>

=
=
=
=

unnamedname
helpstring
boolean
boolean or integer

Arguments
name
The string that is used in the usage to represent this argument. This value is not used elsewhere.
helpstring
String that represents the help description for the argument. The WSH runtime provides the help description using the ShowUsage method or the /? argument.
many
Optional. Boolean value. If true, then this argument may be repeated more times than specified by the required attribute. Otherwise, the required attribute represents the exact number of the argument that is required. See
the example below for more details.
required
Optional. An integer value indicating how many times this argument should appear in the command line.

Remarks
The <unnamed> element is contained by (enclosed within) a set of runtime tags.
An argument with the name server would provide a /server argument at the command line and an argument named server in the WSHNamed arguments collection.
Note

The name attribute of the unnamed elementis just for display purposes.

When setting the "required" attribute, a Boolean value will be converted to an integer; "true" becomes 1 and "false" becomes 0.

Example
Here are a couple of examples of how the various attributes affect the usage with unnamed elements. First, a simple case:
<runtime>
<unnamed
name="filename"
helpstring="The file to process"
many="false"
required="true"
</>
</runtime>

This would produce the following:


Usage: example.wsf filename

Options:
filename : The file to process

Change it to:
<runtime>
<unnamed
name="filename"
helpstring="The files to process"
many="false"
required="3"
</ >
</runtime>

and the output changes to:


Usage: example.wsf filename1 filename2 filename3
Options:
filename : The files to process
The many switch will display ellipses to indicate you can enter more files than indicated. If the example changes to:
<runtime>
<unnamed
name="filename"
helpstring="The file(s) to process"
many="true"
required="1"
</>
</runtime>

then the output changes to:


Usage: example.wsf filename1 [filename2...]
Options:
filename: The file to process.
See also
ShowUsage Method | <runtime> Element | <named> Element | <description> Element | <example> Element

2001 Microsoft Corporation. All rights reserved.


Build: Topic Version 5.6.9309.1546
Windows Script Host

<usage> Element
Allows user to override default usage display.
<usage>
This section describes the script
</usage>

Remarks
The <usage> element is similar to the <example> and <description> elements it contains text that the developer can include in the usage. The difference is that if a <usage> element exists, everything else in the <runtime>
element is ignored, and only the text in the <usage> element is displayed. This is so you can completely override the usage display.
Note

The <usage> Elementshould always be enclosed by a <runtime> Element.

Example
The following script demonstrates the use of the <usage> Element:
<job>
<runtime>
<named name="arg1" helpstring="the first arg"/>
<usage>
Your usage text goes here.
</usage>
</runtime>
<script language="vbscript">
WScript.Arguments.ShowUsage
</script>
</job>

This produces the following:


Your usage text goes here.

See Also
<runtime> Element | <named> Element | <description> Element | <example> Element | <package> Element | <resource> Element | <?XML?> Element

2001 Microsoft Corporation. All rights reserved.


Build: Topic Version 5.6.9309.1546
Windows Script Host

Objects
In this Section
WScript Object
Provides access to most of the objects, methods, and properties in the WSH object model.
WshArguments Object
Gives you access to the entire collection of command-line parameters in the order in which they were originally entered.
WshController Object
Exposes the method CreateScript() that creates a remote script process.
WshEnvironment Object
Gives you access to the collection of Microsoft Windows system environment variables.

WshNamed Object
Provides access to the named command-line script arguments within the WshArguments object.
WshNetwork Object
Gives you access to the shared resources on the network to which your computer is connected.
WshRemote Object
Provides access to the remote script process.
WshRemoteError Object
Exposes the error information available when a remote script (a WshRemote object) terminates as a result of a script error.
WshScriptExec Object
Provides status and error information about a script run with Exec, along with access to the stdIn, stdOut, and stdErr channels.
WshShell Object
Gives you access to the native Windows shell functionality.
WshShortcut Object
Allows you to create a shortcut programmatically.
WshSpecialFolders Object
Allows you to access the Windows Special Folders.
WshUnnamed Object
Provides access to the unnamed command-line script arguments within the WshArguments object.
WshUrlShortcut Object
Allows you to create a shortcut to an Internet resource, programmatically.
Related Sections
WSH Reference
List of elements that make up WSH Reference.
WSH Basics
Learn the basics of WSH.

2001 Microsoft Corporation. All rights reserved.


Build: Topic Version 5.6.9309.1546
Windows Script Host

Scripting.Signer Object
The Scripting.Signer object enables an author to sign a script with a digital signature and a recipient to verify the signature's authenticity and trustworthiness.
Remarks
The Scripting.Signer object requires a valid certificate.
Example
The following JScript code shows the Scripting.Signer object digitally signing a script.
<job>
<runtime>
<named name="file" helpstring="the file to sign" required="true" type="string"/>
<named name="cert" helpstring="the name of the signing certificate" required="true" type="string"/>
<named name="store" helpstring="the name of the certificate store" required="false" type="string"/>
</runtime>
<script language="JScript">
var Signer, File, Cert, Store = "my";
if (!(WScript.Arguments.Named.Exists("cert") && WScript.Arguments.Named.Exists("file")))
{
WScript.Arguments.ShowUsage();
WScript.Quit();
}
Signer = new ActiveXObject("Scripting.Signer");
File = WScript.Arguments.Named("file");
Cert = WScript.Arguments.Named("cert");
if (WScript.Arguments.Named.Exists("store"))
{
Store = WScript.Arguments.Named("store");
}
Signer.SignFile(File, Cert, Store);
</script>
</job>

See Also
Signing a Script | Sign Method | SignFile Method | Verify Method | VerifyFile Method

2001 Microsoft Corporation. All rights reserved.


Build: Topic Version 5.6.9309.1546
Windows Script Host

Scripting.Signer Object Methods


Methods
Sign Method
SignFile Method
Verify Method
VerifyFile Method

2001 Microsoft Corporation. All rights reserved.


Build: Topic Version 5.6.9309.1546
Windows Script Host

WScript Object

Provides access to root object for the Windows Script Host object model.
Remarks
The WScript object is the root object of the Windows Script Host object model hierarchy. It never needs to be instantiated before invoking its properties and methods, and it is always available from any script file. The WScript
object provides access to information such as:

command-line arguments,
the name of the script file,
the host file name,
and host version information.

The WScript object allows you to:

create objects,
connect to objects,
disconnect from objects,
sync events,
stop a script's execution programmatically,
output information to the default output device (either a Windows dialog box or the command console).

The WScript object can be used to set the mode in which the script runs (either interactive or batch).
Example
Since the WScript object is the root object for the Windows Script Host object model, many properties and methods apply to the object. For examples of specific syntax, visit the properties and methods links.
Properties
Arguments Property | FullName Property (WScript Object) | Interactive Property | Name Property | Path Property | ScriptFullName Property | ScriptName Property | StdErr Property | StdIn Property | StdOut Property | Version
Property
Methods
CreateObject Method | ConnectObject Method | DisconnectObject Method | Echo Method | GetObject Method | Quit Method | Sleep Method
See Also
Running Your Scripts | WshShell Object | WshNetwork Object

2001 Microsoft Corporation. All rights reserved.


Build: Topic Version 5.6.9309.1546
Windows Script Host

WScript Object Properties and Methods


Properties
Arguments Property
FullName Property
Name Property
Path Property
ScriptFullName Property
ScriptName Property
StdErr Property
StdIn Property
StdOut Property
Version Property
Methods
CreateObject Method
ConnectObject Method
DisconnectObject Method
Echo Method
GetObject Method
Quit Method
Sleep Method

2001 Microsoft Corporation. All rights reserved.


Build: Topic Version 5.6.9309.1546
Windows Script Host

WshArguments Object

Provides access to the entire collection of command-line parameters in the order in which they were originally entered.
Remarks
The WshArguments object is a collection returned by the WScript object's Arguments property (WScript.Arguments). Two of the WshArguments object's properties are filtered collections of arguments one contains the
named arguments (querying this property returns a WshNamed object), the other contains the unnamed arguments (querying this property returns a WshUnnamed object). There are three ways to access sets of command-line
arguments.

You can access the entire set of arguments (those with and without names) with the WshArguments object.
You can access the arguments that have names with the WshNamed object.
You can access the arguments that have no names with the WshUnnamed object.

Example
The following code displays the command-line parameters in the WshArguments object.
[VBScript]
Set objArgs = WScript.Arguments
For I = 0 to objArgs.Count - 1
WScript.Echo objArgs(I)
Next

[JScript]
objArgs = WScript.Arguments;
for (i = 0; i < objArgs.length; i++)
{
WScript.Echo(objArgs(i));
}

Properties
Item Property | Length Property (WshArguments object) | Count Property | Named Property | Unnamed Property
Methods
Count Method | ShowUsage Method
See Also
Arguments Property | WshNamed Object | WshUnnamed Object

2001 Microsoft Corporation. All rights reserved.


Build: Topic Version 5.6.9309.1546
Windows Script Host

WshArguments Object Properties and Methods


Properties
Item Property
Length Property
Methods
Count Method

2001 Microsoft Corporation. All rights reserved.


Build: Topic Version 5.6.9309.1546
Windows Script Host

WshController Object

Provides access to the CreateScript() method (for creating a remote script process).
Example
The following example uses a controller object to create a WshRemote object.
[VBScript]
Dim Controller, RemoteScript
Set Controller = WScript.CreateObject("WSHController")
Set RemoteScript = Controller.CreateScript("remote1.js")
RemoteScript.Execute
Do While RemoteScript.Status <> 2
WScript.Sleep 100
Loop

[JScript]
var Controller = WScript.CreateObject("WSHController");
var RemoteScript = Controller.CreateScript("test.js", "remoteserver");
RemoteScript.Execute();
while (RemoteScript.Status != 2) {
WScript.Sleep(100);
}

Methods
CreateScript Method
See Also

CreateObject Method

2001 Microsoft Corporation. All rights reserved.


Build: Topic Version 5.6.9309.1546
Windows Script Host

WshController Object Methods


Methods
CreateScript Method

2001 Microsoft Corporation. All rights reserved.


Build: Topic Version 5.6.9309.1546
Windows Script Host

WshEnvironment Object

Provides access to the collection of Windows environment variables.


Remarks
The WshEnvironment object is a collection of environment variables that is returned by the WshShell object's Environment property. This collection contains the entire set of environment variables (those with names and
those without). To retrieve individual environment variables (and their values) from this collection, use the environment variable name as the index.
Example
The following code displays an environment variable.
[VBScript]
Set WshShell = WScript.CreateObject("WScript.Shell")
Set WshSysEnv = WshShell.Environment("SYSTEM")
WScript.Echo WshSysEnv("NUMBER_OF_PROCESSORS")

[JScript]
var WshShell = WScript.CreateObject("WScript.Shell");
var WshSysEnv = WshShell.Environment("SYSTEM");
WScript.Echo(WshSysEnv("NUMBER_OF_PROCESSORS"));

Properties
Item Property | Length Property (WshEnvironment object)
Methods
Count Method | Remove Method
See Also
Environment Property

2001 Microsoft Corporation. All rights reserved.


Build: Topic Version 5.6.9309.1546
Windows Script Host

WshEnvironment Object Properties and Methods


Properties
Item Property
Length Property
Methods
Count Method
Remove Method

2001 Microsoft Corporation. All rights reserved.


Build: Topic Version 5.6.9309.1546
Windows Script Host

WshNamed Object

Provides access to the named arguments from the command line.


Remarks
The Named property of the WshArguments object returns the WshNamed object, which is a collection of arguments that have names. This collection uses the argument name as the index to retrieve individual argument values.
There are three ways to access sets of command-line arguments.

You can access the entire set of arguments (those with and without names) with the WshArguments object.
You can access the arguments that have names with the WshNamed object.
You can access the arguments that have no names with the WshUnnamed object.

Example
The following code displays the number of named and unnamed command-line arguments.
<package>
<job id="JS">
<script language="JScript">
var argsNamed = WScript.Arguments.Named;
var argsUnnamed = WScript.Arguments.Unnamed;
WScript.Echo("There are " + argsNamed.length + " named arguments.");
WScript.Echo("There are " + argsUnnamed.length + " unnamed arguments.");
</script>
</job>
<job id="VBS">
<script language="VBScript">
Dim argsNamed, argsUnnamed
Set argsNamed = WScript.Arguments.Named
Set argsUnnamed = WScript.Arguments.Unnamed
WScript.Echo "There are " & argsNamed.Count & " named arguments."
WScript.Echo "There are " & argsUnnamed.Count & " unnamed arguments."
</script>
</job>
</package>

Properties
Item Property | Length Property
Methods
Count Method | Exists Method
See Also
WshArguments Object | WshUnnamed Object

2001 Microsoft Corporation. All rights reserved.


Build: Topic Version 5.6.9309.1546
Windows Script Host

WshNamed Object Properties and Methods


Properties
Item Property
Length Property
Methods
Count Method
Exists Method

2001 Microsoft Corporation. All rights reserved.


Build: Topic Version 5.6.9309.1546
Windows Script Host

WshNetwork Object

Provides access to the shared resources on the network to which your computer is connected.
Remarks
You create a WshNetwork object when you want to connect to network shares and network printers, disconnect from network shares and network printers, map or remove network shares, or access information about a user on
the network.
Example
The following example demonstrates displaying the domain name, computer name, and user name for the current computer system using the WshNetwork object.
<package>
<job id="vbs">
<script language="VBScript">
Set WshNetwork = WScript.CreateObject("WScript.Network")
WScript.Echo "Domain = " & WshNetwork.UserDomain
WScript.Echo "Computer Name = " & WshNetwork.ComputerName
WScript.Echo "User Name = " & WshNetwork.UserName
</script>
</job>

<job id="js">
<script language="JScript">
var WshNetwork = WScript.CreateObject("WScript.Network");
WScript.Echo("Domain = " + WshNetwork.UserDomain);
WScript.Echo("Computer Name = " + WshNetwork.ComputerName);
WScript.Echo("User Name = " + WshNetwork.UserName);
</script>
</job>
</package>

Properties
ComputerName Property | UserDomain Property | UserName Property
Methods
AddWindowsPrinterConnection Method | AddPrinterConnection Method | EnumNetworkDrives Method | EnumPrinterConnection Method | MapNetworkDrive Method | RemoveNetworkDrive Method |
RemovePrinterConnection Method | SetDefaultPrinter Method
See Also
Running Your Scripts | WScript Object

2001 Microsoft Corporation. All rights reserved.


Build: Topic Version 5.6.9309.1546
Windows Script Host

WshNetwork Object Properties and Methods


Properties
ComputerName Property
UserDomain Property
UserName Property
Methods
AddPrinterConnection Method
EnumNetworkDrives Method
EnumPrinterConnection Method
MapNetworkDrive Method
RemoveNetworkDrive Method
RemovePrinterConnection Method
SetDefaultPrinter Method

2001 Microsoft Corporation. All rights reserved.


Build: Topic Version 5.6.9309.1546
Windows Script Host

WshRemote Object

Provides access to the remote script process.


Remarks
The WshRemote object allows you to remotely administer computer systems on a computer network. It represents an instance of a WSH script, i.e., a script file with one of the following extensions: .wsh, .wsf, .js, .vbs, .jse,
.vbe, and so on. An instance of a running script is a process. You can run the process either on the local machine or on a remote machine. If you do not provide a network path, it will run locally. When a WSHRemote object is
created (by using the CreateScript() method), the script is copied to the target computer system. Once there, the script does not begin executing immediately; it begins executing only when the WSHRemote method Execute is
invoked. Through the WshRemote object interface, your script can manipulate other programs or scripts. Additionally, external applications can also manipulate remote scripts. The WshRemote object works asynchronously
over DCOM.
Example
The following example demonstrates how the WshRemote object is used to start a remote script.
[VBScript]
Dim Controller, RemoteScript
Set Controller = WScript.CreateObject("WSHController")
Set RemoteScript = Controller.CreateScript("test.js", "remoteserver")
RemoteScript.Execute
Do While RemoteScript.Status <> 2
WScript.Sleep 100
Loop

[JScript]
var Controller = WScript.CreateObject("WSHController");
var RemoteScript = Controller.CreateScript("test.js", "remoteserver");
RemoteScript.Execute();
while (RemoteScript.Status != 2) {
WScript.Sleep(100);
}

Properties
Status Property | Error Property

Methods
Execute Method | Terminate Method
Events
Start Event | End Event | Error Event
See Also
WshController Object

2001 Microsoft Corporation. All rights reserved.


Build: Topic Version 5.6.9309.1546
Windows Script Host

WshRemote Object Properties, Methods, and Events


Properties
Status Property
Error Property
Methods
Execute Method
Terminate Method
Events
Start Event
End Event
Error Event

2001 Microsoft Corporation. All rights reserved.


Build: Topic Version 5.6.9309.1546
Windows Script Host

WshRemoteError Object

Provides access to the error information available when a remote script (a WshRemote object) terminates as a result of a script error.
Remarks
The WshRemoteError object is returned by the Error property of the WshRemote object.
Example
The following example demonstrates how the WshRemoteError object is used to show where the error occurred in the script along with a description of the error.
[VBScript]
Dim Controller, RemoteScript
Set Controller = WScript.CreateObject("WSHController")
Set RemoteScript = Controller.CreateScript("test.js", "remoteserver")
WScript.ConnectObject RemoteScript, "remote_"
RemoteScript.Execute
Do While RemoteScript.Status <> 2
WScript.Sleep 100
Loop
WScript.DisconnectObject RemoteScript
Sub remote_Error
Dim theError
Set theError = RemoteScript.Error
WScript.Echo "Error " & theError.Number & " - Line: " & theError.Line & ", Char: " & theError.Character & vbCrLf & "Description: " & theError.Description
WScript.Quit -1
End Sub

[JScript]
var Controller = WScript.CreateObject("WSHController");
var RemoteScript = Controller.CreateScript("test.js", "remoteserver");
WScript.ConnectObject(RemoteScript, "remote_");
RemoteScript.Execute();
while (RemoteScript.Status != 2) {
WScript.Sleep(100);
}
WScript.DisconnectObject(RemoteScript);
function remote_Error()
{
var theError = RemoteScript.Error;
WScript.Echo("Error " + theError.Number + " - Line: " + theError.Line + ", Char: " + theError.Character + "\nDescription: " + theError.Description);
WScript.Quit(-1);
}

Properties
Description Property | Line Property | Character Property | SourceText Property | Source Property | Number Property

See Also
WshRemote Object

2001 Microsoft Corporation. All rights reserved.


Build: Topic Version 5.6.9309.1546
Windows Script Host

WshRemoteError Object Properties


Properties
Description Property
Line Property
Character Property
SourceText Property
Source Property
Number Property

2001 Microsoft Corporation. All rights reserved.


Build: Topic Version 5.6.9309.1546
Windows Script Host

WshScriptExec Object

Provides status information about a script run with Exec along with access to the StdIn, StdOut, and StdErr streams.
Remarks
The WshScriptExec object is returned by the Exec method of the WshShell object. The Exec method returns the WshScriptExec object either once the script or program has finished executing, or before the script or program
begins executing.
Example
The following code runs calc.exe and echoes the final status to the screen.
[VBScript]
Dim WshShell, oExec
Set WshShell = CreateObject("WScript.Shell")
Set oExec = WshShell.Exec("calc")
Do While oExec.Status = 0
WScript.Sleep 100
Loop
WScript.Echo oExec.Status

[JScript]
var WshShell = new ActiveXObject("WScript.Shell");
var oExec = WshShell.Exec("calc");
while (oExec.Status == 0)
{
WScript.Sleep(100);
}
WScript.Echo(oExec.Status);

Properties
Status Property | StdOut Property | StdIn Property | StdErr Property
Methods
Terminate Method
See Also
WScript Object | Exec Method

2001 Microsoft Corporation. All rights reserved.


Build: Topic Version 5.6.9309.1546
Windows Script Host

WshScriptExec Object Properties and Methods


Properties
ExitCode Property
ProcessID Property

Status Property
StdOut Property
StdIn Property
StdErr Property
Methods
Terminate Method

2001 Microsoft Corporation. All rights reserved.


Build: Topic Version 5.6.9309.1546
Windows Script Host

WshShell Object

Provides access to the native Windows shell.


Remarks
You create a WshShell object whenever you want to run a program locally, manipulate the contents of the registry, create a shortcut, or access a system folder. The WshShell object provides the Environment collection. This
collection allows you to handle environmental variables (such as WINDIR, PATH, or PROMPT).
Example
The following example demonstrates the creation of a shortcut to the script being run and a URL shortcut to www.microsoft.com:
<package>
<job id="vbs">
<script language="VBScript">
set WshShell = WScript.CreateObject("WScript.Shell")
strDesktop = WshShell.SpecialFolders("Desktop")
set oShellLink = WshShell.CreateShortcut(strDesktop & "\Shortcut Script.lnk")
oShellLink.TargetPath = WScript.ScriptFullName
oShellLink.WindowStyle = 1
oShellLink.Hotkey = "CTRL+SHIFT+F"
oShellLink.IconLocation = "notepad.exe, 0"
oShellLink.Description = "Shortcut Script"
oShellLink.WorkingDirectory = strDesktop
oShellLink.Save
</script>
</job>
<job id="js">
<script language="JScript">
var WshShell = WScript.CreateObject("WScript.Shell");
strDesktop = WshShell.SpecialFolders("Desktop");
var oShellLink = WshShell.CreateShortcut(strDesktop + "\\Shortcut Script.lnk");
oShellLink.TargetPath = WScript.ScriptFullName;
oShellLink.WindowStyle = 1;
oShellLink.Hotkey = "CTRL+SHIFT+F";
oShellLink.IconLocation = "notepad.exe, 0";
oShellLink.Description = "Shortcut Script";
oShellLink.WorkingDirectory = strDesktop;
oShellLink.Save();
</script>
</job>
</package>

Properties
CurrentDirectory Property | Environment Property | SpecialFolders Property
Methods
AppActivate Method | CreateShortcut Method | ExpandEnvironmentStrings Method | LogEvent Method | Popup Method | RegDelete Method | RegRead Method | RegWrite Method | Run Method | SendKeys Method | Exec
Method
See Also
Running Your Scripts

2001 Microsoft Corporation. All rights reserved.


Build: Topic Version 5.6.9309.1546
Windows Script Host

WshShellObject Properties and Methods


Properties
CurrentDirectory Property
Environment Property
SpecialFolders Property
Methods
AppActivate Method
CreateShortcut Method
ExpandEnvironmentStrings Method
LogEvent Method

Popup Method
RegDelete Method
RegRead Method
RegWrite Method
Run Method
SendKeys Method

2001 Microsoft Corporation. All rights reserved.


Build: Topic Version 5.6.9309.1546
Windows Script Host

WshShortcut Object

Allows you to create a shortcut programmatically.


Example
The following example demonstrates the creation of a shortcut to the script being run:
<package>
<job id="vbs">
<script language="VBScript">
set WshShell = WScript.CreateObject("WScript.Shell")
strDesktop = WshShell.SpecialFolders("Desktop")
set oShellLink = WshShell.CreateShortcut(strDesktop & "\Shortcut Script.lnk")
oShellLink.TargetPath = WScript.ScriptFullName
oShellLink.WindowStyle = 1
oShellLink.Hotkey = "CTRL+SHIFT+F"
oShellLink.IconLocation = "notepad.exe, 0"
oShellLink.Description = "Shortcut Script"
oShellLink.WorkingDirectory = strDesktop
oShellLink.Save
</script>
</job>
<job id="js">
<script language="JScript">
var WshShell = WScript.CreateObject("WScript.Shell");
strDesktop = WshShell.SpecialFolders("Desktop");
var oShellLink = WshShell.CreateShortcut(strDesktop + "\\Shortcut Script.lnk");
oShellLink.TargetPath = WScript.ScriptFullName;
oShellLink.WindowStyle = 1;
oShellLink.Hotkey = "CTRL+SHIFT+F";
oShellLink.IconLocation = "notepad.exe, 0";
oShellLink.Description = "Shortcut Script";
oShellLink.WorkingDirectory = strDesktop;
oShellLink.Save();
</script>
</job>
</package>

Properties
Arguments Property | Description Property | FullName Property (WshShortcut Object) | Hotkey Property | IconLocation Property | TargetPath Property | WindowStyle Property | WorkingDirectory Property
Methods
Save Method
See Also
Running Your Scripts | CreateShortcut Method

2001 Microsoft Corporation. All rights reserved.


Build: Topic Version 5.6.9309.1546
Windows Script Host

WshShortcut Object Properties and Methods


Properties
Arguments Property
Description Property
FullName Property
Hotkey Property
IconLocation Property
TargetPath Property
WindowStyle Property
WorkingDirectory Property
Methods
Save Method

2001 Microsoft Corporation. All rights reserved.


Build: Topic Version 5.6.9309.1546
Windows Script Host

WshSpecialFolders Object

Provides access to the collection of Windows special folders.


Remarks
The WshShell object's SpecialFolders property returns the WshSpecialFolders object, which is a collection of special folders. This collection contains references to Windows special folders (for example, the Desktop folder,
Start Menu folder, and Personal Documents folder). This collection retrieves paths to special folders using the special folder name as the index. A special folder's path depends on the user environment. The information stored
in a special folder is unique to the user logged onto the computer system. If several different users have accounts on the same computer system, several different sets of special folders are stored on the hard disk.
The following special folders are available:

AllUsersDesktop
AllUsersStartMenu
AllUsersPrograms
AllUsersStartup
Desktop
Favorites
Fonts
MyDocuments
NetHood
PrintHood
Programs
Recent
SendTo
StartMenu
Startup
Templates

Example
The following script demonstrates the use of the WshSpecialFolders Object:
<package>
<job id="vbs">
<script language="VBScript">
set WshShell = WScript.CreateObject("WScript.Shell")
strDesktop = WshShell.SpecialFolders("Desktop")
set oShellLink = WshShell.CreateShortcut(strDesktop & "\Shortcut Script.lnk")
oShellLink.TargetPath = WScript.ScriptFullName
oShellLink.WindowStyle = 1
oShellLink.Hotkey = "CTRL+SHIFT+F"
oShellLink.IconLocation = "notepad.exe, 0"
oShellLink.Description = "Shortcut Script"
oShellLink.WorkingDirectory = strDesktop
oShellLink.Save
</script>
</job>
<job id="js">
<script language="JScript">
var WshShell = WScript.CreateObject("WScript.Shell");
strDesktop = WshShell.SpecialFolders("Desktop");
var oShellLink = WshShell.CreateShortcut(strDesktop + "\\Shortcut Script.lnk");
oShellLink.TargetPath = WScript.ScriptFullName;
oShellLink.WindowStyle = 1;
oShellLink.Hotkey = "CTRL+SHIFT+F";
oShellLink.IconLocation = "notepad.exe, 0";
oShellLink.Description = "Shortcut Script";
oShellLink.WorkingDirectory = strDesktop;
oShellLink.Save();
</script>
</job>
</package>

Properties
Item Property
Methods
Count Method
See Also
Running Your Scripts | SpecialFolders Property

2001 Microsoft Corporation. All rights reserved.


Build: Topic Version 5.6.9309.1546
Windows Script Host

WshSpecialFolders Object Properties and Methods


Properties
Item Property
Length Property
Methods
Count Method

2001 Microsoft Corporation. All rights reserved.


Build: Topic Version 5.6.9309.1546
Windows Script Host

WshUnnamed Object

Provides access to the unnamed arguments from the command line.


Remarks
The WshUnnamed object is a read-only collection that is returned by the Unnamed property of the WshArguments object. Individual argument values are retrieved from this collection using zero-based indexes. Two of the
WshArguments object's properties are filtered arguments collections one contains the named arguments (the WshNamed object), the other contains the unnamed arguments (the WshUnnamed object). In total, this gives you
three ways to access sets of command-line arguments.

You can access the entire set of arguments (those with and without names) with the WshArguments object.
You can access the arguments that have names with the WshNamed object.
You can access the arguments that have no names with the WshUnnamed object.

Example
The following code displays the number of named and unnamed command-line arguments.
<package>
<job id="JS">
<script language="JScript">
var argsNamed = WScript.Arguments.Named;
var argsUnnamed = WScript.Arguments.Unnamed;
WScript.Echo("There are " + argsNamed.length + " named arguments.");
WScript.Echo("There are " + argsUnnamed.length + " unnamed arguments.");
</script>
</job>
<job id="VBS">
<script language="VBScript">
Dim argsNamed, argsUnnamed
Set argsNamed = WScript.Arguments.Named
Set argsUnnamed = WScript.Arguments.Unnamed
WScript.Echo "There are " & argsNamed.Count & " named arguments."
WScript.Echo "There are " & argsUnnamed.Count & " unnamed arguments."
</script>
</job>
</package>

Properties
Item Property | Length Property (WshArguments object)
Methods
Count Method
See Also
WshArguments Object | WshNamed Object

2001 Microsoft Corporation. All rights reserved.


Build: Topic Version 5.6.9309.1546
Windows Script Host

WshUnnamed Object Properties and Methods


Properties
Item Property
Length Property
Methods
Count Method

2001 Microsoft Corporation. All rights reserved.


Build: Topic Version 5.6.9309.1546
Windows Script Host

WshUrlShortcut Object

Allows you to create a shortcut to an Internet resource programmatically.


Remarks
The WshUrlShortcut object is a child object of the WshShell object you must use the WshShell method CreateShortcut to create a WshUrlShortcut object (e.g., WshShell.CreateShortcut(strDesktop & "\Shortcut
Script.lnk")).

Example
The following example demonstrates the creation of a URL shortcut to www.microsoft.com.
<package>
<job id="vbs">
<script language="VBScript">
set WshShell = WScript.CreateObject("WScript.Shell")
set oUrlLink = WshShell.CreateShortcut(strDesktop & "\Microsoft Web Site.url")
oUrlLink.TargetPath = "http://www.microsoft.com"
oUrlLink.Save
</script>
</job>
<job id="js">
<script language="JScript">
var WshShell = WScript.CreateObject("WScript.Shell");
var oUrlLink = WshShell.CreateShortcut(strDesktop + "\\Microsoft Web Site.url");
oUrlLink.TargetPath = "http://www.microsoft.com";
oUrlLink.Save();
</script>
</job>
</package>

Properties
FullName Property (WshUrlShortcut Object) | TargetPath Property
Methods
Save Method
See Also
Running Your Scripts | CreateShortcut Method

2001 Microsoft Corporation. All rights reserved.


Build: Topic Version 5.6.9309.1546
Windows Script Host

WshUrlShortcut Object Properties and Methods


Properties
FullName Property
TargetPath Property
Methods
Save Method

2001 Microsoft Corporation. All rights reserved.


Build: Topic Version 5.6.9309.1546
Windows Script Host

Properties
In this Section
Arguments Property
Returns the WshArguments object.
AtEndOfLine Property
Returns a Boolean value indicating whether the end of an input line has been reached.
AtEndOfStream Property
Returns a Boolean value indicating whether the end of an input stream has been reached.
Character Property
Reports the specific character in the line of code that contained the error.
Column Property
Returns the column number of the current character position in an input stream.
ComputerName Property
Returns the name of the computer.
CurrentDirectory Property
Allows you to set or retrieve the active script's current working folder.
Description Property
Returns the description of a shortcut.
Environment Property
Returns the WshEnvironment object.
Error Property (WshRemote)
Exposes a WshRemoteError object.
ExitCode Property
Returns the exit code set by a script/program run using the Exec() method.
FullName Property
Returns a fully qualified path name.
Hotkey Property
Allows you to assign a key combination to a shortcut and determine the key combination to a shortcut.
IconLocation Property
Allows you to assign an icon to a shortcut and determine which icon has been assigned to a shortcut.
Interactive Property
Allows you to set the script mode programmatically, as well as determine the script mode programmatically.
Item Property
Exposes a specified item from a collection.
Item Property (WshNamed)
Provides access to the items in the WshNamed object.
Item Property (WshUnnamed)
Returns an item using a zero-based index.
Length Property
Returns the number of items in a collection.
Line Property (WScript)
Returns the current line number in an input stream.

Line Property (WshRemote)


Identifies the line in a script that contains an error-causing statement.
Name Property
Returns the friendly name of the WScript object (the host executable file).
Number Property
Reports the error number representing a script error.
Path PropertyPath
Returns the name of the directory containing the WScript object (the host executable file).
ProcessID Property
Reports the process ID (PID) of a process started with the WshScriptExec object.
ScriptFullName Property
Returns the full path-name of the currently running script.
ScriptName Property
Returns the file name of the currently running script.
Source Property
Identifies the COM object responsible for causing the script error.
SourceText Property
Contains the line of source code that caused an error.
SpecialFolders Property
Returns the WshSpecialFolders object.
Status Property (WshRemote)
Reports the current running-condition of the remote script.
Status Property (WshScriptExec)
Provides status information about a script run with the Exec() method.
StdErr Property (WScript)
Exposes the write-only error output stream for the current script.
StdErr Property (WshScriptExec)
Exposes the read-only stderr output stream of the Exec object.
StdIn Property (WScript)
Exposes the read-only input stream for the current script.
StdIn Property (WshScriptExec)
Exposes the write-only stdin input stream of the Exec object.
StdOut Property (WScript)
Exposes the write-only output stream for the current script.
StdOut Property (WshScriptExec)
Exposes the write-only stdout output stream of the Exec object.
TargetPath Property
Allows you to assign a path to the executable file to which a shortcut points, as well as a determine the path to the executable file pointed to by a shortcut.
UserDomain Property
Returns the user's domain name.
UserName Property
Returns the name of the user.
Version Property
Returns the version of WSH.
WindowStyle Property
Allows you to assign a window style to a shortcut, as well as determine the type of window style used by a shortcut.
WorkingDirectory Property
Allows you to assign a working directory to a shortcut, as well as determine the working directory used by a shortcut.
Related Sections
WSH Language
List of elements that make up WSH Reference.
WSH Basics
Learn the basics of WSH.

2001 Microsoft Corporation. All rights reserved.


Build: Topic Version 5.6.9309.1546
Windows Script Host

Arguments Property (Shortcut Object)


Sets the arguments for a shortcut, or identifies a shortcut's arguments.
object.Arguments

Arguments
object
WshShortcut object.
Remarks
The Arguments property returns a string.
Example
The following code sets the Arguments property.
[VBScript]
set WshShell = WScript.CreateObject("WScript.Shell")
strDesktop = WshShell.SpecialFolders("Desktop")
set oShellLink = WshShell.CreateShortcut(strDesktop & "\Shortcut Script.lnk")
oShellLink.TargetPath = WScript.ScriptFullName
oShellLink.WindowStyle = 1
oShellLink.Hotkey = "Ctrl+Alt+f"
oShellLink.IconLocation = "notepad.exe, 0"
oShellLink.Description = "Shortcut Script"
oShellLink.WorkingDirectory = strDesktop
oShellLink.Arguments = "C:\myFile.txt"
oShellLink.Save

[JScript]
var WshShell = WScript.CreateObject("WScript.Shell");
var strDesktop = WshShell.SpecialFolders("Desktop");
var oShellLink = WshShell.CreateShortcut(strDesktop + "\\Shortcut Script.lnk");
oShellLink.TargetPath = WScript.ScriptFullName;
oShellLink.WindowStyle= 1;
oShellLink.Hotkey= "Ctrl+Alt+f";
oShellLink.IconLocation= "notepad.exe, 0";
oShellLink.Description= "Shortcut Script";
oShellLink.WorkingDirectory= strDesktop;
oShellLink.Arguments = "C:\\myFile.txt"; oShellLink.Save();

See Also

WshShortcut Object | WshShell Object | CreateShortcut Method

2001 Microsoft Corporation. All rights reserved.


Build: Topic Version 5.6.9309.1546
Windows Script Host

Arguments Property (WScript Object)


Returns the WshArguments object (a collection of arguments).
object.Arguments

Arguments
object
WScript object.
Remarks
The Arguments property contains the WshArguments object (a collection of arguments). Use a zero-based index to retrieve individual arguments from this collection.
Example
The following code samples display the entire set of command-line parameters associated with a script.
[VBScript]
Set objArgs = WScript.Arguments
For I = 0 to objArgs.Count - 1
WScript.Echo objArgs(I)
Next

[JScript]
objArgs = WScript.Arguments;
for (i = 0; i < objArgs.length; i++)
{
WScript.Echo(objArgs(i));
}

See Also
WScript Object | WshArguments Object | WshNamed Object | WshUnnamed Object

2001 Microsoft Corporation. All rights reserved.


Build: Topic Version 5.6.9309.1546
Windows Script Host

AtEndOfLine Property
Returns a Boolean value indicating whether the end of a line in an input stream has been reached.
object.AtEndOfLine

Arguments
object
StdIn text stream object.
Remarks
The AtEndOfLine property contains a Boolean value indicating whether the end of a line in an input stream has been reached. The AtEndOfLine property returns True if the stream pointer immediately precedes the end-of-line
marker in an input stream, False if it does not. The StdIn, StdOut, and StdErr properties and methods work only when the script is run with CScript.exe. If the script is run with WScript.exe, an error occurs.
Example
The following samples will read a line of text from the keyboard and display whatever was typed when the end of the line is seen.
[VBScript]
Dim Input
Input = ""
Do While Not WScript.StdIn.AtEndOfLine
Input = Input & WScript.StdIn.Read(1)
Loop
WScript.Echo Input

[JScript]
var input = "";
while (!WScript.StdIn.AtEndOfLine)
{
input += WScript.StdIn.Read(1);
}
WScript.Echo(input);

See Also
StdIn Property | Error Messages

2001 Microsoft Corporation. All rights reserved.


Build: Topic Version 5.6.9309.1546
Windows Script Host

AtEndOfStream Property
Returns a Boolean value indicating whether the end of an input stream has been reached.
object.AtEndOfStream

Arguments
object
StdIn text stream object.
Remarks
The AtEndOfStream property contains a Boolean value indicating whether the end of an input stream has been reached. The AtEndOfStream property returns True if the stream pointer is at the end of an input stream, False if
not. The StdIn, StdOut, and StdErr properties and methods work only when the script is run with CScript.exe. If the script is run with WScript.exe, an error occurs.
Example
The following code samples demonstrate the AtEndOfStream property by reading a standard directory listing from "dir", stripping the top and bottom lines that aren't actual entries, and double spacing the directory entries.
[VBScript]
Dim StdIn, StdOut, Str1, Str2
Set StdIn = WScript.StdIn
Set StdOut = WScript.StdOut
Str1 = ""
Str2 = ""For i = 0 to 4
StdIn.SkipLine
Next
i = 0
Do While Not StdIn.AtEndOfStream
If i >= 2 Then
StdOut.WriteLine Str1
End If
i = i + 1
Str1 = Str2
Str2 = StdIn.ReadLine
Loop

[JScript]
var
var
var
var
for

stdin = WScript.StdIn;
stdout = WScript.StdOut;
str1, str2 = "";
i;
(i = 0; i < 5; i++)
stdin.SkipLine();
i = 0;
while (!stdin.AtEndOfStream)
{
if (i++ >= 2)
{
stdout.WriteLine(str1);
}
str1 = str2;
str2 = stdin.ReadLine();
}

See Also
StdIn Property | Error Messages

2001 Microsoft Corporation. All rights reserved.


Build: Topic Version 5.6.9309.1546
Windows Script Host

BuildVersion Property
Returns the Windows Script Host build version number.
Object.BuildVersion

Parameters
Object
WScript object.
Remarks
The BuildVersion property returns an integer value.
The full version number of Windows Script Host consists of the product release version number followed by the build version number. For example, if the Windows Script Host product release version number is 5.6, and the
build version number is 6626, the full version number is 5.6.6626.
Example
The following code returns the full version number of the Windows Script Host. This consists of the product release version number plus the build version number.
WScript.Echo WScript.Version & "." & WScript.BuildVersion;

See Also
Version Property

2001 Microsoft Corporation. All rights reserved.


Build: Topic Version 5.6.9309.1546
Windows Script Host

Character Property
Reports the specific character in a line of code that contains an error.
Object.Character

Arguments
Object
WshRemoteError object.
Remarks
The Character property returns a signed long integer.
Some errors are not associated with a particular character position. For example, consider the error Expected End If. In this case, there is no line (a line of code is missing). In such a case, the Character property returns zero
(0).
The character position is based on an offset of one (1) (the first character in a line resides at position one).
Example
The following JScript code demonstrates how the WshRemoteError object exposes the character in the line of code that contained the error.
[VBScript]
Dim Controller, RemoteScript
Set Controller = WScript.CreateObject("WSHController")
Set RemoteScript = Controller.CreateScript("test.js", "remoteserver")
WScript.ConnectObject RemoteScript, "remote_"
RemoteScript.Execute
Do While RemoteScript.Status <> 2
WScript.Sleep 100
Loop
Sub remote_Error
Dim theError
Set theError = RemoteScript.Error
WScript.Echo "Error - Line: " & theError.Line & ", Char: " & theError.Character & vbCrLf & "Description: " & theError.Description
WScript.Quit -1
End Sub

[JScript]
var Controller = WScript.CreateObject("WSHController");
var RemoteScript = Controller.CreateScript("test.js", "remoteserver");
WScript.ConnectObject(RemoteScript, "remote_");
RemoteScript.Execute();
while (RemoteScript.Status != 2) {
WScript.Sleep(100);
}
function remote_Error()
{
var theError = RemoteScript.Error;
WScript.Echo("Error - Line: " + theError.Line + ", Char: " + theError.Character + "\nDescription: " + theError.Description);
WScript.Quit(-1);
}

See Also
WshRemote Object | WshRemoteError Object | Line Property| Description Property | SourceText Property | Number Property | Source Property

2001 Microsoft Corporation. All rights reserved.


Build: Topic Version 5.6.9309.1546
Windows Script Host

Column Property
Returns the column number of the current character position in an input stream.
object.Column

Arguments
object
StdIn text stream object.
Remarks
The Column property contains a read-only integer value indicating the column number of the current character position in an input stream. The Column property is equal to 1 after a newline character is written (even before any
other character is written). The StdIn, StdOut, and StdErr properties and methods work only when the script is run with CScript.exe. If the script is run with WScript.exe, an error occurs.
Example
The following code demonstrates the use of the Column property by reading input from the keyboard and breaking it into lines of 20 characters.
[VBScript]
Dim Input
Input = ""
Do While Not WScript.StdIn.AtEndOfLine
Input = Input & WScript.StdIn.Read(1)
If (WScript.StdIn.Column - 1) Mod 20 = 0 Then
Input = Input & vbCrLf
End If
Loop
WScript.Echo Input

[JScript]
var input = "";
while (!WScript.StdIn.AtEndOfLine)
{
input += WScript.StdIn.Read(1);
if ((WScript.StdIn.Column - 1) % 20 == 0)

input += "\n";
}
WScript.Echo(input);

See Also
StdIn Property | Error Messages

2001 Microsoft Corporation. All rights reserved.


Build: Topic Version 5.6.9309.1546
Windows Script Host

ComputerName Property
Returns the name of the computer system.
object.ComputerName

Arguments
object
WshNetwork object.
Remarks
The ComputerName property contains a string value indicating the name of the computer system.
Example
The following example demonstrates the use of the ComputerName property.
<package>
<job id="vbs">
<script language="VBScript">
Set WshNetwork = WScript.CreateObject("WScript.Network")
WScript.Echo "Domain = " & WshNetwork.UserDomain
WScript.Echo "Computer Name = " & WshNetwork.ComputerName
WScript.Echo "User Name = " & WshNetwork.UserName
</script>
</job>
<job id="js">
<script language="JScript">
var WshNetwork = WScript.CreateObject("WScript.Network");
WScript.Echo("Domain = " + WshNetwork.UserDomain);
WScript.Echo("Computer Name = " + WshNetwork.ComputerName);
WScript.Echo("User Name = " + WshNetwork.UserName);
}
</script>
</job>
</package>

See Also
Running Your Scripts | WshNetwork Object

2001 Microsoft Corporation. All rights reserved.


Build: Topic Version 5.6.9309.1546
Windows Script Host

CurrentDirectory Property
Retrieves or changes the current active directory.
object.CurrentDirectory

Arguments
object
WshShell object.
Remarks
The CurrentDirectory returns a string that contains the fully qualified path of the current working directory of the active process.
Example
The following code displays the current active directory.
[VBScript]
Dim WshShell
Set WshShell = WScript.CreateObject("WScript.Shell")
WScript.Echo WshShell.CurrentDirectory

[JScript]
var WshShell = WScript.CreateObject ("WScript.Shell");
WScript.Echo (WshShell.CurrentDirectory);

See Also
WshShell Object

2001 Microsoft Corporation. All rights reserved.


Build: Topic Version 5.6.9309.1546

Windows Script Host

Description Property
Returns a shortcut's description.
object.Description

Arguments
object
WshShortcut object.
Remarks
The Description property contains a string value describing a shortcut.
Example
The following example demonstrates the use of the Description Property.
<package>
<job id="vbs">
<script language="VBScript">
set WshShell = WScript.CreateObject("WScript.Shell")
strDesktop = WshShell.SpecialFolders("Desktop")
set oShellLink = WshShell.CreateShortcut(strDesktop & "\Shortcut Script.lnk")
oShellLink.TargetPath = WScript.ScriptFullName
oShellLink.WindowStyle = 1
oShellLink.Hotkey = "Ctrl+Alt+e"
oShellLink.IconLocation = "notepad.exe, 0"
oShellLink.Description = "Shortcut Script"
oShellLink.WorkingDirectory = strDesktop
oShellLink.Save
set oUrlLink = WshShell.CreateShortcut(strDesktop & "\Microsoft Web Site.url")
oUrlLink.TargetPath = "http://www.microsoft.com"
oUrlLink.Save
</script>
</job>
<job id="js">
<script language="JScript">
var WshShell = WScript.CreateObject("WScript.Shell");
strDesktop = WshShell.SpecialFolders("Desktop");
var oShellLink = WshShell.CreateShortcut(strDesktop + "\\Shortcut Script.lnk");
oShellLink.TargetPath = WScript.ScriptFullName;
oShellLink.WindowStyle = 1;
oShellLink.Hotkey = "Ctrl+Alt+e";
oShellLink.IconLocation = "notepad.exe, 0";
oShellLink.Description = "Shortcut Script";
oShellLink.WorkingDirectory = strDesktop;
oShellLink.Save();
var oUrlLink = WshShell.CreateShortcut(strDesktop + "\\Microsoft Web Site.url");
oUrlLink.TargetPath = "http://www.microsoft.com";
oUrlLink.Save();
</script>
</job>
</package>

See Also
Running Your Scripts | WshShortcut Object

2001 Microsoft Corporation. All rights reserved.


Build: Topic Version 5.6.9309.1546
Windows Script Host

Description Property (WshRemoteError)


Contains a brief description of the error that caused the remote script to terminate.
Object.Description

Arguments
Object
WshRemoteError object.
Remarks
The Description property returns a string.
If an error description is not available, the Description property returns an empty string.
Example
The following JScript code demonstrates how the WshRemoteError object exposes the description of the error.
[VBScript]
Dim Controller, RemoteScript
Set Controller = WScript.CreateObject("WSHController")
Set RemoteScript = Controller.CreateScript("test.js", "remoteserver")
WScript.ConnectObject RemoteScript, "remote_"
RemoteScript.Execute
Do While RemoteScript.Status <> 2
WScript.Sleep 100
Loop
Sub remote_Error
Dim theError
Set theError = RemoteScript.Error
WScript.Echo "Error - Line: " & theError.Line & ", Char: " & theError.Character & vbCrLf & "Description: " & theError.Description
WScript.Quit -1
End Sub

[JScript]
var Controller = WScript.CreateObject("WSHController");
var RemoteScript = Controller.CreateScript("test.js", "remoteserver");

WScript.ConnectObject(RemoteScript, "remote_");
RemoteScript.Execute();
while (RemoteScript.Status != 2) {
WScript.Sleep(100);
}
function remote_Error()
{
var theError = RemoteScript.Error;
WScript.Echo("Error - Line: " + theError.Line + ", Char: " + theError.Character + "\nDescription: " + theError.Description);
WScript.Quit(-1);
}

See Also
WshRemote Object | WshRemoteError Object | Line Property | Character Property | SourceText Property | Number Property | Source Property

2001 Microsoft Corporation. All rights reserved.


Build: Topic Version 5.6.9309.1546
Windows Script Host

Environment Property
Returns the WshEnvironment object (a collection of environment variables).
object.Environment ([strType])

Arguments
object
WshShell object.
strType
Optional. Specifies the location of the environment variable.
Remarks
The Environment property contains the WshEnvironment object (a collection of environment variables). If strType is supplied, it specifies where the environment variable resides with possible values of System, User, Volatile,
or Process. If strType is not supplied, the Environment property returns different environment variable types depending on the operating system.
Type of Environment Variable
Operating System
System
Microsoft Windows NT/2000
Process
Windows 95/98/Me
Note

For Windows 95/98/Me,


only one strType is permitted Process.

The following table lists some of the variables that are provided with the Windows operating system. Scripts can access environment variables that have been set by other applications.
Note

None of the following variables areavailable from the Volatile type.


Name

NUMBER_OF_PROCESSORS
PROCESSOR_ARCHITECTURE
PROCESSOR_IDENTIFIER
PROCESSOR_LEVEL
PROCESSOR_REVISION
OS
COMSPEC
HOMEDRIVE
HOMEPATH
PATH
PATHEXT
PROMPT
SYSTEMDRIVE
SYSTEMROOT
WINDIR

TEMP
TMP

Description
Number of processors running on the
X
machine.
Processor type of the user's workstation. X
Processor ID of the user's workstation. X
Processor level of the user's
X
workstation.
Processor version of the user's
X
workstation.
Operating system on the user's
X
workstation.
Executable file for the command prompt X
(typically cmd.exe).
Primary local drive (typically the C
drive).
Default directory for users (typically
\users\default in Windows 2000).
PATH environment variable.
X
Extensions for executable files
X
(typically .com, .exe, .bat, or .cmd).
Command prompt (typically $P$G).
Local drive on which the system
directory resides (typically c:\).
System directory (for example,
c:\winnt). This is the same as WINDIR.
System directory (for example,
X
c:\winnt). This is the same as
SYSTEMROOT.
Directory for storing temporary files
(for example, c:\temp).
Directory for storing temporary files
(for example, c:\temp).

Example
The following code retrieves the system environment variable NUMBER_OF_PROCESSORS.
[VBScript]
Set WshShell = WScript.CreateObject("WScript.Shell")
Set WshSysEnv = WshShell.Environment("SYSTEM")
WScript.Echo WshSysEnv("NUMBER_OF_PROCESSORS")

[JScript]
var WshShell = WScript.CreateObject("WScript.Shell");
var WshSysEnv = WshShell.Environment("SYSTEM");
WScript.Echo(WshSysEnv("NUMBER_OF_PROCESSORS"));

See Also
WshEnvironment Object | WshShell Object

System

User

Process (NT/
2000)

Process (98/ME)

X
X
X

X
-

X
X

X
-

X
X

X
-

2001 Microsoft Corporation. All rights reserved.


Build: Topic Version 5.6.9309.1546
Windows Script Host

Error Property (WshRemote)


Exposes the WshRemoteError object, which holds information about the error that caused the remote script to terminate prematurely.
Object.Error

Arguments
Object
WshRemote object.
Remarks
The Error property returns a WshRemoteError object.
Example
The following code demonstrates how the Error property of the WshRemote object exposes a WshRemoteError object, which exposes the line, character, and description of the error.
[VBScript]
Dim Controller, RemoteScript
Set Controller = WScript.CreateObject("WSHController")
Set RemoteScript = Controller.CreateScript("test.js", "remoteserver")
WScript.ConnectObject RemoteScript, "remote_"
RemoteScript.Execute
Do While RemoteScript.Status <> 2
WScript.Sleep 100
Loop
Sub remote_Error
Dim theError
Set theError = RemoteScript.Error
WScript.Echo "Error - Line: " & theError.Line & ", Char: " & theError.Character & vbCrLf & "Description: " & theError.Description
WScript.Quit -1
End Sub

[JScript]
var Controller = WScript.CreateObject("WSHController");
var RemoteScript = Controller.CreateScript("test.js", "remoteserver");
WScript.ConnectObject(RemoteScript, "remote_");
RemoteScript.Execute();
while (RemoteScript.Status != 2) {
WScript.Sleep(100);
}
function remote_Error()
{
var theError = RemoteScript.Error;
WScript.Echo("Error - Line: " + theError.Line + ", Char: " + theError.Character + "\nDescription: " + theError.Description);
}

WScript.Quit(-1);

See Also
WshController Object | WshRemote Object | WshRemoteError Object | Status Property | Execute Method | Terminate Method | Start Event | End Event | Error Event

2001 Microsoft Corporation. All rights reserved.


Build: Topic Version 5.6.9309.1546
Windows Script Host

ExitCode Property
Returns the exit code set by a script or program run using the Exec() method.
Object.ExitCode

Parameters
Object
WshScriptExec Object
Remarks
Executables set an exit code when they finish running. This conveys the status information when a process ends. Often, it is used to send an error code (or some other piece of information) back to the caller. If the process has not
finished, the ExitCode property returns 0. The values returned from ExitCode depend on the application that was called.
Example
The following code shows an example of the ExitCode property.
[VBScript]
Dim WshShell, oExec
Set WshShell = CreateObject("WScript.Shell")
Set oExec
= WshShell.Exec("%comspec% /c dire")
Function ReadAllFromAny(oExec)
If Not oExec.StdOut.AtEndOfStream Then
ReadAllFromAny = oExec.StdOut.ReadAll
Exit Function
End If
If Not oExec.StdErr.AtEndOfStream Then
ReadAllFromAny = oExec.StdErr.ReadAll
Exit Function
End If

ReadAllFromAny = -1
End Function
Dim allInput, tryCount
allInput = ""
tryCount = 0
Do While True
Dim input
input = ReadAllFromAny(oExec)
If -1 = input Then
If tryCount > 10 And oExec.Status = 1 Then
Exit Do
End If
tryCount = tryCount + 1
WScript.Sleep 100
Else
allInput = allInput & input
tryCount = 0
End If
Loop
If oExec.ExitCode <> 0 Then
WScript.Echo "Warning: Non-zero exit code"
End If
WScript.Echo allInput

[JScript]
var WshShell = new ActiveXObject("WScript.Shell");
var oExec
= WshShell.Exec("%comspec% /c dire");
function ReadAllFromAny(oExec)
{
if (!oExec.StdOut.AtEndOfStream)
return oExec.StdOut.ReadAll();
if (!oExec.StdErr.AtEndOfStream)
return oExec.StdErr.ReadAll();
return -1;
}
var allInput = "";
var tryCount = 0;
while (true)
{
var input = ReadAllFromAny(oExec);
if (-1 == input)
{
if (tryCount++ > 10 && oExec.Status == 1)
break;
WScript.Sleep(100);
}
else
{
allInput += input;
tryCount = 0;
}
}
if (oExec.ExitCode != 0)
{
WScript.Echo("Warning: Non-zero exit code");
}
WScript.Echo(allInput);

See Also
Exec Method | WshScriptExec Object

2001 Microsoft Corporation. All rights reserved.


Build: Topic Version 5.6.9309.1546
Windows Script Host

FullName Property (WScript Object)


Returns the fully qualified path of the host executable (CScript.exe or WScript.exe).
object.FullName

Arguments
object
WScript object.
Remarks
The FullName property is a read-only string representing the fully qualified path of the host executable.
Example
The following JScript code uses the FullName property:
WScript.Echo (WScript.FullName);

produces the following output.


C:\WINNT\System32\cscript.exe

See Also
Path Property | WScript Object | WshShortcut Object | WshUrlShortcut Object

2001 Microsoft Corporation. All rights reserved.

Build: Topic Version 5.6.9309.1546


Windows Script Host

FullName Property (WshShortcut Object)


Returns the fully qualified path of the shortcut object's target.
object.FullName

Arguments
object
WshShortcut object.
Remarks
The FullName property contains a read-only string value indicating the fully qualified path to the shortcut's target.
Example
The following code retrieves the fully qualified path of a shortcut.
[VBScript]
set WshShell = WScript.CreateObject("WScript.Shell")
strDesktop = WshShell.SpecialFolders("Desktop")
set oShellLink = WshShell.CreateShortcut(strDesktop & "\Shortcut Script.lnk")
oShellLink.TargetPath = WScript.ScriptFullName
oShellLink.WindowStyle = 1
oShellLink.Hotkey = "CTRL+SHIFT+F"
oShellLink.IconLocation = "notepad.exe, 0"
oShellLink.Description = "Shortcut Script"
oShellLink.WorkingDirectory = strDesktop
oShellLink.Save
WScript.Echo oShellLink.FullName

[JScript]
var WshShell = new ActiveXObject("WScript.Shell");
strDesktop = WshShell.SpecialFolders("Desktop");
var oShellLink = WshShell.CreateShortcut(strDesktop + "\\Shortcut Script.lnk");
oShellLink.TargetPath = WScript.ScriptFullName;
oShellLink.WindowStyle = 1;
oShellLink.Hotkey = "CTRL+SHIFT+F";
oShellLink.IconLocation = "notepad.exe, 0";
oShellLink.Description = "Shortcut Script";
oShellLink.WorkingDirectory = strDesktop;
oShellLink.Save();
WScript.Echo(oShellLink.FullName);

See Also
Path Property | WScript Object | WshShortcut Object | WshUrlShortcut Object

2001 Microsoft Corporation. All rights reserved.


Build: Topic Version 5.6.9309.1546
Windows Script Host

FullName Property (WshUrlShortcut Object)


Returns the fully qualified path of the shortcut object's target.
object.FullName

Arguments
object
WshUrlShortcut object.
Remarks
String. Read-only.
The FullName property is a read-only string representing the fully qualified path to the shortcut's target.
Example
The following code retrieves the fully qualified path of a URL shortcut.
[VBScript]
set oUrlLink = WshShell.CreateShortcut(strDesktop & "\Microsoft Web Site.url")
oUrlLink.TargetPath = "http://www.microsoft.com"
oUrlLink.Save
WScript.Echo oUrlLink.FullName

[JScript]
var oUrlLink = WshShell.CreateShortcut(strDesktop + "\\Microsoft Web Site.url");
oUrlLink.TargetPath = "http://www.microsoft.com";
oUrlLink.Save();
WScript.Echo (oUrlLink.FullName);

See Also
Path Property | WScript Object | WshShortcut Object | WshUrlShortcut Object

2001 Microsoft Corporation. All rights reserved.


Build: Topic Version 5.6.9309.1546
Windows Script Host

Hotkey Property
Assigns a key-combination to a shortcut, or identifies the key-combination assigned to a shortcut.
object.Hotkey = strHotkey

Arguments
object
WshShortcut object.
strHotkey
A string representing the key-combination to assign to the shortcut.
Syntax
The syntax of strHotkey is:
[KeyModifier]KeyName

KeyModifier
Can be any one of the following: ALT+, CTRL+, SHIFT+, EXT+.
Note EXT+ means "Extended key." it appears here in case a new type of SHIFT-key is added to the character set in the future.
KeyName
a ... z, ...
0 9, F1 F12, ...
The KeyName is not case-sensitive.
Remarks
A hotkey is a combination of keys that starts a shortcut when all associated keys are held down at the same time.

Hotkeys can be used to start shortcuts located on your system's desktop and in the Windows Start menu.
Note

Another name for a hotkey is K


a eyboard Shortcut.

In Windows 2000, valid Hotkeys always begin with CTRL + ALT.


Example
The following example demonstrates the use of the HotKey property.
<package>
<job id="vbs">
<script language="VBScript">
set WshShell = WScript.CreateObject("WScript.Shell")
strDesktop = WshShell.SpecialFolders("Desktop")
set oShellLink = WshShell.CreateShortcut(strDesktop & "\Shortcut Script.lnk")
oShellLink.TargetPath = WScript.ScriptFullName
oShellLink.WindowStyle = 1
oShellLink.Hotkey = "Ctrl+Alt+e"
oShellLink.IconLocation = "notepad.exe, 0"
oShellLink.Description = "Shortcut Script"
oShellLink.WorkingDirectory = strDesktop
oShellLink.Save
</script>
</job>
<job id="js">
<script language="JScript">
var WshShell = WScript.CreateObject("WScript.Shell");
strDesktop = WshShell.SpecialFolders("Desktop");
var oShellLink = WshShell.CreateShortcut(strDesktop + "\\Shortcut Script.lnk");
oShellLink.TargetPath = WScript.ScriptFullName;
oShellLink.WindowStyle = 1;
oShellLink.Hotkey = "Ctrl+Alt+e";
oShellLink.IconLocation = "notepad.exe, 0";
oShellLink.Description = "Shortcut Script";
oShellLink.WorkingDirectory = strDesktop;
oShellLink.Save();
</script>
</job>
</package>

See Also
Running Your Scripts | Running Your Scripts | WshSpecialFolders Object | WshShortcut Object

2001 Microsoft Corporation. All rights reserved.


Build: Topic Version 5.6.9309.1546
Windows Script Host

IconLocation Property
Assigns an icon to a shortcut, or identifies the icon assigned to a shortcut.
object.IconLocation = strIconLocation

Arguments
object
WshShortcut object.
strIconLocation
A string that locates the icon. The string should contain a fully qualified path and an index associated with the icon. See example for more details.
Remarks
String.
Example
The following example demonstrates the use of the IconLocation property.
<package>
<job id="vbs">
<script language="VBScript">

set WshShell = WScript.CreateObject("WScript.Shell")


strDesktop = WshShell.SpecialFolders("Desktop")
set oShellLink = WshShell.CreateShortcut(strDesktop & "\Shortcut Script.lnk")
oShellLink.TargetPath = WScript.ScriptFullName
oShellLink.WindowStyle = 1
oShellLink.Hotkey = "Ctrl+Alt+e"
oShellLink.IconLocation = "notepad.exe, 0" 'Zero is the index
oShellLink.Description = "Shortcut Script"
oShellLink.WorkingDirectory = strDesktop
oShellLink.Save
</script>
</job>
<job id="js">
<script language="JScript">
var WshShell = WScript.CreateObject("WScript.Shell");
strDesktop = WshShell.SpecialFolders("Desktop");
var oShellLink = WshShell.CreateShortcut(strDesktop + "\\Shortcut Script.lnk");
oShellLink.TargetPath = WScript.ScriptFullName;
oShellLink.WindowStyle = 1;
oShellLink.Hotkey = "Ctrl+Alt+e";
oShellLink.IconLocation = "notepad.exe, 0"; //Zero is the index
oShellLink.Description = "Shortcut Script";
oShellLink.WorkingDirectory = strDesktop;
oShellLink.Save();
</script>
</job>
</package>

See Also
Running Your Scripts | WshShortcut Object

2001 Microsoft Corporation. All rights reserved.


Build: Topic Version 5.6.9309.1546
Windows Script Host

Interactive Property
Sets the script mode, or identifies the script mode.
object.Interactive

Arguments
object
WScript object.
Remarks
The Interactive Property returns a Boolean value.
There are two modes, batch and interactive. In interactive mode (the default), the script provides user interaction. Input to and output from the Windows Script Host is enabled. The script can echo information to dialog boxes
and can wait for the user to provide feedback. In batch mode, this type of user interaction is not supported all input and output to WSH is disabled. You can also set the script mode using the Windows Script Host command
line switches //I (for Interactive), and //B (for Batch).
Example
The following JScript code displays the script mode.
WScript.Echo WScript.Interactive;

The following JScript code sets the script mode to batch.


WScript.Interactive = false;

See Also
WScript Object

2001 Microsoft Corporation. All rights reserved.


Build: Topic Version 5.6.9309.1546
Windows Script Host

Item Property
Exposes a specified item from a collection.
Object.Item(natIndex)

Arguments
Object
The result of the EnumNetworkDrive or EnumPrinterConnections methods, or the object returned by the Environment or SpecialFolders properties.
natIndex
Item to retrieve.
Remarks
Item is the default property for each collection. For EnumNetworkDrive and EnumPrinterConnections collections, index is an integer; for the Environment and SpecialFolders collections, index is a string.
WshShell.SpecialFolders.Item (strFolderName) returns "Empty" in VBScript and "undefined" in JScript if the requested folder (strFolderName) is not available.
The following table lists special folders along with the version of Windows that supports them.
Folder
AllUsersDesktop
AllUsersStartMenu
AllUsersPrograms
AllUsersStartup
Desktop

Windows version
Windows 2000
Windows 2000
Windows 2000
Windows 2000
Windows 98/ME, Windows 2000

Favorites
Fonts
My Documents
NetHood
PrintHood
Programs
Recent
SendTo
Start Menu
StartupB
Templates

Windows 98/ME, Windows 2000


Windows 98/ME, Windows 2000
Windows 98/ME, Windows 2000
Windows 98/ME, Windows 2000
Windows 98/ME, Windows 2000
Windows 98/ME, Windows 2000
Windows 98/ME, Windows 2000
Windows 98/ME, Windows 2000
Windows 98/ME, Windows 2000
Windows 2000
Windows 2000

Example
The following code displays network mapping information for the drives and printers.
<package>
<job id="vbs">
<script language="VBScript">
Set WshNetwork = WScript.CreateObject("WScript.Network")
Set oDrives = WshNetwork.EnumNetworkDrives
Set oPrinters = WshNetwork.EnumPrinterConnections
WScript.Echo "Network drive mappings:"
For i = 0 to oDrives.Count - 1 Step 2
WScript.Echo "Drive " & oDrives.Item(i) & " = " & oDrives.Item(i+1)
Next
WScript.Echo
WScript.Echo "Network printer mappings:"
For i = 0 to oPrinters.Count - 1 Step 2
WScript.Echo "Port " & oPrinters.Item(i) & " = " & oPrinters.Item(i+1)
Next
</script>
</job>
<job id="js">
<script language="JScript">
var WshNetwork = WScript.CreateObject("WScript.Network");
var oDrives = WshNetwork.EnumNetworkDrives();
var oPrinters = WshNetwork.EnumPrinterConnections();
WScript.Echo();
WScript.Echo("Network drive mappings:");
for(i = 0; i < oDrives.length; i += 2){
WScript.Echo("Drive " + oDrives.Item(i) + " = " + oDrives.Item(i + 1));
}
WScript.Echo();
WScript.Echo("Network printer mappings:");
for(i = 0; i < oPrinters.length; i += 2){
WScript.Echo("Port " + oPrinters.Item(i) + " = " + oPrinters.Item(i + 1));
}
</script>
</job>
</package>

See Also
EnumNetworkDrive Method | EnumPrinterConnections Method | Environment Property | SpecialFolders Property

2001 Microsoft Corporation. All rights reserved.


Build: Topic Version 5.6.9309.1546
Windows Script Host

Item Property (WshNamed)


Provides access to the items in the WshNamed object.
Object.Item(key)

Parameters
Object
WshNamed object
key
The name of the item you want to retrieve.
Remarks
The Item property returns a string. For collections, it returns an item based on the specified key. When entering the arguments at the command line, you can use blanks in string arguments if you enclose the string in quotes.
Consider the following example:
myscript.vbs /stringarg:"This string has spaces"

The quotes will be removed in the WshNamed collection. For an argument to be in the WshNamed collection, it must have been used on the command line. If the argument has no value (such as a simple argument or an empty
string), the Item property returns an empty string. Requesting a non-existent named argument from the Item property causes an error. To check if an argument exists, use the Exists method.
Example 1
In the following example, two named arguments are supplied to run a script. Inside the script, code causes the named arguments to be output. The Item property is used to index into the named arguments collection.
The following line is typed at the command prompt to run the script.
myScript.vbs /c:arg1 /d:arg2

If the following code is executed inside the script:


WScript.Echo WScript.Arguments.Named.Item("c")
WScript.Echo WScript.Arguments.Named.Item("d")

then the following output is produced:


arg1
arg2

See Also
WshNamed Object | WshUnnamed Object | Count Method | Item Property | Exists Method

2001 Microsoft Corporation. All rights reserved.


Build: Topic Version 5.6.9309.1546
Windows Script Host

Item Property (WshUnnamed)


Returns an item using a zero-based index.
Object.Item(key)

Parameters
Object
WshUnnamed object.
key
Associated with either a collection or a WshUnnamed object.
Remarks
The Item property returns a string. For collections, it returns an item based on the specified key.
For the unnamed object, items are not named, so you cannot pass the name of the WshUnnamed argument.
The WshUnnamed argument items are stored in the order that they were included on the command line.
When entering the WshUnnamed argument at the command line, you can use blanks in string arguments if you enclose them in quotes.
The quotes are removed in the WshUnnamed collection.
Example
The following example demonstrates how the Item property can be used to return items in the WshUnnamed collection. In this example, two unnamed arguments are supplied to run a script. Inside the script, code causes the
unnamed arguments to be output. The Item property is used to index into the unnamed arguments collection.
The following line is typed at the command prompt to run the script.
myScript.vbs arg1 arg2

When the following code is executed inside the script:


WScript.Echo WScript.Arguments.Unnamed.Item(0)
WScript.Echo WScript.Arguments.Unnamed.Item(1)

the following output is produced:


arg1
arg2

See Also
Arguments Property | WshUnnamed Object | WshUnnamed Object | Count Method | Item Property (WshNamed) | Exists Method

2001 Microsoft Corporation. All rights reserved.


Build: Topic Version 5.6.9309.1546
Windows Script Host

length Property (WshArguments object)


Returns the number of command-line parameters belonging to a script (the number of items in an argument's collection).
object.length

Arguments
object
WshArguments object.
Remarks
The length property is a read-only integer that you use in scripts when you write in JScript. It is similar to VBScript's Count method.
See Also
WshArguments Object | Arguments Property | Count Method

2001 Microsoft Corporation. All rights reserved.


Build: Topic Version 5.6.9309.1546
Windows Script Host

length Property (WshEnvironment object)


Returns the number of Windows environment variables on the local computer system (the number of items in an Environment collection).
object.length

Arguments
object
WshEnvironment object.
Remarks
The length property is a read-only integer that you use in scripts when you write in JScript. It is similar to VBScript's Count method.

See Also
WshEnvironment Object | Count Method

2001 Microsoft Corporation. All rights reserved.


Build: Topic Version 5.6.9309.1546
Windows Script Host

length Property (WshSpecialFolders object)


Returns the number of Windows special folders on the local computer system (the number of items in a SpecialFolders collection).
object.length

Arguments
object
WshSpecialFolders object.
Remarks
The length property is a read-only integer that you use in scripts when you write in JScript. It is similar to VBScript's Count method.
See Also
WshSpecialFolders Object | Count Method

2001 Microsoft Corporation. All rights reserved.


Build: Topic Version 5.6.9309.1546
Windows Script Host

Line Property (WScript)


Returns the current line number in an input stream.
object.strStream.Line

Arguments
object
WScript object.
strStream
StdIn property.
Remarks
The Line property is a read-only integer.
After a stream is first opened, Line will initially be 1.
The StdIn, StdOut, and StdErr properties and methods work only when the script is run with CScript.exe. If the script is run with WScript.exe, an error occurs.
Example
The following code demonstrates the use of the Line property.
[VBScript]
Dim StdIn, StdOut
Set StdIn = WScript.StdIn
Set StdOut = WScript.StdOut
Do While Not StdIn.AtEndOfStream
str = StdIn.ReadLine
StdOut.WriteLine "Line " & (StdIn.Line - 1) & ": " & str
Loop

[JScript]
var stdin = WScript.StdIn;
var stdout = WScript.StdOut;
while (!stdin.AtEndOfStream)
{
var str = stdin.ReadLine();
stdout.WriteLine("Line " + (stdin.Line - 1) + ": " + str);
}

See Also
Error Messages | StdIn Property

2001 Microsoft Corporation. All rights reserved.


Build: Topic Version 5.6.9309.1546
Windows Script Host

Line Property (WshRemoteError)


Identifies the line in a script that contains an error.
Object.Line

Arguments

Object
WshRemoteError object.
Remarks
The Line property returns an unsigned long integer.
Notice that some errors do not occur on a particular line. For example, consider the error Expected End If. In this case, there is no line (a line of code is missing). In such a case, the Line property returns zero (0).
Example
The following JScript code demonstrates how the WshRemoteError object exposes the line in which the error occurred.
[VBScript]
Dim Controller, RemoteScript
Set Controller = WScript.CreateObject("WSHController")
Set RemoteScript = Controller.CreateScript("test.js", "remoteserver")
WScript.ConnectObject RemoteScript, "remote_"
RemoteScript.Execute
Do While RemoteScript.Status <> 2
WScript.Sleep 100
Loop
Sub remote_Error
Dim theError
Set theError = RemoteScript.Error
WScript.Echo "Error - Line: " & theError.Line & ", Char: " & theError.Character & vbCrLf & "Description: " & theError.Description
WScript.Quit -1
End Sub

[JScript]
var Controller = WScript.CreateObject("WSHController");
var RemoteScript = Controller.CreateScript("test.js", "remoteserver");
WScript.ConnectObject(RemoteScript, "remote_");
RemoteScript.Execute();
while (RemoteScript.Status != 2) {
WScript.Sleep(100);
}
function remote_Error()
{
var theError = RemoteScript.Error;
WScript.Echo("Error - Line: " + theError.Line + ", Char: " + theError.Character + "\nDescription: " + theError.Description);
WScript.Quit(-1);
}

See Also
WshRemote Object | WshRemoteError Object | Character Property | Description Property | Line Property | SourceText Property | Number Property | Source Property

2001 Microsoft Corporation. All rights reserved.


Build: Topic Version 5.6.9309.1546
Windows Script Host

Name Property (WScript Object)


Returns the name of the WScript object (the host executable file).
object.Name

Arguments
object
WScript object.
Remarks
The Name property is a read-only string.
Example
The following JScript code shows how to use the Name property.
WScript.Echo (WScript.Name);

See Also
WScript Object

2001 Microsoft Corporation. All rights reserved.


Build: Topic Version 5.6.9309.1546
Windows Script Host

Named Property
Returns the WshNamed object (a collection of named arguments).
Object.Named

Parameters
Object
WshArguments object.
Remarks
The Named property returns the WshNamed collection, the collection of named arguments. Use the name of the argument to find out if the argument was included and to access its value.

Example
The following code displays the number of named and unnamed command-line arguments.
<package>
<job id="JS">
<script language="JScript">
var argsNamed = WScript.Arguments.Named;
var argsUnnamed = WScript.Arguments.Unnamed;
WScript.Echo("There are " + argsNamed.length + " named arguments.");
WScript.Echo("There are " + argsUnnamed.length + " unnamed arguments.");
</script>
</job>
<job id="VBS">
<script language="VBScript">
Dim argsNamed, argsUnnamed
Set argsNamed = WScript.Arguments.Named
Set argsUnnamed = WScript.Arguments.Unnamed
WScript.Echo "There are " & argsNamed.Count & " named arguments."
WScript.Echo "There are " & argsUnnamed.Count & " unnamed arguments."
</script>
</job>
</package>

See Also
WshArguments Object | WshNamed Object | Unnamed Property

2001 Microsoft Corporation. All rights reserved.


Build: Topic Version 5.6.9309.1546
Windows Script Host

Number Property
Reports the error number representing a script error.
Object.Number

Arguments
Object
WshRemoteError object.
Remarks
That Number property returns an unsigned long integer.
Example
The following JScript code demonstrates how the WshRemoteError object exposes the error number.
[VBScript]
Dim Controller, RemoteScript
Set Controller = WScript.CreateObject("WSHController")
Set RemoteScript = Controller.CreateScript("test.js", "remoteserver")
WScript.ConnectObject RemoteScript, "remote_"
RemoteScript.Execute
Do While RemoteScript.Status <> 2
WScript.Sleep 100
Loop
Sub remote_Error
Dim theError
Set theError = RemoteScript.Error
WScript.Echo "Error " & theError.Number & " - Line: " & theError.Line & ", Char: " & theError.Character & vbCrLf & "Description: " & theError.Description
WScript.Quit -1
End Sub

[JScript]
var Controller = WScript.CreateObject("WSHController");
var RemoteScript = Controller.CreateScript("test.js", "remoteserver");
WScript.ConnectObject(RemoteScript, "remote_");
RemoteScript.Execute();
while (RemoteScript.Status != 2) {
WScript.Sleep(100);
}
function remote_Error()
{
var theError = RemoteScript.Error;
WScript.Echo("Error " + theError.Number + " - Line: " + theError.Line + ", Char: " + theError.Character + "\nDescription: " + theError.Description);
WScript.Quit(-1);
}

See Also
WshRemote Object | WshRemoteError Object | Description Property | Line Property | Character Property| SourceText Property| Source Property

2001 Microsoft Corporation. All rights reserved.


Build: Topic Version 5.6.9309.1546
Windows Script Host

Path Property
Returns the name of the directory containing the host executable (CScript.exe or WScript.exe).

object.Path

Arguments
object
WScript object.
Remarks
The Path property is a read-only string.
Example
The following VBScript code echoes the directory where the executable file resides.
WScript.Echo (WScript.Path);

See Also
FullName Property | WScript Object

2001 Microsoft Corporation. All rights reserved.


Build: Topic Version 5.6.9309.1546
Windows Script Host

ProcessID Property
The process ID (PID) for a process started with the WshScriptExec object.
Object.ProcessID

Parameters
Object
WshScriptExec object.
Remarks
You can use the ProcessID property to activate an application (as an argument to the AppActivate method).
Example
The following code uses the ProcessID property to activate the calculator and notepad applications.
[VBScript]
Sub delayedSendKeys(str)
WScript.Sleep 100
WshShell.SendKeys str
End Sub
Dim WshShell, oCalc, oNotepad
Set WshShell = CreateObject("WScript.Shell")
Set oCalc = WshShell.Exec("calc")
Set oNotepad = WshShell.Exec("notepad")
WScript.Sleep 500
WshShell.AppActivate oCalc.ProcessID
delayedSendKeys "1{+}1~"
delayedSendKeys "^C"
delayedSendKeys "%{F4}"
WshShell.AppActivate oNotepad.ProcessID
delayedSendKeys "1 {+} 1 = ^V"

[JScript]
function delayedSendKeys(str)
{
WScript.Sleep(100);
WshShell.SendKeys(str);
}
var WshShell = new ActiveXObject("WScript.Shell");
var oCalc = WshShell.Exec("calc");
var oNotepad = WshShell.Exec("notepad");
WScript.Sleep(500);
WshShell.AppActivate(oCalc.ProcessID);
delayedSendKeys("1{+}1~");
delayedSendKeys("^C");
delayedSendKeys("%{F4}");
WshShell.AppActivate(oNotepad.ProcessID);
delayedSendKeys("1 {+} 1 = ^V");

See Also
WshScriptExec Object | AppActivate Method

2001 Microsoft Corporation. All rights reserved.


Build: Topic Version 5.6.9309.1546
Windows Script Host

RelativePath Property
Assigns a relative path to a shortcut, or identifies the relative path of a shortcut.
object.RelativePath

Arguments
object

WshShortcut object.
Remarks
String.
Example
The following code sets the relative path of a shortcut.
[VBScript]
Dim WshShell, WshShortcut
Set WshShell = WScript.CreateObject ("WScript.Shell")
Set WshShortcut = WshShell.CreateShortcut("MyScript.lnk")
WshShortcut.RelativePath = "C:\Scripts\"

[JScript]
var WshShell = WScript.CreateObject ("WScript.Shell");
var WshShortcut = WshShell.CreateShortcut("MyScript.lnk");
WshShortcut.RelativePath = "C:\\Scripts\\";

See Also
WshShortcut Object

2001 Microsoft Corporation. All rights reserved.


Build: Topic Version 5.6.9309.1546
Windows Script Host

ScriptFullName Property
Returns the full path of the currently running script.
object.ScriptFullName

Arguments
object
WScript object.
Remarks
The ScriptFullName property is a read-only string.
Example
The following example demonstrates the use of the ScriptFullName property.
<package>
<job id="vbs">
<script language="VBScript">
set WshShell = WScript.CreateObject("WScript.Shell")
strDesktop = WshShell.SpecialFolders("Desktop")
set oShellLink = WshShell.CreateShortcut(strDesktop & "\Shortcut Script.lnk")
oShellLink.TargetPath = WScript.ScriptFullName
oShellLink.WindowStyle = 1
oShellLink.Hotkey = "Ctrl+Alt+e"
oShellLink.IconLocation = "notepad.exe, 0"
oShellLink.Description = "Shortcut Script"
oShellLink.WorkingDirectory = strDesktop
oShellLink.Save
set oUrlLink = WshShell.CreateShortcut(strDesktop & "\Microsoft Web Site.url")
oUrlLink.TargetPath = "http://www.microsoft.com"
oUrlLink.Save
</script>
</job>
<job id="js">
<script language="JScript">
var WshShell = WScript.CreateObject("WScript.Shell");
strDesktop = WshShell.SpecialFolders("Desktop");
var oShellLink = WshShell.CreateShortcut(strDesktop + "\\Shortcut Script.lnk");
oShellLink.TargetPath = WScript.ScriptFullName;
oShellLink.WindowStyle = 1;
oShellLink.Hotkey = "Ctrl+Alt+e";
oShellLink.IconLocation = "notepad.exe, 0";
oShellLink.Description = "Shortcut Script";
oShellLink.WorkingDirectory = strDesktop;
oShellLink.Save();
var oUrlLink = WshShell.CreateShortcut(strDesktop + "\\Microsoft Web Site.url");
oUrlLink.TargetPath = "http://www.microsoft.com";
oUrlLink.Save();
</script>
</job>
</package>

See Also
Running Your Scripts | ScriptName Property | WScript Object

2001 Microsoft Corporation. All rights reserved.


Build: Topic Version 5.6.9309.1546
Windows Script Host

ScriptName Property
Returns the file name of the currently running script.
object.ScriptName

Arguments

object
WScript object.
Remarks
The ScriptName property is a read-only string.
Example
The following VBScript code echoes the name of the script being run.
WScript.Echo WScript.ScriptName

See Also
ScriptFullName Property | WScript Object

2001 Microsoft Corporation. All rights reserved.


Build: Topic Version 5.6.9309.1546
Windows Script Host

Source Property
Identifies the COM object responsible for causing the script error.
Object.Source

Arguments
Object
WshRemoteError object.
Remarks
The Source property returns a string.
Example
The following JScript code demonstrates how the WshRemoteError object exposes the COM object responsible for causing the script error.
[VBScript]
Dim Controller, RemoteScript
Set Controller = WScript.CreateObject("WSHController")
Set RemoteScript = Controller.CreateScript("test.js", "remoteserver")
WScript.ConnectObject RemoteScript, "remote_"
RemoteScript.Execute
Do While RemoteScript.Status <> 2
WScript.Sleep 100
Loop
Sub remote_Error
Dim theError
Set theError = RemoteScript.Error
WScript.Echo "Error - Line: " & theError.Line & ", Char: " & theError.Character & vbCrLf & "Description: " & theError.Description & vbCrLf & "Source: " & theError.Source
WScript.Quit -1
End Sub

[JScript]
var Controller = WScript.CreateObject("WSHController");
var RemoteScript = Controller.CreateScript("test.js", "remoteserver");
WScript.ConnectObject(RemoteScript, "remote_");
RemoteScript.Execute();
while (RemoteScript.Status != 2) {
WScript.Sleep(100);
}
function remote_Error()
{
var theError = RemoteScript.Error;
WScript.Echo("Error - Line: " + theError.Line + ", Char: " + theError.Character + "\nDescription: " + theError.Description + "\nSource: " + theError.Source);
WScript.Quit(-1);
}

See Also
WshRemote Object | WshRemoteError Object | Description Property | Line Property | Character Property| SourceText Property | Number Property

2001 Microsoft Corporation. All rights reserved.


Build: Topic Version 5.6.9309.1546
Windows Script Host

SourceText Property
Contains the line of source code that caused an error.
Object.SourceText

Arguments
Object
WshRemoteError object.
Remarks
The SourceText property returns a string.
It is not always possible to obtain the source text. If that is the case, the SourceText property returns an empty string.

Example
The following JScript code demonstrates how the WshRemoteError object exposes the line of source code that caused an error.
[VBScript]
Dim Controller, RemoteScript
Set Controller = WScript.CreateObject("WSHController")
Set RemoteScript = Controller.CreateScript("test.js", "remoteserver")
WScript.ConnectObject RemoteScript, "remote_"
RemoteScript.Execute
Do While RemoteScript.Status <> 2
WScript.Sleep 100
Loop
Sub remote_Error
Dim theError
Set theError = RemoteScript.Error
WScript.Echo "Error - Line: " & theError.Line & ", Char: " & theError.Character & vbCrLf & "Description: " & theError.Description & vbCrLf & "Source Text: " & theError.SourceText
WScript.Quit -1
End Sub

[JScript]
var Controller = WScript.CreateObject("WSHController");
var RemoteScript = Controller.CreateScript("test.js", "remoteserver");
WScript.ConnectObject(RemoteScript, "remote_");
RemoteScript.Execute();
while (RemoteScript.Status != 2) {
WScript.Sleep(100);
}
function remote_Error()
{
var theError = RemoteScript.Error;
WScript.Echo("Error - Line: " + theError.Line + ", Char: " + theError.Character + "\nDescription: " + theError.Description + "\nSource Text: "_+ theError.SourceText);
WScript.Quit(-1);
}

See Also
WshRemote Object | WshRemoteError Object | Description Property | Line Property | Character Property| Number Property | Source Property

2001 Microsoft Corporation. All rights reserved.


Build: Topic Version 5.6.9309.1546
Windows Script Host

SpecialFolders Property
Returns a SpecialFolders object (a collection of special folders).
object.SpecialFolders(objWshSpecialFolders)

Arguments
object
WshShell object.
objWshSpecialFolders
The name of the special folder.
Remarks
The WshSpecialFolders object is a collection. It contains the entire set of Windows special folders, such as the Desktop folder, the Start Menu folder, and the Personal Documents folder. The special folder name is used to index
into the collection to retrieve the special folder you want. The SpecialFolders property returns an empty string if the requested folder (strFolderName) is not available. For example, Windows 95 does not have an
AllUsersDesktop folder and returns an empty string if strFolderNameis AllUsersDesktop.
The following special folders are available:

AllUsersDesktop
AllUsersStartMenu
AllUsersPrograms
AllUsersStartup
Desktop
Favorites
Fonts
MyDocuments
NetHood
PrintHood
Programs
Recent
SendTo
StartMenu
Startup
Templates

Example
The following example demonstrates the use of the SpecialFolders property:
<package>
<job id="vbs">
<script language="VBScript">
set WshShell = WScript.CreateObject("WScript.Shell")
strDesktop = WshShell.SpecialFolders("Desktop")
set oShellLink = WshShell.CreateShortcut(strDesktop & "\Shortcut Script.lnk")
oShellLink.TargetPath = WScript.ScriptFullName
oShellLink.WindowStyle = 1
oShellLink.Hotkey = "Ctrl+Alt+e"
oShellLink.IconLocation = "notepad.exe, 0"
oShellLink.Description = "Shortcut Script"
oShellLink.WorkingDirectory = strDesktop
oShellLink.Save
set oUrlLink = WshShell.CreateShortcut(strDesktop & "\Microsoft Web Site.url")
oUrlLink.TargetPath = "http://www.microsoft.com"
oUrlLink.Save
</script>
</job>
<job id="js">
<script language="JScript">

var WshShell = WScript.CreateObject("WScript.Shell");


strDesktop = WshShell.SpecialFolders("Desktop");
var oShellLink = WshShell.CreateShortcut(strDesktop + "\\Shortcut Script.lnk");
oShellLink.TargetPath = WScript.ScriptFullName;
oShellLink.WindowStyle = 1;
oShellLink.Hotkey = "Ctrl+Alt+e";
oShellLink.IconLocation = "notepad.exe, 0";
oShellLink.Description = "Shortcut Script";
oShellLink.WorkingDirectory = strDesktop;
oShellLink.Save();
var oUrlLink = WshShell.CreateShortcut(strDesktop + "\\Microsoft Web Site.url");
oUrlLink.TargetPath = "http://www.microsoft.com";
oUrlLink.Save();
</script>
</job>
</package>

See Also
Running Your Scripts | WshSpecialFolders Object | WshShell Object

2001 Microsoft Corporation. All rights reserved.


Build: Topic Version 5.6.9309.1546
Windows Script Host

Status Property (WshRemote)


Reports the current status of the remote script.
Object.Status

Arguments
Object
WshRemote object.
Remarks
The Status property returns a read-only enumerated data type.
Values
The Status property returns one of three possible values.
Return Value
NoTask
Running
Finished

Numeric value
0
1
2

Description
The remote script object has been created but has not yet executed.
The remote script object is currently running.
The remote script object has finished running.

Example
The following JScript code demonstrates how to use the Status property in a test block that checks to see if a remote script terminated normally.
[VBScript]
Dim Controller, RemoteScript
Set Controller = WScript.CreateObject("WSHController")
Set RemoteScript = Controller.CreateScript("test.js", "remoteserver")
RemoteScript.Execute
Do While RemoteScript.Status <> 2
WScript.Sleep 100
Loop

[JScript]
var Controller = WScript.CreateObject("WSHController");
var RemoteScript = Controller.CreateScript("test.js", "remoteserver");
RemoteScript.Execute();
while (RemoteScript.Status != 2) {
WScript.Sleep(100);
}

See Also
WshController Object | WshRemote Object | Error Property | Execute Method | Terminate Method | Start Event | End Event | Error Event

2001 Microsoft Corporation. All rights reserved.


Build: Topic Version 5.6.9309.1546
Windows Script Host

Status Property (WshScriptExec)


Provides status information about a script run with the Exec() method.
Object.Status

Arguments
Object
WshScriptExec object.
Remarks
The Status property is used when a program is run asynchronously.
Return Values
The Status property returns a value from an enumerated type.

WshRunning ( = 0)
The job is still running.
WshFinished ( = 1)
The job has completed.
Example
The following code runs calc.exe and echoes the final status to the screen.
[VBScript]
Dim WshShell, oExec
Set WshShell = CreateObject("WScript.Shell")
Set oExec = WshShell.Exec("calc")
Do While oExec.Status = 0
WScript.Sleep 100
Loop
WScript.Echo oExec.Status

[JScript]
var WshShell = new ActiveXObject("WScript.Shell");
var oExec = WshShell.Exec("calc");
while (oExec.Status == 0)
{
WScript.Sleep(100);
}
WScript.Echo(oExec.Status);

See Also
Exec Method | WshScriptExec Object

2001 Microsoft Corporation. All rights reserved.


Build: Topic Version 5.6.9309.1546
Windows Script Host

StdErr Property (WScript)


Exposes the write-only error output stream for the current script.
object.StdErr

Arguments
object
WScript object.
Remarks
The StdErr property returns an object representing the standard error stream. The StdIn, StdOut, and StdErr streams can be accessed while using CScript.exe only. Attempting to access these streams while using WScript.exe
produces an error.
See Also
Error Messages | WScript Object

2001 Microsoft Corporation. All rights reserved.


Build: Topic Version 5.6.9309.1546
Windows Script Host

StdErr Property (WshScriptExec)


Provides access to the stderr output stream of the Exec object.
Object.StdErr

Arguments
Object
WshScriptExec object.
Remarks
Use the StdErr property to retrieve data sent to the stderr stream from a process started with Exec.
Example
The following code demonstrates the StdErr object by attempting to execute a non-existent command and displaying the results.
[VBScript]
Dim WshShell, oExec
Set WshShell = CreateObject("WScript.Shell")
Set oExec
= WshShell.Exec("%comspec% /c dire")
Function ReadAllFromAny(oExec)
If Not oExec.StdOut.AtEndOfStream Then
ReadAllFromAny = oExec.StdOut.ReadAll
Exit Function
End If
If Not oExec.StdErr.AtEndOfStream Then
ReadAllFromAny = "STDERR: " + oExec.StdErr.ReadAll
Exit Function
End If

ReadAllFromAny = -1
End Function
Dim allInput, tryCount
allInput = ""
tryCount = 0
Do While True
Dim input
input = ReadAllFromAny(oExec)
If -1 = input Then
If tryCount > 10 And oExec.Status = 1 Then
Exit Do
End If
tryCount = tryCount + 1
WScript.Sleep 100
Else
allInput = allInput & input
tryCount = 0
End If
Loop
WScript.Echo allInput

[JScript]
var WshShell = new ActiveXObject("WScript.Shell");
var oExec
= WshShell.Exec("%comspec% /c dire");
function ReadAllFromAny(oExec)
{
if (!oExec.StdOut.AtEndOfStream)
return oExec.StdOut.ReadAll();
if (!oExec.StdErr.AtEndOfStream)
return "STDERR: " + oExec.StdErr.ReadAll();
return -1;
}
var allInput = "";
var tryCount = 0;
while (true)
{
var input = ReadAllFromAny(oExec);
if (-1 == input)
{
if (tryCount++ > 10 && oExec.Status == 1)
break;
WScript.Sleep(100);
}
else
{
allInput += input;
tryCount = 0;
}
}
WScript.Echo(allInput);

See Also
WshScriptExec Object | StdIn Property | StdOut Property

2001 Microsoft Corporation. All rights reserved.


Build: Topic Version 5.6.9309.1546
Windows Script Host

StdIn Property (WScript)


Exposes the read-only input stream for the current script.
object.StdIn

Arguments
object
WScript object.
Remarks
The StdIn property returns an object representing the standard input stream. The StdIn, StdOut, and StdErr streams can be accessed while using CScript.exe only. Attempting to access these streams while using WScript.exe
produces an error.
See Also
Error Messages | WScript Object | Read Method | ReadAll Method | ReadLine Method | Skip Method | SkipLine Method | AtEndOfLine Property | Close Method | Column Property | Line Property (WScript)

2001 Microsoft Corporation. All rights reserved.


Build: Topic Version 5.6.9309.1546
Windows Script Host

StdIn Property (WshScriptExec)


Exposes the stdin input stream of the Exec object.
Object.StdIn

Arguments
Object
WshScriptExec object.

Remarks
Use the StdIn property to pass data to a process started using Exec.
Example
The following code starts a batch file and waits for the user input prompt. After entering the needed data through the StdIn stream, the batch file will be able to complete.
[VBScript]
Dim WshShell, oExec, input
Set WshShell = CreateObject("WScript.Shell")
Set oExec
= WshShell.Exec("test.bat")
input = ""
Do While True
If Not oExec.StdOut.AtEndOfStream Then
input = input & oExec.StdOut.Read(1)
If InStr(input, "Press any key") <> 0 Then Exit Do
End If
WScript.Sleep 100
Loop
oExec.StdIn.Write VbCrLf
Do While oExec.Status <> 1
WScript.Sleep 100
Loop

[JScript]
var WshShell = new ActiveXObject("WScript.Shell");
var oExec
= WshShell.Exec("test.bat");
var input = "";
while (true)
{
if (!oExec.StdOut.AtEndOfStream)
{
input += oExec.StdOut.Read(1);
if (input.indexOf("Press any key") != -1)
break;
}
WScript.Sleep(100);
}
oExec.StdIn.Write("\n");
while (oExec.Status != 1)
WScript.Sleep(100);

See Also
WshScriptExec Object | StdIn Property | StdErr Property

2001 Microsoft Corporation. All rights reserved.


Build: Topic Version 5.6.9309.1546
Windows Script Host

StdOut Property (WScript)


Exposes the write-only output stream for the current script.
object.StdOut

Arguments
object
WScript object.
Remarks
The StdOut property returns an object representing the standard output stream. The StdIn, StdOut, and StdErr streams can be accessed while using CScript.exe only. Attempting to access these streams while using
WScript.exe produces an error.
See Also
Error Messages | WScript Object | Write Method | WriteBlankLines Method | WriteLine Method | Close Method | Column Property | Line Property (WScript)

2001 Microsoft Corporation. All rights reserved.


Build: Topic Version 5.6.9309.1546
Windows Script Host

StdOut Property (WshScriptExec)


Exposes the write-only stdout output stream of the Exec object.
Object.StdOut

Arguments
Object
WshScriptExec object.
Remarks
The StdOut property contains a read-only copy of any information the script may have sent to the standard output.
Example
The following code starts a batch file and waits for the user input prompt. After entering the needed data through the StdIn stream, the batch file will be able to complete.

[VBScript]
Dim WshShell, oExec, input
Set WshShell = CreateObject("WScript.Shell")
Set oExec
= WshShell.Exec("test.bat")
input = ""
Do While True
If Not oExec.StdOut.AtEndOfStream Then
input = input & oExec.StdOut.Read(1)
If InStr(input, "Press any key") <> 0 Then Exit Do
End If
WScript.Sleep 100
Loop
oExec.StdIn.Write VbCrLf
Do While oExec.Status <> 1
WScript.Sleep 100
Loop

[JScript]
var WshShell = new ActiveXObject("WScript.Shell");
var oExec
= WshShell.Exec("test.bat");
var input = "";
while (true)
{
if (!oExec.StdOut.AtEndOfStream)
{
input += oExec.StdOut.Read(1);
if (input.indexOf("Press any key") != -1)
break;
}
WScript.Sleep(100);
}
oExec.StdIn.Write("\n");
while (oExec.Status != 1)
WScript.Sleep(100);

See Also
WshScriptExec Object | StdIn Property | StdErr Property

2001 Microsoft Corporation. All rights reserved.


Build: Topic Version 5.6.9309.1546
Windows Script Host

TargetPath Property
The path to the shortcut's executable.
object.TargetPath

Arguments
object
WshShortcut or WshUrlShortcut object.
Remarks
String.
This property is for the shortcut's target path only. Any arguments to the shortcut must be placed in the Argument's property.
Example
The following example demonstrates the use of the TargetPath property:
<package>
<job id="vbs">
<script language="VBScript">
set WshShell = WScript.CreateObject("WScript.Shell")
strDesktop = WshShell.SpecialFolders("Desktop")
set oShellLink = WshShell.CreateShortcut(strDesktop & "\Shortcut Script.lnk")
oShellLink.TargetPath = WScript.ScriptFullName
oShellLink.WindowStyle = 1
oShellLink.Hotkey = "Ctrl+Alt+e"
oShellLink.IconLocation = "notepad.exe, 0"
oShellLink.Description = "Shortcut Script"
oShellLink.WorkingDirectory = strDesktop
oShellLink.Save
set oUrlLink = WshShell.CreateShortcut(strDesktop & "\Microsoft Web Site.url")
oUrlLink.TargetPath = "http://www.microsoft.com"
oUrlLink.Save
</script>
</job>
<job id="js">
<script language="JScript">
var WshShell = WScript.CreateObject("WScript.Shell");
strDesktop = WshShell.SpecialFolders("Desktop");
var oShellLink = WshShell.CreateShortcut(strDesktop + "\\Shortcut Script.lnk");
oShellLink.TargetPath = WScript.ScriptFullName;
oShellLink.WindowStyle = 1;
oShellLink.Hotkey = "Ctrl+Alt+e";
oShellLink.IconLocation = "notepad.exe, 0";
oShellLink.Description = "Shortcut Script";
oShellLink.WorkingDirectory = strDesktop;
oShellLink.Save();
var oUrlLink = WshShell.CreateShortcut(strDesktop + "\\Microsoft Web Site.url");
oUrlLink.TargetPath = "http://www.microsoft.com";
oUrlLink.Save();
</script>
</job>
</package>

See Also
Running Your Scripts | WshShortcut Object | WshUrlShortcut Object

2001 Microsoft Corporation. All rights reserved.


Build: Topic Version 5.6.9309.1546
Windows Script Host

Unnamed Property
Returns the WshUnnamed object (a collection of unnamed arguments).
Object.Unnamed

Parameters
Object
WshArguments object.
Remarks
The Unnamed property returns the WshUnnamed collection, the collection of unnamed arguments. The arguments are presented in the order that they were entered on the command line. The first unnamed argument at index 0.
Example
The following code displays the number of named and unnamed command-line arguments.
<package>
<job id="JS">
<script language="JScript">
var argsNamed = WScript.Arguments.Named;
var argsUnnamed = WScript.Arguments.Unnamed;
WScript.Echo("There are " + argsNamed.length + " named arguments.");
WScript.Echo("There are " + argsUnnamed.length + " unnamed arguments.");
</script>
</job>
<job id="VBS">
<script language="VBScript">
Dim argsNamed, argsUnnamed
Set argsNamed = WScript.Arguments.Named
Set argsUnnamed = WScript.Arguments.Unnamed
WScript.Echo "There are " & argsNamed.Count & " named arguments."
WScript.Echo "There are " & argsUnnamed.Count & " unnamed arguments."
</script>
</job>
</package>

See Also
WshArguments Object | WshUnnamed Object | Named Property

2001 Microsoft Corporation. All rights reserved.


Build: Topic Version 5.6.9309.1546
Windows Script Host

UserDomain Property
Returns a user's domain name.
object.UserDomain

Arguments
object
WshNetwork object.
Remarks
String.
The UserDomain property does not work on Windows98 and Windows ME unless the USERDOMAIN environment variable is set. The variable is not set by default.
Example
The following example demonstrates the use of the UserDomain property:
<package>
<job id="vbs">
<script language="VBScript">
Set WshNetwork = WScript.CreateObject("WScript.Network")
WScript.Echo "Domain = " & WshNetwork.UserDomain
WScript.Echo "Computer Name = " & WshNetwork.ComputerName
WScript.Echo "User Name = " & WshNetwork.UserName
</script>
</job>
<job id="js">
<script language="JScript">
var WshNetwork = WScript.CreateObject("WScript.Network");
WScript.Echo("Domain = " + WshNetwork.UserDomain);
WScript.Echo("Computer Name = " + WshNetwork.ComputerName);
WScript.Echo("User Name = " + WshNetwork.UserName);
}
</script>
</job>
</package>

See Also
Running Your Scripts | WshNetwork Object

2001 Microsoft Corporation. All rights reserved.


Build: Topic Version 5.6.9309.1546
Windows Script Host

UserName Property
Returns the name of a user.
object.UserName

Arguments
object
WshNetwork object.
Remarks
String.
If you are using this property in a login script, see Creating an Automated Login Script.
Example
The following example demonstrates the use of the UserName property:
<package>
<job id="vbs">
<script language="VBScript">
Set WshNetwork = WScript.CreateObject("WScript.Network")
WScript.Echo "Domain = " & WshNetwork.UserDomain
WScript.Echo "Computer Name = " & WshNetwork.ComputerName
WScript.Echo "User Name = " & WshNetwork.UserName
</script>
</job>
<job id="js">
<script language="JScript">
var WshNetwork = WScript.CreateObject("WScript.Network");
WScript.Echo("Domain = " + WshNetwork.UserDomain);
WScript.Echo("Computer Name = " + WshNetwork.ComputerName);
WScript.Echo("User Name = " + WshNetwork.UserName);
}
</script>
</job>
</package>

See Also
Running Your Scripts | WshNetwork Object

2001 Microsoft Corporation. All rights reserved.


Build: Topic Version 5.6.9309.1546
Windows Script Host

Version Property
Returns the version of Windows Script Host.
object.Version

Arguments
object
WScript object.
Remarks
String.
Example
The following VBScript code echoes the current version of Windows Script Host.
WScript.Echo WScript.Version

See Also
WScript Object

2001 Microsoft Corporation. All rights reserved.


Build: Topic Version 5.6.9309.1546
Windows Script Host

WindowStyle Property
Assigns a window style to a shortcut, or identifies the type of window style used by a shortcut.
object.WindowStyle = intWindowStyle

Arguments
object
WshShortcut object.
intWindowStyle

Sets the window style for the program being run.


Remarks
The WindowStyle property returns an integer.
The following table lists the available settings for intWindowStyle.
intWindowStyle
1
3
7

Description
Activates and displays a window. If the window is minimized or maximized, the system restores it to its original size and position.
Activates the window and displays it as a maximized window.
Minimizes the window and activates the next top-level window.

Example
The following example demonstrates the use of the WindowStyle property:
<package>
<job id="vbs">
<script language="VBScript">
set WshShell = WScript.CreateObject("WScript.Shell")
strDesktop = WshShell.SpecialFolders("Desktop")
set oShellLink = WshShell.CreateShortcut(strDesktop & "\Shortcut Script.lnk")
oShellLink.TargetPath = WScript.ScriptFullName
oShellLink.WindowStyle = 1
oShellLink.Hotkey = "Ctrl+Alt+e"
oShellLink.IconLocation = "notepad.exe, 0"
oShellLink.Description = "Shortcut Script"
oShellLink.WorkingDirectory = strDesktop
oShellLink.Save
set oUrlLink = WshShell.CreateShortcut(strDesktop & "\Microsoft Web Site.url")
oUrlLink.TargetPath = "http://www.microsoft.com"
oUrlLink.Save
</script>
</job>
<job id="js">
<script language="JScript">
var WshShell = WScript.CreateObject("WScript.Shell");
strDesktop = WshShell.SpecialFolders("Desktop");
var oShellLink = WshShell.CreateShortcut(strDesktop + "\\Shortcut Script.lnk");
oShellLink.TargetPath = WScript.ScriptFullName;
oShellLink.WindowStyle = 1;
oShellLink.Hotkey = "Ctrl+Alt+e";
oShellLink.IconLocation = "notepad.exe, 0";
oShellLink.Description = "Shortcut Script";
oShellLink.WorkingDirectory = strDesktop;
oShellLink.Save();
var oUrlLink = WshShell.CreateShortcut(strDesktop + "\\Microsoft Web Site.url");
oUrlLink.TargetPath = "http://www.microsoft.com";
oUrlLink.Save();
</script>
</job>
</package>

See Also
Running Your Scripts | WshShortcut Object

2001 Microsoft Corporation. All rights reserved.


Build: Topic Version 5.6.9309.1546
Windows Script Host

WorkingDirectory Property
Assign a working directory to a shortcut, or identifies the working directory used by a shortcut.
object.WorkingDirectory = strWorkingDirectory

Arguments
object
WshShortcut object.
strWorkingDirectory
String. Directory in which the shortcut starts.
Remarks
String.
Example
The following example demonstrates the use of the WorkingDirectory property:
<package>
<job id="vbs">
<script language="VBScript">
set WshShell = WScript.CreateObject("WScript.Shell")
strDesktop = WshShell.SpecialFolders("Desktop")
set oShellLink = WshShell.CreateShortcut(strDesktop & "\Shortcut Script.lnk")
oShellLink.TargetPath = WScript.ScriptFullName
oShellLink.WindowStyle = 1
oShellLink.Hotkey = "Ctrl+Alt+e"
oShellLink.IconLocation = "notepad.exe, 0"
oShellLink.Description = "Shortcut Script"
oShellLink.WorkingDirectory = strDesktop
oShellLink.Save
set oUrlLink = WshShell.CreateShortcut(strDesktop & "\Microsoft Web Site.url")
oUrlLink.TargetPath = "http://www.microsoft.com"
oUrlLink.Save
</script>
</job>
<job id="js">
<script language="JScript">
var WshShell = WScript.CreateObject("WScript.Shell");
strDesktop = WshShell.SpecialFolders("Desktop");
var oShellLink = WshShell.CreateShortcut(strDesktop + "\\Shortcut Script.lnk");
oShellLink.TargetPath = WScript.ScriptFullName;
oShellLink.WindowStyle = 1;
oShellLink.Hotkey = "Ctrl+Alt+e";
oShellLink.IconLocation = "notepad.exe, 0";
oShellLink.Description = "Shortcut Script";

oShellLink.WorkingDirectory = strDesktop;
oShellLink.Save();
var oUrlLink = WshShell.CreateShortcut(strDesktop + "\\Microsoft Web Site.url");
oUrlLink.TargetPath = "http://www.microsoft.com";
oUrlLink.Save();
</script>
</job>
</package>

See Also
Running Your Scripts

2001 Microsoft Corporation. All rights reserved.


Build: Topic Version 5.6.9309.1546
Windows Script Host

Methods
In this Section
AddPrinterConnection Method
Adds a DOS-style printer connection to your computer.
AddWindowsPrinterConnection Method
Adds a Windows-style printer connection to your computer.
AppActivate Method
Activates an application window.
Close Method
Closes an open stream.
ConnectObject Method
Connects an object's event sources to functions with a given prefix.
Count Method
Returns the number of switches in the WshNamed or WshUnnamed objects.
CreateObject Method
Creates an object specified by the strProgID parameter.
CreateScript Method
Creates a WshRemote object (an object that represents an instance of a script running in a remote process).
CreateShortcut Method
Creates an object reference to a shortcut or URLshortcut.
DisconnectObject Method
Disconnects a previously connected object from Windows Script Host.
Echo Method
Sends output to a dialog box or the console.
EnumNetworkDrives Method
Returns the current network drive mappings.
EnumPrinterConnections Method
Returns the current network printer mappings.
Exec Method
Runs an application in a child command-shell, providing access to the stdin/stdout/stderr channels, and the sharing of environment variables.
Execute Method
Starts execution of a remote script object.
Exists Method
Indicates whether a specific key value exists in the WshNamed object.
ExpandEnvironmentStrings Method
Expands the requested environment variable from the running process and returns the result string.
GetObject Method
Retrieves an Automation object from a file or an object specified by the strProgID parameter.
getResource Method
Returns the value of a resource defined with the resource element.
LogEvent Method
Logs an event in the Windows NT event log or WSH.log file.
MapNetworkDrive Method
Maps the share point specified by strRemoteName to the local resource name strLocalName.
Popup Method
Displays a pop-up message box window that contains the message contained in strText.
Quit Method
Quits execution with a specified error code.
Read Method
Reads a specified number of characters from an input stream and returns the resulting string.
ReadAll Method
Reads an entire input stream and returns the resulting string.
ReadLine Method
Reads an entire line (up to, but not including, the newline character) from an input stream and returns the resulting string.
RegDelete Method
Deletes from the registry the key or value named by strName.
RegRead Method
Returns the registry key or value named by strName.
RegWrite Method
Sets the registry key or value named by strName.
Remove Method
Deletes the environment variable specified by strName.
RemoveNetworkDrive Method
Removes the current resource connection denoted by strName.
RemovePrinterConnection Method
Removes the current resource connection denoted by strName.
Run Method
Creates a new process that executes strCommand.
Save Method
Saves a shortcut to the specified location.
SendKeys Method
Sends one or more keystrokes to the active window (as if typed on the keyboard).
SetDefaultPrinter Method
Sets the default printer to the remote printer specified.
ShowUsage Method
Displays information about how a script should be used.
Skip Method
Skips a specified number of characters when reading an input stream.
SkipLine Method
Skips the next line when reading an input stream.
Sleep Method
Places the script process into an inactive state for the number of milliseconds specified and then continues execution.
Terminate Method (WshScriptExec)
Instructs the script engine to end the process started by the Exec method.
Write Method
Writes a specified string to an output stream.
WriteBlankLines Method

Writes a specified number of newline characters to an output stream.


WriteLine Method
Writes a specified string and newline character to an output stream.
Related Sections
WSH Language
List of elements that make up WSH Reference.
WSH Basics
Learn the basics of WSH.

2001 Microsoft Corporation. All rights reserved.


Build: Topic Version 5.6.9309.1546
Windows Script Host

AddPrinterConnection Method
Adds a remote MS-DOS-based printer connection to your computer system.
object.AddPrinterConnection(strLocalName, strRemoteName[,bUpdateProfile][,strUser][,strPassword])

Arguments
object
WshNetwork object.
strLocalName
Sting value indicating the local name to assign to the connected printer.
strRemoteName
Sting value indicating the name of the remote printer.
bUpdateProfile
Optional. Boolean value indicating whether the printer mapping is stored in the current user's profile. If bUpdateProfile is supplied and is true, the mapping is stored in the user profile. The default value is false.
strUser
Optional. String value indicating the user name. If you are mapping a remote printer using the profile of someone other than current user, you can specify strUser and strPassword.
strPassword
Optional. String value indicating the user password. If you are mapping a remote printer using the profile of someone other than current user, you can specify strUser and strPassword.
Remarks
The AddPrinterConnection method adds a network printer to an MS-DOS printer port, such as LPT1. You cannot use this method to add a remote Windows-based printer connection. To add a remote Windows-based printer
connection, use the AddWindowsPrinterConnection method.
Example
The following code uses the AddPrinterConnection method to connect a network printer to LPT1.
[VBScript]
Set WshNetwork = WScript.CreateObject("WScript.Network")
WshNetwork.AddPrinterConnection "LPT1", "\\Server\Print1"

[JScript]
var WshNetwork = WScript.CreateObject("WScript.Network");
WshNetwork.AddPrinterConnection ("LPT1", "\\\\Server\\Print1");

See Also
WshNetwork Object | AddWindowsPrinterConnection Method | EnumPrinterConnections Method | RemovePrinterConnection Method | SetDefaultPrinter Method

2001 Microsoft Corporation. All rights reserved.


Build: Topic Version 5.6.9309.1546
Windows Script Host

AddWindowsPrinterConnection Method
Adds a Windows-based printer connection to your computer system.
Windows NT/2000:
object.AddWindowsPrinterConnection(
strPrinterPath
)
Windows 9x/Me:
object.AddWindowsPrinterConnection(
strPrinterPath,
strDriverName[,strPort]
)

Arguments
object
WshNetwork object.
strPrinterPath
String value indicating the path to the printer connection.
strDriverName
String value indicating the name of the driver (ignored if used on Windows NT/Windows 2000).
strPort
Optional. String value specifying a printer port for the printer connection (ignored on Windows NT/Windows 2000).
Remarks
Using this method is similar to using the Printer option on Control Panel to add a printer connection. Unlike the AddPrinterConnection method, this method allows you to create a printer connection without directing it to a
specific port, such as LPT1. If the connection fails, an error is thrown. In Windows 9x/Me, the printer driver must already be installed on the machine for the AddWindowsPrinterConnection method to work. If the driver is not
installed, Windows returns an error message.
Example 1
The following code uses the AddWindowsPrinterConnection method to connect a network printer to a Windows NT/2000 computer system.

[VBScript]
Set WshNetwork = WScript.CreateObject("WScript.Network")
PrinterPath = "\\printserv\DefaultPrinter"
WshNetwork.AddWindowsPrinterConnection PrinterPath

[JScript]
var WshNetwork = WScript.CreateObject("WScript.Network");
var PrinterPath = "\\\\printserv\\DefaultPrinter";
WshNetwork.AddWindowsPrinterConnection(PrinterPath);

Example 2
The following code uses the AddWindowsPrinterConnection method to connect a network printer to a Windows 9x/Me computer system.
[VBScript]
Set WshNetwork = WScript.CreateObject("WScript.Network")
PrinterPath = "\\printserv\DefaultPrinter"
PrinterDriver = "Lexmark Optra S 1650"
WshNetwork.AddWindowsPrinterConnection PrinterPath, PrinterDriver

[JScript]
var WshNetwork = WScript.CreateObject("WScript.Network");
var PrinterPath = "\\\\printserv\\DefaultPrinter";
var PrinterDriver = "Lexmark Optra S 1650";
WshNetwork.AddWindowsPrinterConnection(PrinterPath, PrinterDriver);

See Also
WshNetwork Object | AddPrinterConnection Method | EnumPrinterConnections Method | RemovePrinterConnection Method | SetDefaultPrinter Method

2001 Microsoft Corporation. All rights reserved.


Build: Topic Version 5.6.9309.1546
Windows Script Host

AppActivate Method
Activates an application window.
object.AppActivate title

Arguments
object
WshShell object.
title
Specifies which application to activate. This can be a string containing the title of the application (as it appears in the title bar) or the application's Process ID.
Remarks
The AppActivate method returns a Boolean value that identifies whether the procedure call is successful. This method changes the focus to the named application or window, but it does not affect whether it is maximized or
minimized. Focus moves from the activated application window when the user takes action to change the focus (or closes the window).
In determining which application to activate, the specified title is compared to the title string of each running application. If no exact match exists, any application whose title string begins with title is activated. If an application
still cannot be found, any application whose title string ends with title is activated. If more than one instance of the application named by title exists, one instance is arbitrarily activated.
Example
The following example demonstrates the use of a single .wsf file for two jobs in different script languages (VBScript and JScript). The functionality of both jobs is the same each runs the Windows calculator and sends it
keystrokes to execute a simple calculation.
The following example starts the Windows calculator and uses AppActivate to ensure that the calculator is at the top.
<package>
<job id="vbs">
<script language="VBScript">
set WshShell = WScript.CreateObject("WScript.Shell")
WshShell.Run "calc"
WScript.Sleep 100
WshShell.AppActivate "Calculator"
WScript.Sleep 100
WshShell.SendKeys "1{+}"
WScript.Sleep 500
WshShell.SendKeys "2"
WScript.Sleep 500
WshShell.SendKeys "~"
WScript.Sleep 500
WshShell.SendKeys "*3"
WScript.Sleep 500
WshShell.SendKeys "~"
WScript.Sleep 2500
</script>
</job>
<job id="js">
<script language="JScript">
var WshShell = WScript.CreateObject("WScript.Shell");
WshShell.Run("calc");
WScript.Sleep(100);
WshShell.AppActivate("Calculator");
WScript.Sleep(100);
WshShell.SendKeys("1{+}");
WScript.Sleep(500);
WshShell.SendKeys("2");
WScript.Sleep(500);
WshShell.SendKeys("~");
WScript.Sleep(500);
WshShell.SendKeys("*3");
WScript.Sleep(500);
WshShell.SendKeys("~");
WScript.Sleep(2500);
</script>
</job>
</package>

See Also
Running Your Scripts | WshShell Object | SendKeys Method

2001 Microsoft Corporation. All rights reserved.


Build: Topic Version 5.6.9309.1546
Windows Script Host

Close Method
Closes a text stream.
object.Close

Arguments
object
StdIn, StdOut, or StdErr text stream objects.
Remarks
The StdIn, StdOut, and StdErr properties and methods work when running the script with the CScript.exe host executable file only. An error is returned when run with WScript.exe. It is not necessary to close standard streams;
they close automatically when the process ends. If you close a standard stream, be aware that any other pointers to that standard stream become invalid. This method is provided for compatibility with the TextStream object.
See Also
StdErr Property | StdIn Property | StdOut Property | Error Messages

2001 Microsoft Corporation. All rights reserved.


Build: Topic Version 5.6.9309.1546
Windows Script Host

ConnectObject Method
Connects the object's event sources to functions with a given prefix.
object.ConnectObject(strObject, strPrefix)

Arguments
object
WScript object.
strObject
Required. String value indicating the name of the object you want to connect.
strPrefix
Required. String value indicating the function prefix.
Remarks
Connected objects are useful when you want to sync an object's events. The ConnectObject method connects the object's outgoing interface to the script file after creating the object. Event functions are a combination of this
prefix and the event name.
Example
The following example demonstrates using the ConnectObject method to connect to the WshRemote object's Error event.
[VBScript]
Dim Controller, RemoteScript
Set Controller = WScript.CreateObject("WSHController")
Set RemoteScript = Controller.CreateScript("test.js", "remoteserver")
WScript.ConnectObject RemoteScript, "remote_"
RemoteScript.Execute
Do While RemoteScript.Status <> 2
WScript.Sleep 100
Loop
Sub remote_Error
Dim theError
Set theError = RemoteScript.Error
WScript.Echo "Error " & theError.Number & " - Line: " & theError.Line & ", Char: " & theError.Character & vbCrLf & "Description: " & theError.Description
WScript.Quit -1
End Sub

[JScript]
var Controller = WScript.CreateObject("WSHController");
var RemoteScript = Controller.CreateScript("test.js", "remoteserver");
WScript.ConnectObject(RemoteScript, "remote_");
RemoteScript.Execute();
while (RemoteScript.Status != 2) {
WScript.Sleep(100);
}
function remote_Error()
{
var theError = RemoteScript.Error;
WScript.Echo("Error " + theError.Number + " - Line: " + theError.Line + ", Char: " + theError.Character + "\nDescription: " + theError.Description);
WScript.Quit(-1);
}

See Also
WScript Object | DisconnectObject Method | CreateObject Method | GetObject Method

2001 Microsoft Corporation. All rights reserved.


Build: Topic Version 5.6.9309.1546
Windows Script Host

Count Method
Returns the number of switches in the WshNamed or WshUnnamed objects.
object.Count

Arguments
object
Arguments object.
Remarks
The Count method returns an integer value. The Count method is primarily intended for VBScript users. JScript users should generally use the length property instead.
Example (WshNamed)
The following example demonstrates the Count method using the WshNamed object. Begin by typing the following text at the Command Prompt.
myScript.vbs /c:"WSH is a wonderful thing" /s:"scripts are wonderful"

Next, add the following VBScript code.


For i = 0 to WScript.Arguments.Count-1
WScript.Echo WScript.Arguments.Named(i)
next i

Following is the result.


WSH is a wonderful thing
scripts are wonderful

Example (WshUnnamed)
The following example demonstrates the Count method using the WshUnnamed object. Begin by typing the following text at the command line.
myscript.vbs "WSH is a wonderful thing" "scripts are wonderful"

Next, add the following VBScript code.


For i = 0 to WScript.Arguments.Count-1
WScript.Echo WScript.Arguments.Unnamed(i)
next i

Following is the result.


WSH is a wonderful thing
scripts are wonderful

See Also
Arguments Property | WshNamed Object | WshUnnamed Object | Item Property | Exists Method | Length Property

2001 Microsoft Corporation. All rights reserved.


Build: Topic Version 5.6.9309.1546
Windows Script Host

CreateObject Method
Creates a COM object.
object.CreateObject(strProgID[,strPrefix])

Arguments
object
WScript object.
strProgID
String value indicating the programmatic identifier (ProgID) of the object you want to create.
strPrefix
Optional. String value indicating the function prefix.
Remarks
Objects created with the CreateObject method using the strPrefix argument are connected objects. These are useful when you want to sync an object's events. The object's outgoing interface is connected to the script file after
the object is created. Event functions are a combination of this prefix and the event name. If you create an object and do not supply the strPrefix argument, you can still sync events on the object by using the ConnectObject
method. When the object fires an event, WSH calls a subroutine with strPrefix attached to the beginning of the event name. For example, if strPrefix is MYOBJ and the object fires an event named OnBegin, Windows Script Host
calls the MYOBJ_OnBegin subroutine located in the script. The CreateObject method returns a pointer to the object's IDispatch interface.
Example
The following VBScript code uses the CreateObject method to create a WshNetwork object:
Set WshNetwork = WScript.CreateObject("WScript.Network")

See Also
WScript Object | GetObject Method | ConnectObject Method | DisconnectObject Method

2001 Microsoft Corporation. All rights reserved.


Build: Topic Version 5.6.9309.1546
Windows Script Host

CreateScript Method
Creates a WshRemote object.

object.CreateScript(CommandLine,[MachineName])

Parameters
object
WshController Object.
Commandline
Required. String value indicating the script's path and switches as they would be typed at the command prompt. The path to the script should appear as seen from the controller computer system rather than the computer
system on which you want to run the script.
MachineName
Optional. String value indicating the name of the remote computer system (the computer on which you want to run the remote script). It is specified in the Uniform Naming Convention (UNC).
Remarks
The CreateScript method returns a handle to an instance of a WshRemote object. The path part of the script name does not need to be local it can refer to a script on a network share. This makes it possible to sit at one
computer system, retrieve a script from another computer system, and run it on a third computer system. If a machine name is not provided, the remote script object runs on the controller computer system (this is the default). If a
machine name is provided, the remote script object runs on the named computer system. The CreateScript method establishes a connection with the remote computer system and sets it up to run the script, but the script does not
actually start until you call the Execute method of the WshRemote object.
Example
The following example demonstrates how the CreateScript method of the WshController object is used to create a WshRemote object (an instance of a remote script).
[VBScript]
Dim Controller, RemoteScript
Set Controller = WScript.CreateObject("WSHController")
Set RemoteScript = Controller.CreateScript("test.js", "remoteserver")
WScript.ConnectObject RemoteScript, "remote_"
RemoteScript.Execute
Do While RemoteScript.Status <> 2
WScript.Sleep 100
Loop
WScript.DisconnectObject RemoteScript
Sub remote_Error
Dim theError
Set theError = RemoteScript.Error
WScript.Echo "Error " & theError.Number & " - Line: " & theError.Line & ", Char: " & theError.Character & vbCrLf & "Description: " & theError.Description
WScript.Quit -1
End Sub

[JScript]
var Controller = WScript.CreateObject("WSHController");
var RemoteScript = Controller.CreateScript("test.js", "remoteserver");
WScript.ConnectObject(RemoteScript, "remote_");
RemoteScript.Execute();
while (RemoteScript.Status != 2) {
WScript.Sleep(100);
}
WScript.DisconnectObject(RemoteScript);
function remote_Error()
{
var theError = RemoteScript.Error;
WScript.Echo("Error " + theError.Number + " - Line: " + theError.Line + ", Char: " + theError.Character + "\nDescription: " + theError.Description);
WScript.Quit(-1);
}

See Also
CreateObject Method | CreateScript Method | WshRemote Object | Execute Method

2001 Microsoft Corporation. All rights reserved.


Build: Topic Version 5.6.9309.1546
Windows Script Host

CreateShortcut Method
Creates a new shortcut, or opens an existing shortcut.
object.CreateShortcut(strPathname)

Arguments
object
WshShell object.
strPathname
String value indicating the pathname of the shortcut to create.
Remarks
The CreateShortcut method returns either a WshShortcut object or a WshURLShortcut object. Simply calling the CreateShortcut method does not result in the creation of a shortcut. The shortcut object and changes you
may have made to it are stored in memory until you save it to disk with the Save method. To create a shortcut, you must:
1. Create an instance of a WshShortcut object.
2. Initialize its properties.
3. Save it to disk with the Save method.
Note

A common problem is putting arguments inthe TargetPath property of the shortcut object, which doesn't work. All arguments to the shortcut must be put in the Arguments property.

Example
The following example creates a WshShell object and uses the CreateShortcut method to create two shortcuts.
<package>
<job id="vbs">
<script language="VBScript">
set WshShell = WScript.CreateObject("WScript.Shell")
strDesktop = WshShell.SpecialFolders("Desktop")
set oShellLink = WshShell.CreateShortcut(strDesktop & "\Shortcut Script.lnk")
oShellLink.TargetPath = WScript.ScriptFullName
oShellLink.WindowStyle = 1
oShellLink.Hotkey = "CTRL+SHIFT+F"
oShellLink.IconLocation = "notepad.exe, 0"

oShellLink.Description = "Shortcut Script"


oShellLink.WorkingDirectory = strDesktop
oShellLink.Save
set oUrlLink = WshShell.CreateShortcut(strDesktop & "\Microsoft Web Site.url")
oUrlLink.TargetPath = "http://www.microsoft.com"
oUrlLink.Save
</script>
</job>
<job id="js">
<script language="JScript">
var WshShell = WScript.CreateObject("WScript.Shell");
strDesktop = WshShell.SpecialFolders("Desktop");
var oShellLink = WshShell.CreateShortcut(strDesktop + "\\Shortcut Script.lnk");
oShellLink.TargetPath = WScript.ScriptFullName;
oShellLink.WindowStyle = 1;
oShellLink.Hotkey = "CTRL+SHIFT+F";
oShellLink.IconLocation = "notepad.exe, 0";
oShellLink.Description = "Shortcut Script";
oShellLink.WorkingDirectory = strDesktop;
oShellLink.Save();
var oUrlLink = WshShell.CreateShortcut(strDesktop + "\\Microsoft Web Site.url");
oUrlLink.TargetPath = "http://www.microsoft.com";
oUrlLink.Save();
</script>
</job>
</package>

See Also
Running Your Scripts | WshShortcut Object | WshUrlShortcut Object | WshShell Object

2001 Microsoft Corporation. All rights reserved.


Build: Topic Version 5.6.9309.1546
Windows Script Host

DisconnectObject Method
Disconnects a connected object's event sources.
object.DisconnectObject(obj)

Arguments
object
WScript object.
obj
String value indicating the name of the object to disconnect.
Remarks
Once an object has been "disconnected," WSH will not respond to its events. The object is still capable of firing events, though. Note that the DisconnectObject method does nothing if the specified object is not already
connected.
Example
The following example demonstrates using the DisconnectObject method to disconnect to the WshRemote object's Error event after a remote script has completed.
[VBScript]
Dim Controller, RemoteScript
Set Controller = WScript.CreateObject("WSHController")
Set RemoteScript = Controller.CreateScript("test.js", "remoteserver")
WScript.ConnectObject RemoteScript, "remote_"
RemoteScript.Execute
Do While RemoteScript.Status <> 2
WScript.Sleep 100
Loop
WScript.DisconnectObject RemoteScript
Sub remote_Error
Dim theError
Set theError = RemoteScript.Error
WScript.Echo "Error " & theError.Number & " - Line: " & theError.Line & ", Char: " & theError.Character & vbCrLf & "Description: " & theError.Description
WScript.Quit -1
End Sub

[JScript]
var Controller = WScript.CreateObject("WSHController");
var RemoteScript = Controller.CreateScript("test.js", "remoteserver");
WScript.ConnectObject(RemoteScript, "remote_");
RemoteScript.Execute();
while (RemoteScript.Status != 2) {
WScript.Sleep(100);
}
WScript.DisconnectObject(RemoteScript)
function remote_Error()
{
var theError = RemoteScript.Error;
WScript.Echo("Error " + theError.Number + " - Line: " + theError.Line + ", Char: " + theError.Character + "\nDescription: " + theError.Description);
WScript.Quit(-1);
}

See Also
WScript Object | ConnectObject Method | CreateObject Method | GetObject Method

2001 Microsoft Corporation. All rights reserved.


Build: Topic Version 5.6.9309.1546
Windows Script Host

Echo Method
Outputs text to either a message box or the command console window.
object.Echo [Arg1] [,Arg2] [,Arg3] ...

Arguments
object
WScript object.
Arg1, Arg2, Arg3 ...
Optional. String value indicating the list of items to be displayed.
Remarks
The Echo method behaves differently depending on which WSH engine you are using.
WSH engine
Text Output
Wscript.exe graphical message box
Cscript.exe command console window
Each displayed item is separated with a space character. When using CScript.exe, each item is displayed with a newline character. If no items are provided as arguments to the Echo method, a blank line is output.
Example
The following example uses the Echo Method to display the domain name, computer name, and user name for the current machine, and to display network mapping information for the drives and printers.
<package>
<job id="vbs">
<script language="VBScript">
Set WshNetwork = WScript.CreateObject("WScript.Network")
Set oDrives = WshNetwork.EnumNetworkDrives
Set oPrinters = WshNetwork.EnumPrinterConnections
WScript.Echo "Domain = " & WshNetwork.UserDomain
WScript.Echo "Computer Name = " & WshNetwork.ComputerName
WScript.Echo "User Name = " & WshNetwork.UserName
WScript.Echo
WScript.Echo "Network drive mappings:"
For i = 0 to oDrives.Count - 1 Step 2
WScript.Echo "Drive " & oDrives.Item(i) & " = " & oDrives.Item(i+1)
Next
WScript.Echo
WScript.Echo "Network printer mappings:"
For i = 0 to oPrinters.Count - 1 Step 2
WScript.Echo "Port " & oPrinters.Item(i) & " = " & oPrinters.Item(i+1)
Next
</script>
</job>
<job id="js">
<script language="JScript">
var WshNetwork = WScript.CreateObject("WScript.Network");
var oDrives = WshNetwork.EnumNetworkDrives();
var oPrinters = WshNetwork.EnumPrinterConnections();
WScript.Echo("Domain = " + WshNetwork.UserDomain);
WScript.Echo("Computer Name = " + WshNetwork.ComputerName);
WScript.Echo("User Name = " + WshNetwork.UserName);
WScript.Echo();
WScript.Echo("Network drive mappings:");
for(i=0; i<oDrives.Count(); i+=2){
WScript.Echo("Drive " + oDrives.Item(i) + " = " + oDrives.Item(i+1));
}
WScript.Echo();
WScript.Echo("Network printer mappings:");
for(i=0; i<oPrinters.Count(); i+=2){
WScript.Echo("Port " + oPrinters.Item(i) + " = " + oPrinters.Item(i+1));
}
</script>
</job>
</package>

See Also
Running Your Scripts | WScript Object

2001 Microsoft Corporation. All rights reserved.


Build: Topic Version 5.6.9309.1546
Windows Script Host

EnumNetworkDrives Method
Returns the current network drive mapping information.
objDrives = object.EnumNetworkDrives

Arguments
object
WshNetwork object.
objDrives
Variable that holds the network drive mapping information.
Remarks
The EnumNetworkDrives method returns a collection. This collection is an array that associates pairs of items network drive local names and their associated UNC names. Even-numbered items in the collection represent
local names of logical drives. Odd-numbered items represent the associated UNC share names. The first item in the collection is at index zero (0).
Example
The following example uses EnumNetworkDrives to generate a list of the networked drives and displays the mapping information.
<package>
<job id="vbs">
<script language="VBScript">
Set WshNetwork = WScript.CreateObject("WScript.Network")
Set oDrives = WshNetwork.EnumNetworkDrives
Set oPrinters = WshNetwork.EnumPrinterConnections
WScript.Echo "Network drive mappings:"
For i = 0 to oDrives.Count - 1 Step 2
WScript.Echo "Drive " & oDrives.Item(i) & " = " & oDrives.Item(i+1)

Next
WScript.Echo
WScript.Echo "Network printer mappings:"
For i = 0 to oPrinters.Count - 1 Step 2
WScript.Echo "Port " & oPrinters.Item(i) & " = " & oPrinters.Item(i+1)
Next
</script>
</job>
<job id="js">
<script language="JScript">
var WshNetwork = WScript.CreateObject("WScript.Network");
var oDrives = WshNetwork.EnumNetworkDrives();
var oPrinters = WshNetwork.EnumPrinterConnections();
WScript.Echo("Network drive mappings:");
for(i = 0; i < oDrives.length; i += 2) {
WScript.Echo("Drive " + oDrives.Item(i) + " = " + oDrives.Item(i + 1));
}
WScript.Echo();
WScript.Echo("Network printer mappings:");
for(i = 0; i < oPrinters.length; i += 2) {
WScript.Echo("Port " + oPrinters.Item(i) + " = " + oPrinters.Item(i + 1));
}
</script>
</job>
</package>

See Also
Running Your Scripts | WshNetwork Object | MapNetworkDrive Method | RemoveNetworkDrive Method

2001 Microsoft Corporation. All rights reserved.


Build: Topic Version 5.6.9309.1546
Windows Script Host

EnumPrinterConnections Method
Returns the current network printer mapping information.
objPrinters = object.EnumPrinterConnections

Arguments
object
WshNetwork object.
objPrinters
Variable that holds the network printer mapping information.
Remarks
The EnumPrinterConnections method returns a collection. This collection is an array that associates pairs of items network printer local names and their associated UNC names. Even-numbered items in the collection
represent printer ports. Odd-numbered items represent the networked printer UNC names. The first item in the collection is at index zero (0).
Example
The following example uses the EnumPrinterConnections method to generate a list of networked printers and displays this mapping information.
<package>
<job id="vbs">
<script language="VBScript">
Set WshNetwork = WScript.CreateObject("WScript.Network")
Set oDrives = WshNetwork.EnumNetworkDrives
Set oPrinters = WshNetwork.EnumPrinterConnections
WScript.Echo "Network drive mappings:"
For i = 0 to oDrives.Count - 1 Step 2
WScript.Echo "Drive " & oDrives.Item(i) & " = " & oDrives.Item(i+1)
Next
WScript.Echo
WScript.Echo "Network printer mappings:"
For i = 0 to oPrinters.Count - 1 Step 2
WScript.Echo "Port " & oPrinters.Item(i) & " = " & oPrinters.Item(i+1)
Next
</script>
</job>
<job id="js">
<script language="JScript">
var WshNetwork = WScript.CreateObject("WScript.Network");
var oDrives = WshNetwork.EnumNetworkDrives();
var oPrinters = WshNetwork.EnumPrinterConnections();
WScript.Echo("Network drive mappings:");
for(i = 0; i < oDrives.length; i += 2) {
WScript.Echo("Drive " + oDrives.Item(i) + " = " + oDrives.Item(i + 1));
}
WScript.Echo();
WScript.Echo("Network printer mappings:");
for(i = 0; i < oPrinters.length; i += 2) {
WScript.Echo("Port " + oPrinters.Item(i) + " = " + oPrinters.Item(i + 1));
}
</script>
</job>
</package>

See Also
Running Your Scripts | WshNetwork Object | AddPrinterConnection Method | AddWindowsPrinterConnection Method | RemovePrinterConnection Method | SetDefaultPrinter Method

2001 Microsoft Corporation. All rights reserved.


Build: Topic Version 5.6.9309.1546
Windows Script Host

Exec Method
Runs an application in a child command-shell, providing access to the StdIn/StdOut/StdErr streams.
object.Exec(strCommand)

Arguments
object
WshShell object.
strCommand
String value indicating the command line used to run the script. The command line should appear exactly as it would if you typed it at the command prompt.
Remarks
The Exec method returns a WshScriptExec object, which provides status and error information about a script run with Exec along with access to the StdIn, StdOut, and StdErr channels. The Exec method allows the execution
of command line applications only. The Exec method cannot be used to run remote scripts. Do not confuse the Exec method with the Execute method (of the WshRemote object).
Example
The following example demonstrates the basics of the Exec method.
[VBScript]
Dim WshShell, oExec
Set WshShell = CreateObject("WScript.Shell")
Set oExec = WshShell.Exec("calc")
Do While oExec.Status = 0
WScript.Sleep 100
Loop
WScript.Echo oExec.Status

[JScript]
var WshShell = new ActiveXObject("WScript.Shell");
var oExec = WshShell.Exec("calc");
while (oExec.Status == 0)
{
WScript.Sleep(100);
}
WScript.Echo(oExec.Status);

See Also
WshScriptExec Object

2001 Microsoft Corporation. All rights reserved.


Build: Topic Version 5.6.9309.1546
Windows Script Host

Execute Method
Starts execution of a remote script object.
object.Execute

Parameters
object
WshRemote Object
Remarks
The Start event of the WshRemote object is fired when the script starts executing. Do not confuse the Execute method with the Exec method (of the WScript object).
Example
The following example demonstrates how the Execute method is used to create a WshRemote object (start an instance of a remote script).
[VBScript]
Dim Controller, RemoteScript
Set Controller = WScript.CreateObject("WSHController")
Set RemoteScript = Controller.CreateScript("remote1.js")
RemoteScript.Execute
Do While RemoteScript.Status <> 2
WScript.Sleep 100
Loop

[JScript]
var Controller = WScript.CreateObject("WSHController");
var RemoteScript = Controller.CreateScript("remote1.js");
RemoteScript.Execute();
while (RemoteScript.Status != 2) {
WScript.Sleep(100);
}

See Also
WshController Object | WshRemote Object | Status Property | Error Property | Terminate Method | Start Event | End Event

2001 Microsoft Corporation. All rights reserved.


Build: Topic Version 5.6.9309.1546
Windows Script Host

Exists Method
Indicates whether a specific key value exists in the WshNamed object.
object.Exists(key)

Parameters
object
WshNamed object.
Key
String value indicating an argument of the WshNamed object.
Remarks
The Exists method returns a Boolean value. It returns true if the requested argument was specified on the command line (otherwise, it returns false).
Example
Consider the following information typed at the command line.
myScript.vbs /c:"WSH is a wonderful thing"

You could use these two lines of JScript code to find out whether the following command line switches were used to start the script.
WScript.Echo(WScript.Arguments.Named.Exists("C"));
WScript.Echo(WScript.Arguments.Named.Exists("D"));

See Also
Arguments Property | WshNamed Object | WshUnnamed Object | Count Method | Item Property

2001 Microsoft Corporation. All rights reserved.


Build: Topic Version 5.6.9309.1546
Windows Script Host

ExpandEnvironmentStrings Method
Returns an environment variable's expanded value.
object.ExpandEnvironmentStrings(strString)

Arguments
object
WshShell object.
strString
String value indicating the name of the environment variable you want to expand.
Remarks
The ExpandEnvironmentStrings method expands environment variables defined in the PROCESS environment space only. Environment variable names, which must be enclosed between "%" characters, are not case-sensitive.
Example
The following code expands the Windows Directory environment variable and displays it:
[VBScript]
set WshShell = WScript.CreateObject("WScript.Shell")
WScript.Echo "WinDir is " & WshShell.ExpandEnvironmentStrings("%WinDir%")

[JScript]
var WshShell = WScript.CreateObject("WScript.Shell");
WScript.Echo("WinDir is " + WshShell.ExpandEnvironmentStrings("%WinDir%"));

See Also
WshShell Object

2001 Microsoft Corporation. All rights reserved.


Build: Topic Version 5.6.9309.1546
Windows Script Host

GetObject Method
Retrieves an existing object with the specified ProgID, or creates a new one from a file.
object.GetObject(strPathname [,strProgID], [strPrefix])

Arguments
object
WScript object.
strPathname
The fully qualified path name of the file that contains the object persisted to disk.
strProgID
Optional. The object's program identifier (ProgID).
strPrefix
Optional. Used when you want to sync the object's events. If you supply the strPrefix argument, WSH connects the object's outgoing interface to the script file after creating the object.
Remarks
Use the GetObject method when an instance of the object exists in memory, or when you want to create the object from a file. If no current instance exists and you do not want the object created from a file, use the
CreateObject method. The GetObject method can be used with all COM classes, independent of the language used to create the object. If you supply the strPrefix argument, WSH connects the object's outgoing interface to the
script file after creating the object. When the object fires an event, WSH calls a subroutine with strPrefix attached to the beginning of the event name. For example, if strPrefix is MYOBJ_ and the object fires an event named
OnBegin, WSH calls the MYOBJ_OnBegin subroutine located in the script.
If an object is registered as a single-instance object, only one instance of the object is created (regardless of how many times GetObject is executed). The GetObject method always returns the same instance when called with
the zero-length string syntax (""), and it causes an error if you do not supply the path parameter. You cannot use the GetObject method to obtain a reference to a Microsoft Visual Basic class created with Visual Basic 4.0 or
earlier.
Example

The following VBScript code starts the application associated with the specified file (strPathname):
Dim MyObject As Object
Set MyObject = GetObject("C:\CAD\SCHEMA.CAD")
MyApp = MyObject.Application

Some applications allow you to activate part of a file. To do this, add an exclamation mark (!) to the end of the file name, and follow it with a string that identifies the part of the file you want to activate. For example, in a
drawing application, a drawing stored in a file might have multiple layers. The following code activates a layer within a drawing file called SCHEMA.CAD:
Set LayerObject = GetObject("C:\CAD\SCHEMA.CAD!Layer3")

If you do not specify the object's class (strProgID), COM determines the application to start from the file name. Some files can support more than one class of object. For example, a drawing might support three different types
of objects: an application object, a drawing object, and a toolbar object. All may be part of the same file.
In the following VBScript code, the drawing application FIGMENT starts and opens the object DRAWING from within the file SAMPLE.DRW.
Dim MyObject As Object
Set MyObject = GetObject("C:\DRAWINGS\SAMPLE.DRW", "FIGMENT.DRAWING")

See Also
WScript Object | CreateObject Method | DisconnectObject Method

2001 Microsoft Corporation. All rights reserved.


Build: Topic Version 5.6.9309.1546
Windows Script Host

getResource Method
Returns the value of a resource defined with the <resource> element.
getResource(resourceID)

Arguments
resourceID
A string that uniquely identifies the resource information contained within a set of resource tags in a *.WSF script file.
Remarks
The getResource method returns a string. Use the <resource> element to isolate strings or numbers that are within the .wsf file and that you want to reference. This feature makes it easy to maintain a set of strings that are
localized into several languages. A WSH script file (*.wsf) can contain several different pieces of resource information each one with a unique resource identifier.
Example
The following WSH script defines a resource called errNonNumeric. The value of errNonNumeric is displayed if the parameter upperBound is not a number.
<package>
<job id="JS">
<resource id="errNonNumeric">Error: A non-numeric value was entered where a number was expected.</resource>
<script language="JScript">
function getRandomNumber(upperBound)
{
var realUpperBound = parseInt(upperBound);
if (!isNaN(realUpperBound))
return (realUpperBound * Math.random) + 1
else
{
WScript.Echo(getResource("errNonNumeric"));
WScript.Quit(-1);
}
}
NewValue = getRandomNumber("Bad Value");
</script>
</job>
<job id="VBS">
<resource id="errNonNumeric">Error: A non-numeric value was entered where a number was expected.</resource>
<script language="VBScript">
Function getRandomNumber(upperBound)
If IsNumeric(upperBound) Then
getRandomNumber = CInt(upperBound * Rnd + 1)
Else
WScript.Echo getResource("errNonNumeric")
WScript.Quit -1
End If
End Function
NewValue = getRandomNumber("Bad Value")
</script>
</job>
</package>

See Also
<resource> Element

2001 Microsoft Corporation. All rights reserved.


Build: Topic Version 5.6.9309.1546
Windows Script Host

LogEvent Method
Adds an event entry to a log file.
object.LogEvent(intType, strMessage [,strTarget])

Arguments

object
WshShell object.
intType
Integer value representing the event type.
strMessage
String value containing the log entry text.
strTarget
Optional. String value indicating the name of the computer system where the event log is stored (the default is the local computer system). Applies to Windows NT/2000 only.
Remarks
The LogEvent method returns a Boolean value (true if the event is logged successfully, otherwise false). In Windows NT/2000, events are logged in the Windows NT Event Log. In Windows 9x/Me, events are logged in
WSH.log (located in the Windows directory). There are six event types.
Type
0
1
2
4
8
16

Value
SUCCESS
ERROR
WARNING
INFORMATION
AUDIT_SUCCESS
AUDIT_FAILURE

Example
The following code logs SUCCESS or ERROR depending on the outcome of the function runLoginScript().
[VBScript]
Set WshShell = WScript.CreateObject("WScript.Shell")
rc = runLoginScript()
'Returns true if logon succeeds.
if rc then
WshShell.LogEvent 0, "Logon Script Completed Successfully"
else
WshShell.LogEvent 1, "Logon Script failed"
end if

[JScript]
var WshShell = WScript.CreateObject("WScript.Shell");
var rc = runLoginScript();
if (rc)
WshShell.LogEvent(0, "Logon Script Completed Successfully");
else
WshShell.LogEvent(1, "Logon Script failed");

See Also
WshShell Object

2001 Microsoft Corporation. All rights reserved.


Build: Topic Version 5.6.9309.1546
Windows Script Host

MapNetworkDrive Method
Adds a shared network drive to your computer system.
object.MapNetworkDrive(strLocalName, strRemoteName, [bUpdateProfile], [strUser], [strPassword])

Arguments
object
WshNetwork object.
strLocalName
String value indicating the name by which the mapped drive will be known locally.
strRemoteName
String value indicating the share's UNC name (\\xxx\yyy).
bUpdateProfile
Optional. Boolean value indicating whether the mapping information is stored in the current user's profile. If bUpdateProfile is supplied and has a value of true, the mapping is stored in the user profile (the default is
false).
strUser
Optional. String value indicating the user name. You must supply this argument if you are mapping a network drive using the credentials of someone other than the current user.
strPassword
Optional. String value indicating the user password. You must supply this argument if you are mapping a network drive using the credentials of someone other than the current user.
Remarks
An attempt to map a non-shared network drive results in an error.
Example
The following code maps the logical drive "E" to a network share with the UNC name "\\Server\Public."
[VBScript]
Dim WshNetwork
Set WshNetwork = WScript.CreateObject("WScript.Network")
WshNetwork.MapNetworkDrive "E:", "\\Server\Public"

[JScript]
var WshNetwork = WScript.CreateObject("WScript.Network");
WshNetwork.MapNetworkDrive ("E:", "\\\\Server\\Public");

See Also
WshNetwork Object | EnumNetworkDrives Method | RemoveNetworkDrive Method

2001 Microsoft Corporation. All rights reserved.

Build: Topic Version 5.6.9309.1546


Windows Script Host

Popup Method
Displays text in a pop-up message box.
intButton = object.Popup(strText,[nSecondsToWait],[strTitle],[nType])

Arguments
object
WshShell object.
strText
String value containing the text you want to appear in the pop-up message box.
nSecondsToWait
Optional. Numeric value indicating the maximum length of time (in seconds) you want the pop-up message box displayed.
strTitle
Optional. String value containing the text you want to appear as the title of the pop-up message box.
nType
Optional. Numeric value indicating the type of buttons and icons you want in the pop-up message box. These determine how the message box is used.
IntButton
Integer value indicating the number of the button the user clicked to dismiss the message box. This is the value returned by the Popup method.
Remarks
The Popup method displays a message box regardless of which host executable file is running (WScript.exe or CScript.exe). If nSecondsToWaitis equals zero (the default), the pop-up message box remains visible until closed by
the user. If nSecondsToWaitis is greater than zero, the pop-up message box closes after nSecondsToWait seconds. If you do not supply the argument strTitle, the title of the pop-up message box defaults to "Windows Script
Host." The meaning of nType is the same as in the Microsoft Win32 application programming interface MessageBox function. The following tables show the values and their meanings. You can combine values in these tables.
Note

Todisplay text properly in RTL languages such as Hebrew or Arabic, add hex &h00100000 (decimal 1048576) to the nType parameter.

Button Types
Value
0
1
2
3
4
5

Description
Show OK button.
Show OK and Cancel buttons.
Show Abort, Retry, and Ignore buttons.
Show Yes, No, and Cancel buttons.
Show Yes and No buttons.
Show Retry and Cancel buttons.

Icon Types
Value
16
32
48
64

Description
Show "Stop Mark" icon.
Show "Question Mark" icon.
Show "Exclamation Mark" icon.
Show "Information Mark" icon.

The previous two tables do not cover all values for nType. For a complete list, see the Microsoft Win32 documentation.
The return value intButton denotes the number of the button that the user clicked. If the user does not click a button before nSecondsToWait seconds, intButton is set to -1.
Value Description
1
OK button
2
Cancel button
3
Abort button
4
Retry button
5
Ignore button
6
Yes button
7
No button
Example
The following code generates a simple pop-up window.
[VBScript]
Dim WshShell, BtnCode
Set WshShell = WScript.CreateObject("WScript.Shell")
BtnCode = WshShell.Popup("Do you feel alright?", 7, "Answer This Question:", 4 + 32)
Select Case BtnCode
case 6
WScript.Echo "Glad to hear you feel alright."
case 7
WScript.Echo "Hope you're feeling better soon."
case -1
WScript.Echo "Is there anybody out there?"
End Select

[JScript]
var WshShell = WScript.CreateObject("WScript.Shell");
var BtnCode = WshShell.Popup("Do you feel alright?", 7, "Answer This Question:", 4 + 32);
switch(BtnCode) {
case 6:
WScript.Echo("Glad to hear you feel alright.");
break;
case 7:
WScript.Echo("Hope you're feeling better soon.");
break;
case -1:
WScript.Echo("Is there anybody out there?");
break;
}

See Also
WshShell Object | Echo Method

2001 Microsoft Corporation. All rights reserved.


Build: Topic Version 5.6.9309.1546
Windows Script Host

Quit Method
Forces script execution to stop at any time.
object.Quit([intErrorCode])

Arguments
object
WScript object.
intErrorCode
Optional. Integer value returned as the process's exit code. If you do not include the intErrorCode parameter, no value is returned.
Remarks
The Quit method can return an optional error code. If the Quit method is the final instruction in your script (and you have no need to return a non-zero value), you can leave it out, and your script will end normally.
Example
The following JScript code snippet quits execution and returns an error code of 1:
WScript.Quit (1);
// This line of code is never executed.
var i = 0;

See Also
WScript Object

2001 Microsoft Corporation. All rights reserved.


Build: Topic Version 5.6.9309.1546
Windows Script Host

Read Method
Returns a specified number of characters from an input stream.
object.Read(characters)

Arguments
object
StdIn text stream object.
characters
Integer value indicating the number of characters you want to read.
Remarks
The Read method returns a string. The StdIn, StdOut, and StdErr properties and methods work when running the script with the CScript.exe host executable file only. An error is returned when run with WScript.exe. Reading
begins at the current position pointer location and moves forward one character at a time.
The Read method does not return until the enter key is pressed. Only the number of characters requested will be returned. Any additional characters will be returned on subsequent calls to the Read, ReadLine, or ReadAll
methods.
Example
The following code uses the Read method to get a character from the keyboard and display it on the console.
[VBScript]
Dim Input
Input = ""
Do While Not WScript.StdIn.AtEndOfLine
Input = Input & WScript.StdIn.Read(1)
Loop
WScript.Echo Input

[JScript]
var input = "";
while (!WScript.StdIn.AtEndOfLine)
{
input += WScript.StdIn.Read(1);
}
WScript.Echo(input);

See Also
StdIn Property (WScript)

2001 Microsoft Corporation. All rights reserved.


Build: Topic Version 5.6.9309.1546
Windows Script Host

ReadAll Method
Returns all characters from an input stream.
object.ReadAll

Arguments
object
StdIn text stream object.
Remarks

The ReadAll method returns a string. The StdIn, StdOut, and StdErr properties and methods work when running the script with the CScript.exe host executable file only. An error is returned when run with WScript.exe.
Example
The following code demonstrates the use of ReadAll.
[VBScript]
Dim Input
Input = ""
Do While Not WScript.StdIn.AtEndOfStream
Input = Input & WScript.StdIn.ReadAll
Loop
WScript.Echo Input

[JScript]
var input = "";
while (!WScript.StdIn.AtEndOfStream)
{
input += WScript.StdIn.ReadAll();
}
WScript.Echo(input);

See Also
StdIn Property | FileSystemObject Object

2001 Microsoft Corporation. All rights reserved.


Build: Topic Version 5.6.9309.1546
Windows Script Host

ReadLine Method
Returns an entire line from an input stream.
object.ReadLine

Arguments
object
StdIn text stream object.
Remarks
The ReadLine method returns a string. The StdIn, StdOut, and StdErr properties and methods work when running the script with the CScript.exe host executable file only. An error is returned when run with WScript.exe. A
line is a sequence of characters that ends with a newline character.
Note

Although this methodextracts the newline character, it does not add it to the string.

Example
The following code demonstrates the use of the ReadLine method.
[VBScript]
Dim StdIn, StdOut
Set StdIn = WScript.StdIn
Set StdOut = WScript.StdOut
Do While Not StdIn.AtEndOfStream
str = StdIn.ReadLine
StdOut.WriteLine "Line " & (StdIn.Line - 1) & ": " & str
Loop

[JScript]
var stdin = WScript.StdIn;
var stdout = WScript.StdOut;
while (!stdin.AtEndOfStream)
{
var str = stdin.ReadLine();
stdout.WriteLine("Line " + (stdin.Line - 1) + ": " + str);
}

See Also
StdIn Property | FileSystemObject Object

2001 Microsoft Corporation. All rights reserved.


Build: Topic Version 5.6.9309.1546
Windows Script Host

RegDelete Method
Deletes a key or one of its values from the registry.
object.RegDelete(strName)

Arguments
object
WshShell object.
strName
String value indicating the name of the registry key or key value you want to delete.
Remarks
Specify a key-name by ending strName with a final backslash; leave it off to specify a value-name. Fully qualified key-names and value-names are prefixed with a root key. You may use abbreviated versions of root key names

with the RegDelete method. The five possible root keys you can use are listed in the following table.
Root key Name
Abbreviation
HKEY_CURRENT_USER HKCU
HKEY_LOCAL_MACHINE HKLM
HKEY_CLASSES_ROOT
HKCR
HKEY_USERS
HKEY_USERS
HKEY_CURRENT_CONFIG HKEY_CURRENT_CONFIG
Example
The following code creates a key and two values, reads them, and deletes them.
[VBScript]
Dim WshShell, bKey
Set WshShell = WScript.CreateObject("WScript.Shell")
WshShell.RegWrite "HKCU\Software\ACME\FortuneTeller\", 1, "REG_BINARY"
WshShell.RegWrite "HKCU\Software\ACME\FortuneTeller\MindReader", "Goocher!", "REG_SZ"
bKey = WshShell.RegRead("HKCU\Software\ACME\FortuneTeller\")
WScript.Echo WshShell.RegRead("HKCU\Software\ACME\FortuneTeller\MindReader")
WshShell.RegDelete "HKCU\Software\ACME\FortuneTeller\MindReader"
WshShell.RegDelete "HKCU\Software\ACME\FortuneTeller\"
WshShell.RegDelete "HKCU\Software\ACME\"

[JScript]
var WshShell = WScript.CreateObject("WScript.Shell");
WshShell.RegWrite ("HKCU\\Software\\ACME\\FortuneTeller\\", 1, "REG_BINARY");
WshShell.RegWrite ("HKCU\\Software\\ACME\\FortuneTeller\\MindReader", "Goocher!", "REG_SZ");
var bKey =
WshShell.RegRead ("HKCU\\Software\\ACME\\FortuneTeller\\");
WScript.Echo (WshShell.RegRead ("HKCU\\Software\\ACME\\FortuneTeller\\MindReader"));
WshShell.RegDelete ("HKCU\\Software\\ACME\\FortuneTeller\\MindReader");
WshShell.RegDelete ("HKCU\\Software\\ACME\\FortuneTeller\\");
WshShell.RegDelete ("HKCU\\Software\\ACME\\");

See Also
WshShell Object | RegRead Method | RegWrite Method

2001 Microsoft Corporation. All rights reserved.


Build: Topic Version 5.6.9309.1546
Windows Script Host

RegRead Method
Returns the value of a key or value-name from the registry.
object.RegRead(strName)

Arguments
object
WshShell object.
strName
String value indicating the key or value-name whose value you want.
Remarks
The RegRead method returns values of the following five types.
Type
Description
REG_SZ
A string
REG_DWORD
A number
REG_BINARY
A binary value
REG_EXPAND_SZ An expandable string
(e.g., "%windir%\\calc.exe")
REG_MULTI_SZ An array of strings

In the Form of
A string
An integer
A VBArray of integers
A string
A VBArray of strings

You can specify a key-name by ending strName with a final backslash. Do not include a final backslash to specify a value-name. A value entry has three parts: its name, its data type, and its value. When you specify a key-name
(as opposed to a value-name), RegRead returns the default value. To read a key's default value, specify the name of the key itself. Fully qualified key-names and value-names begin with a root key. You may use abbreviated
versions of root key names with the RegRead method. The five possible root keys are listed in the following table.
Root key Name
Abbreviation
HKEY_CURRENT_USER HKCU
HKEY_LOCAL_MACHINE HKLM
HKEY_CLASSES_ROOT
HKCR
HKEY_USERS
HKEY_USERS
HKEY_CURRENT_CONFIG HKEY_CURRENT_CONFIG
Example
The following code creates a key and two values, reads them, and deletes them.
[VBScript]
Dim WshShell, bKey
Set WshShell = WScript.CreateObject("WScript.Shell")
WshShell.RegWrite "HKCU\Software\ACME\FortuneTeller\", 1, "REG_BINARY"
WshShell.RegWrite "HKCU\Software\ACME\FortuneTeller\MindReader", "Goocher!", "REG_SZ"
bKey = WshShell.RegRead("HKCU\Software\ACME\FortuneTeller\")
WScript.Echo WshShell.RegRead("HKCU\Software\ACME\FortuneTeller\MindReader")
WshShell.RegDelete "HKCU\Software\ACME\FortuneTeller\MindReader"
WshShell.RegDelete "HKCU\Software\ACME\FortuneTeller\"
WshShell.RegDelete "HKCU\Software\ACME\"

[JScript]

var WshShell = WScript.CreateObject ("WScript.Shell");


WshShell.RegWrite ("HKCU\\Software\\ACME\\FortuneTeller\\", 1, "REG_BINARY");
WshShell.RegWrite ("HKCU\\Software\\ACME\\FortuneTeller\\MindReader", "Goocher!", "REG_SZ");
var bKey =
WshShell.RegRead ("HKCU\\Software\\ACME\\FortuneTeller\\");
WScript.Echo (WshShell.RegRead ("HKCU\\Software\\ACME\\FortuneTeller\\MindReader"));
WshShell.RegDelete ("HKCU\\Software\\ACME\\FortuneTeller\\MindReader");
WshShell.RegDelete ("HKCU\\Software\\ACME\\FortuneTeller\\");
WshShell.RegDelete ("HKCU\\Software\\ACME\\");

See Also
WshShell Object | RegDelete Method | RegWrite Method

2001 Microsoft Corporation. All rights reserved.


Build: Topic Version 5.6.9309.1546
Windows Script Host

RegWrite Method
Creates a new key, adds another value-name to an existing key (and assigns it a value), or changes the value of an existing value-name.
object.RegWrite(strName, anyValue [,strType])

Arguments
object
WshShell object.
strName
String value indicating the key-name, value-name, or value you want to create, add, or change.
anyValue
The name of the new key you want to create, the name of the value you want to add to an existing key, or the new value you want to assign to an existing value-name.
strType
Optional. String value indicating the value's data type.
Remarks
Specify a key-name by ending strName with a final backslash. Do not include a final backslash to specify a value name. The RegWrite method automatically converts the parameter anyValue to either a string or an integer. The
value of strType determines its data type (either a string or an integer). The options for strType are listed in the following table.
Converted to
strType
String
REG_SZ
String
REG_EXPAND_SZ
Integer
REG_DWORD
Integer
REG_BINARY
Note

The REG_MULTI_SZ type isnot supported for the RegWrite method.

Tip RegWrite will write at most one DWORD to a REG_BINARY value. Larger values are not supported with this method.
Fully qualified key-names and value-names are prefixed with a root key. You may use abbreviated versions of root key names with the RegWrite method. The five root keys are listed in the following table.
Root key Name
Abbreviation
HKEY_CURRENT_USER HKCU
HKEY_LOCAL_MACHINE HKLM
HKEY_CLASSES_ROOT
HKCR
HKEY_USERS
HKEY_USERS
HKEY_CURRENT_CONFIG HKEY_CURRENT_CONFIG
The four possible data types you can specify with strType are listed in the following table.
Type
Description
REG_SZ
A string
REG_DWORD
A number
REG_BINARY
A binary value
REG_EXPAND_SZ An expandable string
(e.g., "%windir%\\calc.exe")

In the Form of
A string
An integer
An integer
A string

Example
The following code creates a key and two values, reads them, and deletes them.
[VBScript]
Dim WshShell, bKey
Set WshShell = WScript.CreateObject("WScript.Shell")
WshShell.RegWrite "HKCU\Software\ACME\FortuneTeller\", 1, "REG_BINARY"
WshShell.RegWrite "HKCU\Software\ACME\FortuneTeller\MindReader", "Goocher!", "REG_SZ"
bKey = WshShell.RegRead("HKCU\Software\ACME\FortuneTeller\")
WScript.Echo WshShell.RegRead("HKCU\Software\ACME\FortuneTeller\MindReader")
WshShell.RegDelete "HKCU\Software\ACME\FortuneTeller\MindReader"
WshShell.RegDelete "HKCU\Software\ACME\FortuneTeller\"
WshShell.RegDelete "HKCU\Software\ACME\"

[JScript]
var WshShell = WScript.CreateObject("WScript.Shell");
WshShell.RegWrite ("HKCU\\Software\\ACME\\FortuneTeller\\", 1, "REG_BINARY");
WshShell.RegWrite ("HKCU\\Software\\ACME\\FortuneTeller\\MindReader", "Goocher!", "REG_SZ");
var bKey =
WshShell.RegRead ("HKCU\\Software\\ACME\\FortuneTeller\\");
WScript.Echo (WshShell.RegRead ("HKCU\\Software\\ACME\\FortuneTeller\\MindReader"));
WshShell.RegDelete ("HKCU\\Software\\ACME\\FortuneTeller\\MindReader");
WshShell.RegDelete ("HKCU\\Software\\ACME\\FortuneTeller\\");
WshShell.RegDelete ("HKCU\\Software\\ACME\\");

See Also
WshShell Object | RegDelete Method | RegRead Method

2001 Microsoft Corporation. All rights reserved.


Build: Topic Version 5.6.9309.1546
Windows Script Host

Remove Method
Removes an existing environment variable.
object.Remove(strName)

Arguments
object
WshEnvironment object.
strName
String value indicating the name of the environment variable you want to remove.
Remarks
The Remove method removes environment variables from the following types of environments: PROCESS, USER, SYSTEM, and VOLATILE. Environment variables removed with the Remove method are not removed
permanently; they are only removed for the current session.
Example
The following code removes the Process environment variable TestVar.
[VBScript]
Dim WshShell, WshEnv
Set WshShell = WScript.CreateObject("WScript.Shell")
Set WshEnv = WshShell.Environment("PROCESS")
WshEnv("TestVar") = "Windows Script Host"
WScript.Echo WshShell.ExpandEnvironmentStrings("The value of the test variable is: '%TestVar%'")
WshEnv.Remove "TestVar"
WScript.Echo WshShell.ExpandEnvironmentStrings("The value of the test variable is: '%TestVar%'")

[JScript]
var WshShell = WScript.CreateObject("WScript.Shell");
var WshEnv = WshShell.Environment("PROCESS");
WshEnv("TestVar") = "Windows Script Host";
WScript.Echo(WshShell.ExpandEnvironmentStrings("The value of the test variable is: '%TestVar%'"));
WshEnv.Remove("TestVar");
WScript.Echo(WshShell.ExpandEnvironmentStrings("The value of the test variable is: '%TestVar%'"));

See Also
WshEnvironment Object | Environment Property

2001 Microsoft Corporation. All rights reserved.


Build: Topic Version 5.6.9309.1546
Windows Script Host

RemoveNetworkDrive Method
Removes a shared network drive from your computer system.
object.RemoveNetworkDrive(strName, [bForce], [bUpdateProfile])

Arguments
object
WshNetwork object.
strName
String value indicating the name of the mapped drive you want to remove. The strName parameter can be either a local name or a remote name depending on how the drive is mapped.
bForce
Optional. Boolean value indicating whether to force the removal of the mapped drive. If bForce is supplied and its value is true, this method removes the connections whether the resource is used or not.
bUpdateProfile
Optional. String value indicating whether to remove the mapping from the user's profile. If bUpdateProfile is supplied and its value is true, this mapping is removed from the user profile. bUpdateProfile is false by
default.
Remarks
If the drive has a mapping between a local name (drive letter) and a remote name (UNC name), then strName must be set to the local name. If the network path does not have a local name (drive letter) mapping, then strName
must be set to the remote name.
Example
The following code removes the logical drive "E."
[VBScript]
Dim WshNetwork
Set WshNetwork = WScript.CreateObject("WScript.Network")
WshNetwork.RemoveNetworkDrive "E:"

[JScript]
var WshNetwork = WScript.CreateObject("WScript.Network");
WshNetwork.RemoveNetworkDrive ("E:");

See Also
WshNetwork Object | EnumNetworkDrives Method | MapNetworkDrive Method

2001 Microsoft Corporation. All rights reserved.

Build: Topic Version 5.6.9309.1546


Windows Script Host

RemovePrinterConnection Method
Removes a shared network printer connection from your computer system.
object.RemovePrinterConnection(strName, [bForce], [bUpdateProfile])

Arguments
object
WshNetwork object.
strName
String value indicating the name that identifies the printer. It can be a UNC name (in the form \\xxx\yyy) or a local name (such as LPT1).
bForce
Optional. Boolean value indicating whether to force the removal of the mapped printer. If set to true (the default is false), the printer connection is removed whether or not a user is connected.
bUpdateProfile
Optional. Boolean value. If set to true (the default is false), the change is saved in the user's profile.
Remarks
The RemovePrinterConnection method removes both Windows and MS-DOS based printer connections. If the printer was connected using the method AddPrinterConnection, strName must be the printer's local name. If the
printer was connected using the AddWindowsPrinterConnection method or was added manually (using the Add Printer wizard), then strName must be the printer's UNC name.
Example
The following code disconnects a network printer.
[VBScript]
Set WshNetwork = WScript.CreateObject("WScript.Network")
PrinterPath = "\\printserv\DefaultPrinter"
WshNetwork.RemovePrinterConnection PrinterPath, true, true

[JScript]
var WshNetwork = WScript.CreateObject("WScript.Network");
var PrinterPath = "\\\\PRN-CORP1\\B41-4523-A";
WshNetwork.RemovePrinterConnection(PrinterPath, true, true);

See Also
WshNetwork Object | AddPrinterConnection Method | AddWindowsPrinterConnection Method | EnumPrinterConnections Method | SetDefaultPrinter Method

2001 Microsoft Corporation. All rights reserved.


Build: Topic Version 5.6.9309.1546
Windows Script Host

Run Method
Runs a program in a new process.
object.Run(strCommand, [intWindowStyle], [bWaitOnReturn])

Arguments
object
WshShell object.
strCommand
String value indicating the command line you want to run. You must include any parameters you want to pass to the executable file.
intWindowStyle
Optional. Integer value indicating the appearance of the program's window. Note that not all programs make use of this information.
bWaitOnReturn
Optional. Boolean value indicating whether the script should wait for the program to finish executing before continuing to the next statement in your script. If set to true, script execution halts until the program finishes,
and Run returns any error code returned by the program. If set to false (the default), the Run method returns immediately after starting the program, automatically returning 0 (not to be interpreted as an error code).
Remarks
The Run method returns an integer. The Run method starts a program running in a new Windows process. You can have your script wait for the program to finish execution before continuing. This allows you to run scripts and
programs synchronously. Environment variables within the argument strCommand are automatically expanded. If a file type has been properly registered to a particular program, calling run on a file of that type executes the
program. For example, if Word is installed on your computer system, calling Run on a *.doc file starts Word and loads the document. The following table lists the available settings for intWindowStyle.
intWindowStyle
0
1
2
3
4
5
6
7
8
9
10

Description
Hides the window and activates another window.
Activates and displays a window. If the window is minimized or maximized, the system restores it to its original size and position. An application should specify this flag
when displaying the window for the first time.
Activates the window and displays it as a minimized window.
Activates the window and displays it as a maximized window.
Displays a window in its most recent size and position. The active window remains active.
Activates the window and displays it in its current size and position.
Minimizes the specified window and activates the next top-level window in the Z order.
Displays the window as a minimized window. The active window remains active.
Displays the window in its current state. The active window remains active.
Activates and displays the window. If the window is minimized or maximized, the system restores it to its original size and position. An application should specify this flag
when restoring a minimized window.
Sets the show-state based on the state of the program that started the application.

Example 1
The following VBScript code opens a copy of the currently running script with Notepad.
Set WshShell = WScript.CreateObject("WScript.Shell")
WshShell.Run "%windir%\notepad " & WScript.ScriptFullName

The following VBScript code does the same thing, except it specifies the window type, waits for Notepad to be shut down by the user, and saves the error code returned from Notepad when it is shut down.
Set WshShell = WScript.CreateObject("WScript.Shell")
Return = WshShell.Run("notepad " & WScript.ScriptFullName, 1, true)

Example 2

The following VBScript code opens a command window, changes to the path to C:\ , and executes the DIR command.
Dim oShell
Set oShell = WScript.CreateObject ("WSCript.shell")
oShell.run "cmd /K CD C:\ & Dir"
Set oShell = Nothing

See Also
WshShell Object

2001 Microsoft Corporation. All rights reserved.


Build: Topic Version 5.6.9309.1546
Windows Script Host

Save Method
Saves a shortcut object to disk.
object.Save

Arguments
object
WshShortcut or WshUrlShortcut object.
Remarks
After using the CreateShortcut method to create a shortcut object and set the shortcut object's properties, the Save method must be used to save the shortcut object to disk. The Save method uses the information in the shortcut
object's FullName property to determine where to save the shortcut object on a disk. You can only create shortcuts to system objects. This includes files, directories, and drives (but does not include printer links or scheduled
tasks).
Example
The following example demonstrates the use of a single .wsf file for two jobs in different script languages (VBScript and JScript). Each job creates a shortcut to the script being run and a URLshortcut to www.microsoft.com.
<package>
<job id="vbs">
<script language="VBScript">
set WshShell = WScript.CreateObject("WScript.Shell")
strDesktop = WshShell.SpecialFolders("Desktop")
set oShellLink = WshShell.CreateShortcut(strDesktop & "\Shortcut Script.lnk")
oShellLink.TargetPath = WScript.ScriptFullName
oShellLink.WindowStyle = 1
oShellLink.Hotkey = "CTRL+SHIFT+F"
oShellLink.IconLocation = "notepad.exe, 0"
oShellLink.Description = "Shortcut Script"
oShellLink.WorkingDirectory = strDesktop
oShellLink.Save
set oUrlLink = WshShell.CreateShortcut(strDesktop & "\Microsoft Web Site.url")
oUrlLink.TargetPath = "http://www.microsoft.com"
oUrlLink.Save
</script>
</job>
<job id="js">
<script language="JScript">
var WshShell = WScript.CreateObject("WScript.Shell");
strDesktop = WshShell.SpecialFolders("Desktop");
var oShellLink = WshShell.CreateShortcut(strDesktop + "\\Shortcut Script.lnk");
oShellLink.TargetPath = WScript.ScriptFullName;
oShellLink.WindowStyle = 1;
oShellLink.Hotkey = "CTRL+SHIFT+F";
oShellLink.IconLocation = "notepad.exe, 0";
oShellLink.Description = "Shortcut Script";
oShellLink.WorkingDirectory = strDesktop;
oShellLink.Save();
var oUrlLink = WshShell.CreateShortcut(strDesktop + "\\Microsoft Web Site.url");
oUrlLink.TargetPath = "http://www.microsoft.com";
oUrlLink.Save();
</script>
</job>
</package>

See Also
Running Your Scripts | WshShortcut Object | WshUrlShortcut Object | FullName Property | TargetPath Property | WindowStyle Property | Hotkey Property | IconLocation Property | Description Property | WorkingDirectory
Property

2001 Microsoft Corporation. All rights reserved.


Build: Topic Version 5.6.9309.1546
Windows Script Host

SendKeys Method
Sends one or more keystrokes to the active window (as if typed on the keyboard).
object.SendKeys(string)

Arguments
object
WshShell object.
string
String value indicating the keystroke(s) you want to send.
Remarks
Use the SendKeys method to send keystrokes to applications that have no automation interface. Most keyboard characters are represented by a single keystroke. Some keyboard characters are made up of combinations of
keystrokes (CTRL+SHIFT+HOME, for example). To send a single keyboard character, send the character itself as the string argument. For example, to send the letter x, send the string argument "x".
Note

Tosend a space, send the string " ".

You can use SendKeys to send more than one keystroke at a time. To do this, create a compound string argument that represents a sequence of keystrokes by appending each keystroke in the sequence to the one before it. For
example, to send the keystrokes a, b, and c, you would send the string argument "abc". The SendKeys method uses some characters as modifiers of characters (instead of using their face-values). This set of special characters
consists of parentheses, brackets, braces, and the:

plus sign
"+",
caret
"^",
percent sign "%",
and tilde
"~"

Send these characters by enclosing them within braces "{}". For example, to send the plus sign, send the string argument "{+}". Brackets "[ ]" have no special meaning when used with SendKeys, but you must enclose them
within braces to accommodate applications that do give them a special meaning (for dynamic data exchange (DDE) for example).

To send bracket characters, send the string argument "{[}" for the left bracket and "{]}" for the right one.
To send brace characters, send the string argument "{{}" for the left brace and "{}}" for the right one.

Some keystrokes do not generate characters (such as ENTER and TAB). Some keystrokes represent actions (such as BACKSPACE and BREAK). To send these kinds of keystrokes, send the arguments shown in the following
table:
Key
BACKSPACE
BREAK
CAPS LOCK
DEL or DELETE
DOWN ARROW
END
ENTER
ESC
HELP
HOME
INS or INSERT
LEFT ARROW
NUM LOCK
PAGE DOWN
PAGE UP
PRINT SCREEN
RIGHT ARROW
SCROLL LOCK
TAB
UP ARROW
F1
F2
F3
F4
F5
F6
F7
F8
F9
F10
F11
F12
F13
F14
F15
F16

Argument
{BACKSPACE}, {BS}, or {BKSP}
{BREAK}
{CAPSLOCK}
{DELETE} or {DEL}
{DOWN}
{END}
{ENTER} or ~
{ESC}
{HELP}
{HOME}
{INSERT} or {INS}
{LEFT}
{NUMLOCK}
{PGDN}
{PGUP}
{PRTSC}
{RIGHT}
{SCROLLLOCK}
{TAB}
{UP}
{F1}
{F2}
{F3}
{F4}
{F5}
{F6}
{F7}
{F8}
{F9}
{F10}
{F11}
{F12}
{F13}
{F14}
{F15}
{F16}

To send keyboard characters that are comprised of a regular keystroke in combination with a SHIFT, CTRL, or ALT, create a compound string argument that represents the keystroke combination. You do this by preceding the
regular keystroke with one or more of the following special characters:
Key
SHIFT
CTRL
ALT

Special Character
+
^
%

Note When used this way, these special characters are not enclosed within a set of braces.
To specify that a combination of SHIFT, CTRL, and ALT should be held down while several other keys are pressed, create a compound string argument with the modified keystrokes enclosed in parentheses. For example, to
send the keystroke combination that specifies that the SHIFT key is held down while:

e and c are pressed, send the string argument "+(ec)".


e is pressed, followed by a lone c (with no SHIFT), send the string argument "+ec".

You can use the SendKeys method to send a pattern of keystrokes that consists of a single keystroke pressed several times in a row. To do this, create a compound string argument that specifies the keystroke you want to repeat,
followed by the number of times you want it repeated. You do this using a compound string argument of the form {keystroke number}. For example, to send the letter "x" ten times, you would send the string argument "{x 10}".
Be sure to include a space between keystroke and number.
Note The only keystroke pattern you can send is the kind that is comprised of a single keystroke pressed several times. For example, you can send "x" ten times, but you cannot do the same for "Ctrl+x".
Note You cannot send the PRINT SCREEN key {PRTSC} to an application.
Example
The following example demonstrates the use of a single .wsf file for two jobs in different script languages (VBScript and JScript). Each job runs the Windows calculator and sends it keystrokes to execute a simple calculation.
<package>
<job id="vbs">
<script language="VBScript">
set WshShell = WScript.CreateObject("WScript.Shell")
WshShell.Run "calc"
WScript.Sleep 100
WshShell.AppActivate "Calculator"
WScript.Sleep 100
WshShell.SendKeys "1{+}"
WScript.Sleep 500
WshShell.SendKeys "2"
WScript.Sleep 500
WshShell.SendKeys "~"
WScript.Sleep 500
WshShell.SendKeys "*3"
WScript.Sleep 500
WshShell.SendKeys "~"
WScript.Sleep 2500
</script>
</job>
<job id="js">
<script language="JScript">
var WshShell = WScript.CreateObject("WScript.Shell");
WshShell.Run("calc");

WScript.Sleep(100);
WshShell.AppActivate("Calculator");
WScript.Sleep(100);
WshShell.SendKeys ("1{+}");
WScript.Sleep(500);
WshShell.SendKeys("2");
WScript.Sleep(500);
WshShell.SendKeys("~");
WScript.Sleep(500);
WshShell.SendKeys("*3");
WScript.Sleep(500);
WshShell.SendKeys("~");
WScript.Sleep(2500);
</script>
</job>
</package>

See Also
WshShell Object | Run Method

2001 Microsoft Corporation. All rights reserved.


Build: Topic Version 5.6.9309.1546
Windows Script Host

SetDefaultPrinter Method
Assigns a remote printer the role Default Printer.
object.SetDefaultPrinter(strPrinterName)

Arguments
object
WshNetwork object.
strPrinterName
String value indicating the remote printer's UNC name.
Remarks
The SetDefaultPrinter method fails when using a DOS-based printer connection. You cannot use the SetDefaultPrinter method to determine the name of the current default printer.
Example
The following code uses the AddWindowsPrinterConnection method to connect a network printer and set it as the default printer.
[VBScript]
Set WshNetwork = WScript.CreateObject("WScript.Network")
PrinterPath = "\\research\library1"
WshNetwork.AddWindowsPrinterConnection PrinterPath
WshNetwork.SetDefaultPrinter PrinterPath

[JScript]
var WshNetwork = WScript.CreateObject("WScript.Network");
var PrinterPath = "\\\\research\\library1";
WshNetwork.AddWindowsPrinterConnection(PrinterPath);
WshNetwork.SetDefaultPrinter(PrinterPath);

See Also
WshNetwork Object | AddPrinterConnection Method | AddWindowsPrinterConnection Method | EnumPrinterConnections Method | RemovePrinterConnection Method

2001 Microsoft Corporation. All rights reserved.


Build: Topic Version 5.6.9309.1546
Windows Script Host

ShowUsage Method
Makes a script self-documenting by displaying information about how it should be used.
object.ShowUsage

Parameters
object
WScript Object.
Remarks
When you run the ShowUsage method, a help screen (referred to as the usage) appears and displays details about the script's command line options. This information comes from the runtime section of the *.WSF file.
Everything written between the <runtime> and </runtime> tags is pieced together to produce what is called a "usage statement." The usage statement tells the user how to use the script.
Note

The usage can also be displayed using the/? switch.

Example
The following example demonstrates how to set up usage information in a *.WSF script file.
<job>
<runtime>
<description>This script reboots a server</description>
<named
name = "Server"
helpstring = "Server to run the script on"
type = "string"
required = "true"
/>
<example>Example: reboot.wsf /server:scripting</example>
</runtime>
<script language="VBScript">

If WScript.Arguments.Count <> 1 Then


WScript.Arguments.ShowUsage
WScript.Quit
End If
</script>
</job>

The JScript code for the equivalent script block would be:
if (WScript.Arguments.length != 1)
{
WScript.Arguments.ShowUsage();
WScript.Quit();
}

Calling the ShowUsage method from this script results in the following output:
This script reboots a server
Usage: reboot.wsf /server:value
Options:
server : Server to run the script onExample:
reboot.wsf /server:scripting

See Also
WScript Object

2001 Microsoft Corporation. All rights reserved.


Build: Topic Version 5.6.9309.1546
Windows Script Host

Sign Method
Signs a script stored in a string.
Object.Sign (FileExtension, Text, Certificate, Store)

Arguments
object
Scripting.Signer
FileExtension
A string designating the script extension type (.vbs, .js, or .wsf). This provides a mechanism by which the operating system can determine the type of script file being verified.
Text
A string containing the script to be signed.
Certificate
A string designating the author's certificate name.
Store
Optional. A string designating the name of the certificate store. Typically certificates that contain private keys i.e., certificates you can use for code signing are in a certificate store called "my". The default value is
"my".
Remarks
The Sign method is used to digitally sign a script stored in a string. In order to create a digital signature, the caller must have a valid certificate.
Example
Dim Signer, UnsignedText, SignedText
Set Signer = CreateObject("Scripting.Signer")
UnsignedText = _
"Dim X " & vbCrLf & _
"X = 123" & vbCrLf & _
"WScript.Echo X" & vbCrLf
SignedText = Signer.Sign(".VBS", UnsignedText, "Your Certificate Name Here")

See Also
Scripting.Signer Object | SignFile Method | Verify Method | VerifyFileMethod | Signing a Script

2001 Microsoft Corporation. All rights reserved.


Build: Topic Version 5.6.9309.1546
Windows Script Host

SignFile Method
Signs a script using a digital signature.
Object.SignFile (FileName, Certificate, Store)

Arguments
object
Scripting.Signer
FileName
A string containing the name of the script file.
Certificate
A string designating the author's certificate name.
Store
An optional string designating the name of the certificate store. Typically certificates that contain private keys i.e., certificates you can use for code signing are in a certificate store called "my". The default value is
"my".
Remarks
In order to sign a digital signature, the author must have a valid certificate.
Example
The following example demonstrates not only signature checking but also the command-line argument.

<job>
<runtime>
<named name="file" helpstring="the file to sign" required="true" type="string"/>
<named name="cert" helpstring="the name of the signing certificate" required="true" type="string"/>
<named name="store" helpstring="the name of the certificate store" required="false" type="string"/>
</runtime>
<script language="vbscript">
Dim Signer, File, Cert, Store
If Not (WScript.Arguments.Named.Exists("cert") And WScript.Arguments.Named.Exists("file")) Then
WScript.Arguments.ShowUsage
WScript.Quit
End If
Set Signer = CreateObject("Scripting.Signer")
File = WScript.Arguments.Named("file")
Cert = WScript.Arguments.Named("cert")
If WScript.Arguments.Named.Exists("store") Then
Store = WScript.Arguments.Named("store")
Else
Store = "my"
End If
Signer.SignFile File, Cert, Store
</script>
</job>

See Also
Scripting.Signer Object | Sign Method | Verify Method | VerifyFile Method | Signing a Script

2001 Microsoft Corporation. All rights reserved.


Build: Topic Version 5.6.9309.1546
Windows Script Host

Skip Method
Skips a specified number of characters when reading from an input text stream.
object.Skip(characters)

Arguments
object
StdIn text stream object.
characters
Integer value indicating the number of characters you want to skip.
Remarks
The StdIn, StdOut, and StdErr properties and methods work when running the script with the CScript.exe host executable file only. An "Invalid Handle" error is returned when run with WScript.exe. The position pointer moves
forward by the number of characters (bytes) specified in the argument characters. You cannot use the Skip method to skip backwards through a file (negative character values are not supported). The Skip method is limited to
the open for reading mode only (you cannot skip a specified number of characters when writing to an output stream).
Example
The following code uses the Skip method to jump over the first character in a text stream, read a line from the keyboard, and write it to the StdOut text stream.
[VBScript]
WScript.StdIn.Skip 1
Input = WScript.StdIn.ReadLine
WScript.StdOut.Write Input

[JScript]
WScript.StdIn.Skip(1);
Input = WScript.StdIn.ReadLine();
WScript.StdOut.Write(Input);

See Also
StdIn Property

2001 Microsoft Corporation. All rights reserved.


Build: Topic Version 5.6.9309.1546
Windows Script Host

SkipLine Method
Skips the next line when reading from an input text stream.
object.SkipLine

Arguments
object
StdIn text stream object.
Remarks
A line is a sequence of characters that ends with a newline character. The StdIn, StdOut, and StdErr properties and methods work when running the script with the CScript.exe host executable file only. An "Invalid Handle"
error is returned when run with WScript.exe. The position pointer moves forward to the point just past the next newline character. You cannot use the SkipLine method to skip backwards through a file. The SkipLine method is
limited to the open for reading mode only (you cannot skip lines when writing to an output stream).
Example
The following code demonstrates the SkipLine method.
[VBScript]
Dim StdIn, StdOut, Str1, Str2
Set StdIn = WScript.StdIn
Set StdOut = WScript.StdOut

Str1 = ""
Str2 = ""
For i = 0 to 4
StdIn.SkipLine
Next
i = 0
Do While Not StdIn.AtEndOfStream
If i >= 2 Then
StdOut.WriteLine Str1
End If
i = i + 1
Str1 = Str2
Str2 = StdIn.ReadLine
Loop

[JScript]
var
var
var
var
for

stdin = WScript.StdIn;
stdout = WScript.StdOut;
str1, str2 = "";
i;
(i = 0; i < 5; i++)
stdin.SkipLine();
i = 0;
while (!stdin.AtEndOfStream)
{
if (i++ >= 2)
{
stdout.WriteLine(str1);
}
str1 = str2;
str2 = stdin.ReadLine();
}

See Also
StdIn Property

2001 Microsoft Corporation. All rights reserved.


Build: Topic Version 5.6.9309.1546
Windows Script Host

Sleep Method
Suspends script execution for a specified length of time, then continues execution.
object.Sleep(intTime)

Arguments
object
WScript object.
intTime
Integer value indicating the interval (in milliseconds) you want the script process to be inactive.
Remarks
The thread running the script is suspended, releasing its CPU utilization. Execution resumes as soon as the interval expires. Using the Sleep method can be useful when you are running asynchronous operations, multiple
processes, or if your script includes code triggered by an event. To be triggered by an event, a script must be continually active (a script that has finished executing will certainly not detect an event). Events handled by the script
will still be executed during a sleep.
Note

Passing theSleep method a 0 or 1 does not cause the script to suspend indefinitely.

Example
The following example demonstrates the use of a single .wsf file for two jobs in different script languages (VBScript and JScript). The functionality of both jobs is the same each runs the Windows calculator and sends it
keystrokes to execute a simple calculation.
<package>
<job id="vbs">
<script language="VBScript">
set WshShell = WScript.CreateObject("WScript.Shell")
WshShell.Run "calc"
WScript.Sleep 100
WshShell.AppActivate "Calculator"
WScript.Sleep 100
WshShell.SendKeys "1{+}"
WScript.Sleep 500
WshShell.SendKeys "2"
WScript.Sleep 500
WshShell.SendKeys "~"
WScript.Sleep 500
WshShell.SendKeys "*3"
WScript.Sleep 500
WshShell.SendKeys "~"
WScript.Sleep 2500
</script>
</job>
<job id="js">
<script language="JScript">
var WshShell = WScript.CreateObject("WScript.Shell");
WshShell.Run("calc");
WScript.Sleep(100);
WshShell.AppActivate("Calculator");
WScript.Sleep(100);
WshShell.SendKeys("1{+}");
WScript.Sleep(500);
WshShell.SendKeys("2");
WScript.Sleep(500);
WshShell.SendKeys("~");
WScript.Sleep(500);
WshShell.SendKeys("*3");
WScript.Sleep(500);
WshShell.SendKeys("~");
WScript.Sleep(2500);
</script>
</job>
</package>

See Also

Running Your Scripts | WScript Object

2001 Microsoft Corporation. All rights reserved.


Build: Topic Version 5.6.9309.1546
Windows Script Host

Terminate Method (WshScriptExec)


Instructs the script engine to end the process started by the Exec method.
object.Terminate

Arguments
object
WshScriptExec object.
Remarks
The Terminate method does not return a value. Use the Terminate method only as a last resort since some applications do not clean up properly. As a general rule, let the process run its course and end on its own. The
Terminate method attempts to end a process using the WM_CLOSE message. If that does not work, it kills the process immediately without going through the normal shutdown procedure.
Example
The following JScript example demonstrates how to use the Terminate method to stop a running script.
var aScript = WScript.Exec("%comspec% /c myScript.js");
aScript.Terminate();

See Also
WshScriptExec Object

2001 Microsoft Corporation. All rights reserved.


Build: Topic Version 5.6.9309.1546
Windows Script Host

Verify Method
Verifies a digital signature retrieved as a string.
object.Verify (FileExtension, Text, ShowUI)

Arguments
object
Scripting.Signer
FileExtension
A string designating the script extension type (.vbs, .js, or .wsf). This provides a mechanism by which the operating system can determine the type of script file being verified.
Text
The text to verify.
ShowUI
A Boolean value. If the ShowUI argument is false, then the Scripting.Signer object determines whether a trusted source provided the signature without prompting the user. If it is true then the Scripting.Signer object may
create dialog boxes to prompt the user if there is not sufficient information to determine trust.
Note

On some operatingsystems, the operating system also creates a dialog box if the flag is on, the file is trusted, and you have not already checked the "Always trust " option.

Remarks
The Verify method is used to verify a digital signed script stored in a string.
Example
In this example the Verify method determines whether the script in the UnsignedText variable is trusted. (In this example there is no digital signature, so the Scripting.Signer object asks the user whether to extend trust.)
Dim Signer, UnsignedText, Trusted
Set Signer = CreateObject("Scripting.Signer")
UnsignedText = _
"Dim X " & vbCrLf & _
"X = 123" & vbCrLf & _
"WScript.Echo X" & vbCrLf
Trusted = Signer.Verify(".VBS", UnsignedText, True)

See Also
Scripting.Signer Object | VerifyFile Method | Sign Method | SignFile Method | Verifying a Script

2001 Microsoft Corporation. All rights reserved.


Build: Topic Version 5.6.9309.1546
Windows Script Host

VerifyFile Method
Verifies the digital signature encapsulated in a script.
Object.VerifyFile (FileName, ShowUI)

Arguments
object
Scripting.Signer
FileName

A string containing the name of the script file.


ShowUI
A Boolean value. If the ShowUI argument is false, then the Scripting.Signer object determines whether a trusted source provided the signature without prompting the user. If it is true then the Scripting.Signer object may
create dialog boxes to prompt the user if there is not sufficient information to determine trust.
Note

On some operating systems, the operatingsystem also creates a dialog box if the flag is on, the file is trusted, and you have not already checked the "Always trust " option.

Example
The following example demonstrates signature checking using the command-line argument processing features.
<job>
<runtime>
<named name="file" helpstring="the file to sign" required="true" type="string"/>
<named name="UI" helpstring="produce user interface for untrusted scripts" required="false"/>
</runtime>
<script language="vbscript">
Dim Signer, File, UI, OK
If Not WScript.Arguments.Named.Exists("file") Then
WScript.Arguments.ShowUsage
WScript.Quit
End If
Set Signer = CreateObject("Scripting.Signer")
File = WScript.Arguments.Named("file")
UI
= WScript.Arguments.Named.Exists("ui")
OK = Signer.VerifyFile(File, UI)
If OK Then
WScript.Echo File & " is trusted."
Else
WScript.Echo File & " is NOT trusted."
End If
</script>
</job>

See Also
Scripting.Signer Object | Verify Method | Sign Method | SignFile Method | Verifying a Script

2001 Microsoft Corporation. All rights reserved.


Build: Topic Version 5.6.9309.1546
Windows Script Host

Write Method
Sends a string to an output stream.
object.Write(strText)

Arguments
object
StdOut or StdErr text stream objects.
strText
String value indicating the text you want to write to the stream.
Remarks
The StdIn, StdOut, and StdErr properties and methods work when running the script with the CScript.exe host executable file only. An "Invalid Handle" error is returned when run with WScript.exe. The position pointer moves
to the point just beyond the last character in strText.
Example
The following code demonstrates the use of the Write method.
[VBScript]
Dim strInput
strInput = WScript.StdIn.ReadAll
WScript.StdOut.Write strInput

[JScript]
var strInput = WScript.StdIn.ReadAll();
WScript.StdOut.Write(strInput);

See Also
StdErr Property | StdOut Property

2001 Microsoft Corporation. All rights reserved.


Build: Topic Version 5.6.9309.1546
Windows Script Host

WriteBlankLines Method
Sends a specified number of blank lines (newline characters) to an output stream.
object.WriteBlankLines(intLines)

Arguments
object
StdOut or StdErr text stream objects.
intLines
Integer value indicating the number of blank lines you want to write to the stream.
Remarks
Calling the WriteLine method without supplying the strText argument is equivalent to calling WriteBlankLines(1). The StdIn, StdOut, and StdErr properties and methods work when running the script with the CScript.exe
host executable file only. An "Invalid Handle" error is returned when run with WScript.exe.

Example
The following code demonstrates the WriteBlankLines method.
[VBScript]
Dim StdIn, StdOut
Set StdIn = WScript.StdIn
Set StdOut = WScript.StdOut
Do While Not StdIn.AtEndOfStream
str = StdIn.ReadLine
StdOut.Write "Line " & (StdIn.Line - 1) & ": " & str
StdOut.WriteBlankLines 1
Loop

[JScript]
var stdin = WScript.StdIn;
var stdout = WScript.StdOut;
while (!stdin.AtEndOfStream)
{
var str = stdin.ReadLine();
stdout.Write("Line " + (stdin.Line - 1) + ": " + str);
stdout.WriteBlankLines(1);
}

See Also
StdErr Property | StdOut Property | WriteLine Method

2001 Microsoft Corporation. All rights reserved.


Build: Topic Version 5.6.9309.1546
Windows Script Host

WriteLine Method
Sends a string with a newline character to an output stream.
object.WriteLine([strText])

Arguments
object
StdOut or StdErr text stream objects.
strText
Optional. String value indicating the text you want to write to the stream. If omitted, a newline character is written to the output stream.
Remarks
The WriteLine method always appends a newline character to the string. Calling the WriteLine method without supplying the argument strText is equivalent to calling WriteBlankLines(1). The StdIn, StdOut, and StdErr
properties and methods work when running the script with the CScript.exe host executable file only. An "Invalid Handle" error is returned when run with WScript.exe. A line is a sequence of characters that ends with a newline
character.
Example
The following code demonstrates the WriteLine method.
[VBScript]
Dim StdIn, StdOut
Set StdIn = WScript.StdIn
Set StdOut = WScript.StdOut
Do While Not StdIn.AtEndOfStream
str = StdIn.ReadLine
StdOut.WriteLine "Line " & (StdIn.Line - 1) & ": " & str
Loop

[JScript]
var stdin = WScript.StdIn;
var stdout = WScript.StdOut;
while (!stdin.AtEndOfStream)
{
var str = stdin.ReadLine();
stdout.WriteLine("Line " + (stdin.Line - 1) + ": " + str);
}

See Also
StdErr Property | StdOut Property | WriteBlankLines Method

2001 Microsoft Corporation. All rights reserved.


Build: Topic Version 5.6.9309.1546
Windows Script Host

Events
In this Section
End Event
Signals the script engine to end execution of a remote script object.
Error Event
Signals the script engine to end execution of a remote script object when the remote script terminates prematurely due to an error.
Start Event
Signals the script engine to begin execution of a remote script object.
Related Sections

WSH Language
List of elements that make up WSH Reference.
WSH Basics
Learn the basics of WSH.

2001 Microsoft Corporation. All rights reserved.


Build: Topic Version 5.6.9309.1546
Windows Script Host

End Event
Event that is fired when the remote script completes.
Object_end

Parameters
object
WshRemote object.
Remarks
The End event is fired when the remote script object has finished executing. This can be when the remote script object has terminated normally, timed out, or terminated due to an error.
Example
var WshController = new ActiveXObject("WSHController");
var RemoteProc = WshController.CreateScript("foo.wsf", "remotemachine");
WScript.ConnectObject(RemoteProc, "RemoteProc_");
var Done = false;
RemoteProc.Execute();
while (!Done)
WScript.Sleep(100);
function RemoteProc_End()
{
WScript.Echo("The process has ended");
Done = true;
}
function RemoteProc_Error()
{
WScript.Echo("An error has occurred: " + RemoteProc.Error.Description);
Done = true;
}
function RemoteProc_Start()
{
WScript.Echo("The process has started");
}

See Also
WshController Object | WshRemote Object | Status Property | Error Property | Execute Method | Terminate Method | Start Event | Error Event

2001 Microsoft Corporation. All rights reserved.


Build: Topic Version 5.6.9309.1546
Windows Script Host

Error Event
Event that is fired when an error occurs in the remote script.
Object_Error

Parameters
object
WshRemote object.
Remarks
The remote script object fires the Error event when the remote script terminates prematurely. The Error property contains the WshRemoteError object (which holds information about the error that caused the remote script to
terminate prematurely).
Example
var WshController = new ActiveXObject("WSHController");
var RemoteProc = WshController.CreateScript("foo.wsf", "remotemachine");
WScript.ConnectObject(RemoteProc, "RemoteProc_");
var Done = false;
RemoteProc.Execute();
while (!Done)
WScript.Sleep(100);
function RemoteProc_End()
{
WScript.Echo("The process has ended");
Done = true;
}
function RemoteProc_Error()
{
WScript.Echo("An error has occurred: " + RemoteProc.Error.Description);
Done = true;
}
function RemoteProc_Start()
{
WScript.Echo("The process has started");
}

See Also
WshController Object | WshRemote Object | WshRemoteError Object | Status Property | Error Property | Execute Method | Terminate Method | Start Event | End Event

2001 Microsoft Corporation. All rights reserved.


Build: Topic Version 5.6.9309.1546
Windows Script Host

Start Event
Event that is fired when the remote script begins executing.
Object_Start

Parameters
object
WshRemote object.
Remarks
The Start event is fired when the Execute method is called.
Example
var WshController = new ActiveXObject("WSHController");
var RemoteProc = WshController.CreateScript("foo.wsf", "remotemachine");
WScript.ConnectObject(RemoteProc, "RemoteProc_");
var Done = false;
RemoteProc.Execute();
while (!Done)
WScript.Sleep(100);
function RemoteProc_End()
{
WScript.Echo("The process has ended");
Done = true;
}
function RemoteProc_Error()
{
WScript.Echo("An error has occurred: " + RemoteProc.Error.Description);
Done = true;
}
function RemoteProc_Start()
{
WScript.Echo("The process has started");
}

See Also
WshController Object | WshRemote Object | Status Property | Error Property | Execute Method | Terminate Method | End Event | Error Event

2001 Microsoft Corporation. All rights reserved.


Build: Topic Version 5.6.9309.1546
Windows Script Host

Error Messages
In this Section
Here is a list of the errors messages you may encounter when running scripts in the Windows Script Host 5.6 environment.
//E option requires name of script engine.
//H option requires host name.
//T option requires timeout value.
A duplicate name for a named or unnamed element was encountered.
An attempt at saving your settings via the //S option failed.
Can't change default script host <host name>.
Can't find script engine <engine name> for script.
Can't find script file <script file name>.
Can't read script from stdin.
Can't save settings.
Command line option mismatch.
Could not connect object <object name>.
Could not locate automation class name <automation class name>.
Execution of the Windows Script Host failed.
Host name for //H option must be "cscript" or "wscript".
Initialization of the Windows Script Host failed.
Invalid attempt to call Exec without a command.
Invalid pathname.
Invalid root in registry key <name> for reading.
Invalid syntax in URL<name>.

Invalid timeout value for //T option.


Loading script <script name> failed.
Loading your settings failed.
Missing job name.
Protocol handler for <name> not found.
Remote script object can only be executed once.
Script execution time was exceeded on script <script name>. <script name> execution was terminated.
Script setting file <settings filename>is invalid.
The shortcut pathname must end with .lnk or .url.
There is no file extension in <file name>.
There is no printer called <name>.
There is no script engine for file extension <file extension>.
There is no script file specified.
Unable to execute - arguments list too long.
Unable to open registry key <name> for reading.
Unable to remove environment variable <name>.
Unable to remove registry key <name>.
Unable to save shortcut <name>.
Unable to set shortcut target to <name>.
Unable to write to wsh.log. Please check with your administrator.
Unable to wait for process.
Unable to execute remote script.
Unable to find job <job identifier>.
Unicode is not supported on this platform.
Unknown option <option designation> specified.
Windows Script Host access is disabled on this machine. Contact your administrator for details.
Related Sections
WSH Reference
List of elements that make up WSH Reference.
WSH Basics
Learn the basics of WSH.

2001 Microsoft Corporation. All rights reserved.


Build: Topic Version 5.6.9309.1546
Windows Script Host

//H option requires host name.


You failed to specify the default host name.
To correct this error

Specify the default host name when using the //H option.

See Also
Host name for //H option must be "cscript" or "wscript".

2001 Microsoft Corporation. All rights reserved.


Build: Topic Version 5.6.9309.1546
Windows Script Host

//T option requires timeout value.


You failed to input a timeout value for the //T option.
To correct this error

Input a timeout value using the //T option.

See Also
Invalid timeout value for //T option | Script execution time was exceeded on script <script name>. <script name> execution was terminated.

2001 Microsoft Corporation. All rights reserved.

Build: Topic Version 5.6.9309.1546


Windows Script Host

A duplicate name for a named or unnamed element was encountered.


You are attempting to name a <named> or <unnamed> element with a name that is already in use by another <named> or <unnamed> element. The "name" attribute of the <named> and <unnamed> elements must be unique
throughout the <job>.
To correct this error

Choose a different name for the <named> or <unnamed> element.

See Also
WshArguments Object | WshNamed Object | WshUnnamed Object | <named> Element

2001 Microsoft Corporation. All rights reserved.


Build: Topic Version 5.6.9309.1546
Windows Script Host

An attempt at saving your settings via the //S option failed.


Again this is usually a systems permissions issue.
To correct this error

Consult your Administrator about potential network or security problems.

See Also
Can't change default script host <host name> | Setting Script Properties

2001 Microsoft Corporation. All rights reserved.


Build: Topic Version 5.6.9309.1546
Windows Script Host

Unable to execute - arguments list too long.


This error generally occurs when using the drag and drop feature of Windows Script Host. This happens when too many files are dropped on a Windows Script File.
To correct this error

Shorten the argument list by dragging and dropping fewer items.


Note

Themaximum command-line length that your system allows determines the number of files you can drag onto a script.

See Also

Drag and Drop Support | Command line option mismatch

2001 Microsoft Corporation. All rights reserved.


Build: Topic Version 5.6.9309.1546
Windows Script Host

Unable to write to wsh.log. Please check with your administrator.


On Windows 95/98 and Windows Millennium Editions, you are calling the method LogEvent(), but it fails because the wsh.log file is locked.
To correct this error

Unlock the wsh.log file if you the proper permissions or consult your system administrator.

See Also
LogEvent Method

2001 Microsoft Corporation. All rights reserved.


Build: Topic Version 5.6.9309.1546
Windows Script Host

Can't change default script host <host name>.


This is usually a systems permission issue and the likely cause is that the system registry has been locked by an Administrator.
To correct this error

Consult your Administrator about potential network or security problems.

See Also
An attempt at saving your settings via the //s option failed

2001 Microsoft Corporation. All rights reserved.


Build: Topic Version 5.6.9309.1546
Windows Script Host

Can't find script engine <engine name> for script.


Usually, this means that the script engine is not installed.
To correct this error

Consult your Administrator about potential network or security problems.


Make sure that the particular script engine is installed or that you are specifying the correct script engine.
Check your spelling.

2001 Microsoft Corporation. All rights reserved.


Build: Topic Version 5.6.9309.1546
Windows Script Host

Can't find script file <script file name>.


You have given an incorrect path or the script file is not there.
To correct this error

Check the path given and correct it.


Make sure that the file is actually there

See Also
Invalid pathname.

2001 Microsoft Corporation. All rights reserved.


Build: Topic Version 5.6.9309.1546
Windows Script Host

Can't read script from stdin.


This is often a permissions issue.
To correct this error

Consult your Administrator about potentially serious network or security problems.

2001 Microsoft Corporation. All rights reserved.


Build: Topic Version 5.6.9309.1546
Windows Script Host

Can't save settings.


Unable to save the control file (*.wsh) for this script.
To correct this error

Verify that you are not trying to save over a read-only file, a file that is open in another application, or a file locked by an administrator.
Consult your Administrator about potential network or security problems.

See Also
Setting Script Properties

2001 Microsoft Corporation. All rights reserved.


Build: Topic Version 5.6.9309.1546
Windows Script Host

Command line option mismatch.


Often this means you have specified conflicting arguments. For example, //B - batch mode is inconsistent with //I - interactive mode.
To correct this error

Check your arguments for conflicts.

2001 Microsoft Corporation. All rights reserved.


Build: Topic Version 5.6.9309.1546

Windows Script Host

Could not connect object <object name>.


It is likely that you are trying to sync events to an object or are sourcing events to an object that cannot accept those object events.
For example, IE can't be connected to events once it is created. You have to connect any object events to IE at the time it is created as the object as a part of the creation process.
To correct this error

Create the object and connect its object events to it during the creation process.

See Also
<object> Element | WScript Object

2001 Microsoft Corporation. All rights reserved.


Build: Topic Version 5.6.9309.1546
Windows Script Host

Could not locate automation class name <automation class name>.


Either you were unsuccessful in creating an automation class or the automation class was not properly installed.
To correct this error

Make sure the automation class that you created is installed.


Consult your Administrator about potential network or security problems.

2001 Microsoft Corporation. All rights reserved.


Build: Topic Version 5.6.9309.1546
Windows Script Host

//E option requires name of script engine.


You have not designated the script engine using the //E option.
To correct this error

Be sure to designate the script engine when using the //E option.

See Also
There is no script engine for file extension <file extension>.

2001 Microsoft Corporation. All rights reserved.


Build: Topic Version 5.6.9309.1546
Windows Script Host

Unable to remove environment variable <name>.


You are calling the method Environment.Remove() on an unrecognized environment variable.
This error generally occurs when using the Remove method. If the environment variable does not exist or is misspelled, the system is not able to remove it.
To correct this error

Check the names of the current environment variables and make sure they exist and are spelled correctly.

See Also
Remove Method | WshEnvironment Object

2001 Microsoft Corporation. All rights reserved.


Build: Topic Version 5.6.9309.1546
Windows Script Host

Execution of the Windows Script Host failed.


Usually, this is a systems permissions issue.
To correct this error

Consult your Administrator about potentially serious network or security problems.

See Also
Loading script <script name> failed

2001 Microsoft Corporation. All rights reserved.

Build: Topic Version 5.6.9309.1546


Windows Script Host

Host name for //H option must be "cscript" or "wscript".


You specified something other than "cscript" or "wscript" as your host name when you used the //H option.
To correct this error

Specify either "cscript" or "wscript" as the host name when using the //H option.

See Also
H option requires host name.

2001 Microsoft Corporation. All rights reserved.


Build: Topic Version 5.6.9309.1546
Windows Script Host

Initialization of the Windows Script Host failed.


Windows Script Host failed to initialize.
To correct this error

Consult your Administrator about potentially serious network or security problems.

2001 Microsoft Corporation. All rights reserved.


Build: Topic Version 5.6.9309.1546
Windows Script Host

Invalid attempt to call Exec without a command.


You called the WshShell.Exec() method but did not supply a command to execute.
To correct this error

strCommand is a required argument. It is a string that represents the command line used to run the script.

See Also
Exec Method

2001 Microsoft Corporation. All rights reserved.


Build: Topic Version 5.6.9309.1546
Windows Script Host

Invalid pathname.
You have given an incorrect path.
To correct this error

Check the path given and correct it.

See Also
Can't find script file <script file name>.

2001 Microsoft Corporation. All rights reserved.


Build: Topic Version 5.6.9309.1546
Windows Script Host

The shortcut pathname must end with .lnk or .url


When you named your shortcut, either you did not give it a file extension or you gave it an extension other than *.lnk, nor *.url.
When using the CreateShortcut method, the file extension is incorrect or missing.
To correct this error

Check that the file extension for the shortcut ends with .lnk for a Windows shortcut or with .url for an Internet shortcut.

See Also
WshShortcut Object | WshUrlShortcut Object

2001 Microsoft Corporation. All rights reserved.

Build: Topic Version 5.6.9309.1546


Windows Script Host

Invalid timeout value for //T option.


The timeout value that you entered using the //T option is invalid. You must designate a non-negative integer for //T option.
To correct this error

Input an appropriate timeout value using the //T option. Specify a non-negative integer for //T.

See Also
//T option requires timeout value | Script execution time was exceeded on script <script name>. <script name> execution was terminated.

2001 Microsoft Corporation. All rights reserved.


Build: Topic Version 5.6.9309.1546
Windows Script Host

Loading script <script name> failed.


Usually, this is a systems permissions issue and you have been denied read access to the file in question.
To correct this error

Consult your Administrator about potentially serious network or security problems.

See Also
Loading your settings failed

2001 Microsoft Corporation. All rights reserved.


Build: Topic Version 5.6.9309.1546
Windows Script Host

Loading your settings failed.


Usually, this is a systems permissions issue.
To correct this error

Consult your Administrator about potentially serious network or security problems.

See Also
Loading script <script name> failed

2001 Microsoft Corporation. All rights reserved.


Build: Topic Version 5.6.9309.1546
Windows Script Host

Missing job name.


You have failed to specify the job name.
To correct this error

Specify the job name.

See Also
Unable to find job <job identifier>

2001 Microsoft Corporation. All rights reserved.


Build: Topic Version 5.6.9309.1546
Windows Script Host

There is no printer called <name>.


The SetDefaultPrinter method accepts only the names of currently installed printers. This error generally occurs if you specify the printer port instead of the name of the printer, or if you use the name of a printer that is not
currently installed.
To correct this error

Check the names of the currently installed printers and make sure the specified printer is installed.
Check the spelling of the printer path for typing errors.
Make sure the networked printer is online.

See Also
SetDefaultPrinter Method | EnumPrinterConnections Method | AddWindowsPrinterConnection Method

2001 Microsoft Corporation. All rights reserved.


Build: Topic Version 5.6.9309.1546
Windows Script Host

Protocol handler for <name> not found.


This error generally occurs when the protocol handler for the URL shortcut target is misspelled. The two most common protocol handlers are HTTP and FTP.
To correct this error

Check the spelling of the protocol handler.

See Also
WshUrlShortcut Object

2001 Microsoft Corporation. All rights reserved.


Build: Topic Version 5.6.9309.1546
Windows Script Host

Invalid root in registry key <name> for reading.


You are calling the methods RegRead() or RegWrite() on an unrecognized root registry key.
This error generally occurs when using the RegRead or RegWrite methods with an invalid registry key.
To correct this error

Check the Windows registry and make sure the registry key exists and is spelled correctly.

See Also
RegRead Method | RegWrite Method | RegDelete Method

2001 Microsoft Corporation. All rights reserved.


Build: Topic Version 5.6.9309.1546
Windows Script Host

Unable to open registry key <name> for reading.


You are calling the method RegRead() on an unrecognized registry key.
This error generally occurs when using the RegRead method with an invalid registry key.
To correct this error

Check the Windows registry and make sure the registry key exists and is spelled correctly.

See Also
RegRead Method

2001 Microsoft Corporation. All rights reserved.


Build: Topic Version 5.6.9309.1546
Windows Script Host

Unable to remove registry key <name>.


You are calling the method RegDelete() on an unrecognized registry key.
This error generally occurs when using the RegDelete method on an invalid registry key.
To correct this error

Check the Windows registry and make sure the registry key exists and is spelled correctly.

See Also
RegDelete Method | RegRead Method | RegWrite Method

2001 Microsoft Corporation. All rights reserved.


Build: Topic Version 5.6.9309.1546
Windows Script Host

Remote script object can only be executed once.


You are attempting to rerun a remote script object.

To correct this error

Create another remote script object and run it instead.

See Also
WshRemote Object

2001 Microsoft Corporation. All rights reserved.


Build: Topic Version 5.6.9309.1546
Windows Script Host

Script execution time was exceeded on script <script name>. <script name> execution was terminated.
The script in question could not be executed within the user-defined execution time (//T).
To correct this error

Troubleshoot your script to determine why it is not executing within the time parameter (//T) that you set. Redesign your script so that it executes faster and/or change the time parameter (//T).

See Also
T option requires timeout value | Invalid timeout value for T option

2001 Microsoft Corporation. All rights reserved.


Build: Topic Version 5.6.9309.1546
Windows Script Host

Script setting file <settings filename>is invalid.


You used an invalid script setting file.
To correct this error

Recreate your script setting file or consult your systems administrator.

2001 Microsoft Corporation. All rights reserved.


Build: Topic Version 5.6.9309.1546
Windows Script Host

Invalid syntax in URL<name>.


This error generally occurs when the text that makes up the URL target contains incorrect syntax.
To correct this error

Check the spelling of the URL target for typing errors.

See Also
WshUrlShortcut Object

2001 Microsoft Corporation. All rights reserved.


Build: Topic Version 5.6.9309.1546
Windows Script Host

Unable to save shortcut <name>.


This error generally occurs when the name of the shortcut already exists or is a read-only file.
To correct this error

Change the read-only attribute to read/write.


Rename your shortcut to something unique.
Change the name of the existing shortcut.

See Also
WshShortcut Object | WshUrlShortcut Object

2001 Microsoft Corporation. All rights reserved.


Build: Topic Version 5.6.9309.1546
Windows Script Host

Unable to set shortcut target to <name>.


This error generally occurs when the protocol handler for the URL shortcut target is invalid or improperly registered. The two most common protocol handlers are HTTP and FTP.

To correct this error

Use a valid protocol handler.


Check the spelling of the protocol handler being used.
Contact your system administrator to make sure the protocol handler is properly installed.
Consult your Administrator about potential network or security problems.

See Also
WshUrlShortcut Object

2001 Microsoft Corporation. All rights reserved.


Build: Topic Version 5.6.9309.1546
Windows Script Host

There is no file extension in <file name>.


In order to determine what script engine is apt, the program usually needs the appropriate file extension.
To correct this error

Be sure include a correct file extension that is appropriate to the scripting language you wish to use, along with the file name.

2001 Microsoft Corporation. All rights reserved.


Build: Topic Version 5.6.9309.1546
Windows Script Host

There is no script engine for file extension <file extension>.


This file extension is not mapped to a script engine.
To correct this error

Check your file extension and also the spelling of your scripting language designation.
Use //E to designate a script engine.

See Also
E option requires name of script engine.

2001 Microsoft Corporation. All rights reserved.


Build: Topic Version 5.6.9309.1546
Windows Script Host

There is no script file specified.


You have failed to specify a script file.
To correct this error

Specify the appropriate script file.

See Also
Unknown option <option designation> specified

2001 Microsoft Corporation. All rights reserved.


Build: Topic Version 5.6.9309.1546
Windows Script Host

Unable to execute remote script.


The script failed to initialize.
To correct this error

Consult your Administrator about potential network or security problems.

See Also
WshRemote Object

2001 Microsoft Corporation. All rights reserved.


Build: Topic Version 5.6.9309.1546
Windows Script Host

Unable to find job <job identifier>.

You made a reference to an unrecognized job ID in your Windows Script file (*.wsf file).
To correct this error

Check the spelling of the job ID for typing errors.

See Also
Using Windows Script Files | <job> Element

2001 Microsoft Corporation. All rights reserved.


Build: Topic Version 5.6.9309.1546
Windows Script Host

Unable to wait for process.


This error generally occurs when the script is hung up waiting for a process that does not return a value, for example, waiting for the result from running a shortcut link.
To correct this error

Execute the program directly instead of using a shortcut.


Check the shortcut link to be sure it is still current.

See Also
Run Method

2001 Microsoft Corporation. All rights reserved.


Build: Topic Version 5.6.9309.1546
Windows Script Host

Unicode is not supported on this platform.


The WIN 95/98 and Windows Millennium Edition platforms do not support the use of Unicode.
To correct this error

Don't attempt to use Unicode on WIN95/98 or Windows Millennium Edition platforms.

2001 Microsoft Corporation. All rights reserved.


Build: Topic Version 5.6.9309.1546
Windows Script Host

Unknown option <option designation> specified.


You have specified an option that is invalid for Windows script host.
To correct this error

Use the Windows script host option appropriate to the script language you are using or specify another supported script language.
Also check your spelling.

See Also
There is no script file specified

2001 Microsoft Corporation. All rights reserved.


Build: Topic Version 5.6.9309.1546
Windows Script Host

Windows Script Host access is disabled on this machine. Contact your administrator for details.
Usually, this is a systems permissions issue.
To correct this error

Consult your Administrator about potential network or security problems.

See Also
Execution of the Windows Script Host failed

2001 Microsoft Corporation. All rights reserved.


Build: Topic Version 5.6.9309.1546

Das könnte Ihnen auch gefallen