Microsoft Windows Script Technologies
Microsoft Windows Script Technologies
DropDown image

The following table lists the Windows script technologies and describes the functionality included in each technology.

In This Section

JScript

Microsoft's powerful scripting language targeted specifically at the Internet. JScript version 5.6 is the next generation of Microsoft's implementation of the ECMA 262 language.

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 Services.

Script Runtime

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 an integer or a string, but can be anything except an array.

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.

Script Encoder is a simple command-line tool that enables script designers to encode their final script so that Web hosts and Web clients cannot view or modify their source.

Windows Script Components

Microsoft® Windows® Script Components provide you with an easy way to create COM components using scripting languages such as Microsoft® Visual Basic® Scripting Edition (VBScript) and Microsoft® JScript®.

Windows Script Host

The Microsoft Windows Script Host (WSH) is a tool that will allow you to run Visual Basic Scripting Edition and JScript natively within the base Operating System, either on Windows 95 or Windows NT 4.0.

Windows Script Interfaces

Microsoft Windows Script Interfaces introduce a new way for an application to add scripting and OLE Automation capabilities.

Related Sections

Microsoft Windows Script Technologies Home Page

A comprehensive site dedicated to Microsoft's scripting technologies. Contains complete documentation for JScript, VBScript, Windows Script Host, Windows Script Components, Remote Scripting, Script Control, and Script Debugger. You can download the latest versions of JScript and VBScript, as well as updates and enhancements to other Microsoft scripting technologies.
To make a suggestion or report a bug about Help or another feature of this product, go to the feedback site.


JScript (Windows Script Technologies)

JScript
JScript (Windows Script Technologies)
DropDown image

The following sections explain how to use JScript and provide details about its language elements.

In This Section

JScript User's Guide

Provides information about how to use JScript and includes a guide to regular expressions.

JScript Language Reference

Explains the elements that comprise the JScript language.

Related Sections

VBScript

Includes information about how to use VBScript and reference information about the language.


JScript User's Guide

JScript
JScript User's Guide
DropDown image

These sections provide information about how to use VBScript and how to construct and use regular expressions.

In This Section

JScript Fundamentals

Provides an introduction to the basic structures in JScript.

Advanced JScript

Explains advanced JScript functionality, such as recursion, arrays, troubleshooting, and so on.

Introduction to Regular Expressions (Scripting)

Introduces the concept of regular expressions and explains how to create and use them.

Related Sections

VBScript User's Guide

Provides information about how to use VBScript and includes a guide to regular expressions.

VBScript Language Reference

Explains the elements that comprise the VBScript language.


JScript Fundamentals

JScript
JScript Fundamentals
DropDown image

These sections provide information about the basic elements that comprise JScript.

In This Section

What Is JScript?

Defines JScript and explains its relationship to other languages.

Writing JScript Code

Explains the organization of elements within JScript code.

JScript Variables

Explains the concept of variables in JScript.

JScript Data Types

Enumerates data types in JScript and explains the purpose of each type.

JScript Operators

Provides a list of operators with links to information about each operator.

Operator Precedence

Explains the rules that control the order in which operations are performed when an expression is evaluated.

Controlling Program Flow

Explains conditional statements and loops in JScript.

JScript Functions

Describes the built-in functions and explains how to create new functions.

JScript Objects

Explains the concept of objects in JScript.

Intrinsic Objects

Lists the objects that are part of JScript by default and explains the purpose of each object.

Creating Your Own Objects

Explains how to extend JScript functionality by creating your own functions.

JScript Reserved Words

Lists the reserved words in JScript.

Related Sections

Advanced JScript

Explains advanced JScript functionality, such as recursion, arrays, troubleshooting, and so on.

Introduction to Regular Expressions (Scripting)

Introduces the concept of regular expressions and explains how to create and use them.


What Is JScript?

JScript
What Is JScript?
DropDown image

JScript is the Microsoft implementation of the ECMA 262 language specification (ECMAScript Edition 3). With only a few minor exceptions (to maintain backwards compatibility), JScript is a full implementation of the ECMA standard. This overview is intended to help you get started with JScript.

Using JScript

JScript is an interpreted, object-based scripting language. Although it has fewer capabilities than full-fledged object-oriented languages like C++, JScript is more than sufficiently powerful for its intended purposes.

JScript is not a cut-down version of another language (it is only distantly and indirectly related to Java, for example), nor is it a simplification of anything. It is, however, limited. You cannot write stand-alone applications in it, for example, and it has no built-in support for reading or writing files. Moreover, JScript scripts can run only in the presence of an interpreter or "host", such as Active Server Pages (ASP), Internet Explorer, or Windows Script Host.

JScript is a loosely typed language. Loosely typed means you do not have to declare the data types of variables explicitly. In fact, JScript takes it one step further. You cannot explicitly declare data types in JScript. Moreover, in many cases JScript performs conversions automatically when needed. For instance, if you add a number to an item consisting of text (a string), the number is converted to text.

The rest of this user's guide is an overview of JScript features. For full details of the language implementation, consult the language reference.

Note Note

The code in many of the following examples is somewhat more explicit and less dense than code you are likely to find in actual Web pages. The intent here is to clarify the concepts, not to express optimal coding conciseness and style. In any case, there is no shame in writing code that you can read and easily understand six months after you write it.


Writing JScript Code

JScript
Writing JScript Code
DropDown image

Like many other programming languages, Microsoft JScript is written in text format, and organized into statements, blocks consisting of related sets of statements, and comments. Within a statement you can use variables, immediate data such as strings and numbers (called "literals"), and expressions.

Statements

A JScript program is a collection of statements. A JScript statement is equivalent to a complete sentence in English. JScript statements combine expressions in such a way that they carry out one complete task.

A statement consists of one or more expressions, keywords, or operators (symbols). Typically, a statement is written on a single line, although a statement can be written over two or more lines. Also, two or more statements can be written on the same line by separating them with semicolons. In general, each new line begins a new statement. It is a good idea to terminate your statements explicitly. You do this with the semicolon (;), which is the JScript statement termination character. Here are two examples of JScript statements.

CopyCode image Copy Code
aBird = "Robin"; // Assign the text "Robin" to the variable aBird
var today = new Date(); // Assign today's date to the variable today

A group of JScript statements surrounded by braces ({}) is called a block. Statements grouped into a block can generally be treated as a single statement. This means you can use blocks in most places that JScript expects a lone statement. Notable exceptions include the headers of for and while loops. Notice that the primitive statements within a block end in semicolons, but the block itself does not.

Generally, blocks are used in functions and conditionals. Notice that unlike C++ and some other languages, JScript does not consider a block to be a new scope; only functions create a new scope. In the following example, the first statement begins the definition of a function that consists of a block of five statements. Following the block are three statements that are not surrounded by braces; these statements are not a block, and are therefore not part of the function definition.

CopyCode image Copy Code
function convert(inches) {
   feet = inches / 12; // These five statements are in a block.
   miles = feet / 5280;
   nauticalMiles = feet / 6080;
   cm = inches * 2.54;
   meters = inches / 39.37;
}
km = meters / 1000; // These three statements are not in a block.
kradius = km;
mradius = miles;

Comments

A single-line JScript comment begins with a pair of forward slashes (//). Here is an example of a single line comment.

CopyCode image Copy Code
aGoodIdea = "Comment your code thoroughly."; // This is a single-line comment.

A multiline JScript comment begins with a forward slash and asterisk (/*), and ends with the reverse (*/).

CopyCode image Copy Code
/*
This is a multiline comment that explains the preceding code statement.

The statement assigns a value to the aGoodIdea variable. The value,
which is contained between the quote marks, is called a literal. A
literal explicitly and directly contains information; it does not
refer to the information indirectly. The quote marks are not part
of the literal.
*/
Note Note

If you attempt to embed one multiline comment within another, JScript interprets the resulting multiline comment in an unexpected way. The */ that marks the end of the embedded multiline comment is interpreted as the end of the whole multiline comment. This means that the text that follows the embedded multiline comment will not be commented out; instead, it will be interpreted as JScript code, and will generate syntax errors.

It is recommended that you write all your comments as blocks of single-line comments. This allows you to comment out large segments of code with a multiline comment later.

CopyCode image Copy Code
// This is another multiline comment, written as a series of single-line comments.
// After the statement is executed, you can refer to the content of the aGoodIdea
// variable by using its name, as in the next statement, in which a string literal is
// appended to the aGoodIdea variable by concatenation to create a new variable.

var extendedIdea = aGoodIdea + " You never know when you'll have to figure out what it does.";

Assignments and Equality

The equal sign (=) is used in JScript statements to assign values to variables: it is the assignment operator. The left hand operand of the = operator is always an Lvalue. Examples of Lvalues are:

  • variables,

  • array elements,

  • object properties.

The right operand of the = operator is always an Rvalue. Rvalues can be an arbitrary value of any type, including the value of an expression. Here is an example of a JScript assignment statement.

CopyCode image Copy Code
anInteger = 3;

The JScript compiler interprets this statement as meaning: "Assign the value 3 to the variable anInteger," or "anInteger takes the value 3."

Be certain you understand the difference between the = operator (assignment) and the == operator (equality). When you want to compare two values to find out if they are equal, use two equals signs (==). This is discussed in detail in Controlling Program Flow.

Expressions

A JScript expression is a 'phrase' of JScript that a JScript interpreter can evaluate to generate a value. The value can be of any valid JScript type - a number, a string, an object, and so on. The simplest expressions are literals. Here are some examples of JScript literal expressions.

CopyCode image Copy Code
3.9                       // numeric literal
"Hello!"                  // string literal
false                     // boolean literal
null                      // literal null value
{x:1, y:2}                // Object literal
[1,2,3]                   // Array literal
function(x){return x*x;}  // function literal

More complicated expressions can contain variables, function calls, and other expressions. You can combine expressions to create complex expressions using operators. Examples of operators are:

CopyCode image Copy Code
+  // additon
-  // subtraction
*  // multiplication
/  // division

Here are some examples of JScript complex expressions.

CopyCode image Copy Code
var anExpression = 3 * (4 / 5) + 6;
var aSecondExpression = Math.PI * radius * radius;
var aThirdExpression = aSecondExpression + "%" + anExpression;
var aFourthExpression = "(" + aSecondExpression + ") % (" + anExpression + ")";


JScript Variables

JScript
JScript Variables
DropDown image

In any programming language, a piece of data is used to quantify a concept.

Variables in JScript

CopyCode image Copy Code
How old am I?

In JScript, a variable is the name you give that concept; it represents the value at a given instant. When you use the variable, you really mean the data it represents. Here is an example:

CopyCode image Copy Code
NumberOfDaysLeft = EndDate – TodaysDate;

In a mechanical sense, you use variables to store, retrieve, and manipulate all the different values that appear in your scripts. Always create a meaningful variable name; that makes it easy for humans to understand what your scripts do.

Declaring Variables

The first time a variable appears in your script is its declaration. This first mention of the variable sets it up in memory so you can refer to it later on in your script. Always declare variables before using them. You do this using the var keyword.

CopyCode image Copy Code
var count;  // a single declaration.
var count, amount, level;  // multiple declarations with a single var keyword.
var count = 0, amount = 100;  // variable declaration and initialization in one statement.

If you do not initialize your variable in the var statement, it automatically takes on the JScript value undefined. Although it is unsafe to do so, it is legal JScript syntax to omit the var keyword from your declaration statement. When you do, the JScript interpreter gives the variable global scope visibility. When you declare a variable at the procedure level though, you do not want it to be visible at the global scope; in this case, you must use the var keyword in your variable declaration.

Naming Variables

A variable name is an identifier. In JScript, identifiers are used to:

  • name variables,

  • name functions,

  • provide labels for loops.

JScript is a case-sensitive language. This means a variable name such as myCounter is different than the variable name MYCounter. Variable names can be of any length. The rules for creating legal variable names are as follows:

  • The first character must be an ASCII letter (either uppercase or lowercase), or an underscore (_) character. Note that a number cannot be used as the first character.

  • Subsequent characters must be letters, numbers, or underscores.

  • The variable name must not be a reserved word.

Here are some examples of valid variable names:

CopyCode image Copy Code
_pagecount
Part9
Number_Items

Here are some examples of invalid variable names:

CopyCode image Copy Code
99Balloons // Cannot begin with a number.
Smith&Wesson // The ampersand (&) character is not a valid character for variable names.

When you want to declare a variable and initialize it, but do not want to give it any particular value, assign it the JScript value null. Here is an example.

CopyCode image Copy Code
var bestAge = null;
var muchTooOld = 3 * bestAge; // muchTooOld has the value 0.

If you declare a variable without assigning a value to it, it exists, but has the JScript value undefined. Here is an example.

CopyCode image Copy Code
var currentCount;
var finalCount = 1 * currentCount; // finalCount has the value NaN since currentCount is undefined.

Note that the main difference between null and undefined in JScript is that null behaves like the number 0, while undefined behaves like the special value NaN (Not a Number). A null value and an undefined value will always compare to be equal.

You can declare a variable without using the var keyword in the declaration, and assign a value to it. This is an implicit declaration.

CopyCode image Copy Code
noStringAtAll = ""; // The variable noStringAtAll is declared implicitly.

You cannot use a variable that has never been declared.

CopyCode image Copy Code
var volume = length * width; // Error - length and width do not yet exist.

Coercion

The JScript interpreter can only evaluate expressions in which the data types of the operands are the same. Without coercion, an expression that attempts to perform an operation on two different data types (a number and a string for example) would produce an erroneous result. But that is not the case with JScript.

JScript is a loosely typed language. This means its variables have no predetermined type (as opposed to strongly typed languages like C++). Instead, JScript variables have a type that corresponds to the type of value they contain. A benefit of this behavior is that it provides you with the flexibility to treat a value as if it were of another type.

In JScript, you can perform operations on values of differing types without fear that the JScript interpreter will raise an exception. Instead, the JScript interpreter automatically changes (coerces) one of the data types to that of the other, then performs the operation. For example:

Operation | Result
Add a number and a string | The number is coerced into a string.
Add a Boolean and a string | The Boolean is coerced into a string.
Add a number and a Boolean | The Boolean is coerced into a number.

Consider the following example.

CopyCode image Copy Code
var x = 2000;      // A number.
var y = "Hello";   // A string.
x = x + y;         // the number is coerced into a string.
document.write(x); // Outputs 2000Hello.

To explicitly convert a string to an integer, use the parseInt Method. To explicitly convert a string to a number, use the parseFloat Method. Notice that strings are automatically converted to equivalent numbers for comparison purposes, but are left as strings for addition (concatenation).


Data Types (JScript 5.6)

JScript
Data Types (JScript 5.6)
DropDown image

In JScript, there are three primary data types, two composite data types, and two special data types.

Primary Data Types

The primary (primitive) data types are:

  • String

  • Number

  • Boolean

Composite Data Types

The composite (reference) data types are:

  • Object

  • Array

Special Data Types

The special data types are:

  • Null

  • Undefined

String Data Type

A string value is a chain of zero or more Unicode characters (letters, digits, and punctuation marks) strung together. You use the string data type to represent text in JScript. String literals can be included in your scripts by enclosing them in matching pairs of single or double quotation marks. Double quotation marks can be contained within strings surrounded by single quotation marks, and single quotation marks can be contained within strings surrounded by double quotation marks. The following are examples of strings:

CopyCode image Copy Code
"Happy am I; from care I'm free!"
'"Avast, ye lubbers!" roared the technician.'
"42"
'c'

Notice that JScript does not have a type to represent a single character. To represent a single character in JScript, you create a string that consists of only one character. A string that contains zero characters ("") is an empty (zero-length) string.

Number Data Type

In JScript, there is no distinction between integer and floating-point values; a JScript number can be either (internally, JScript represent all numbers as floating-point values).

Integer Values

Integer values can be positive whole numbers, negative whole numbers, and 0. They can be represented in base 10 (decimal), base 8 (octal), and base 16 (hexadecimal). Most numbers in JScript are written in decimal. You denote octal integers by prefixing them with a leading "0" (zero). They can contain digits 0 through 7 only. A number with a leading "0", containing the digits "8" and/or "9" is interpreted as a decimal number.

You denote hexadecimal ("hex") integers by prefixing them with a leading "0x" (zero and x|X). They can contain digits 0 through 9, and letters A through F (either uppercase or lowercase) only. The letters A through F are used to represent, as single digits, 10 through 15 in base 10. That is, 0xF is equivalent to 15, and 0x10 is equivalent to 16.

Both octal and hexadecimal numbers can be negative, but cannot have a decimal portion, and cannot be written in scientific (exponential) notation.

Floating-point Values

Floating-point values can be whole numbers with a decimal portion. Additionally, they can be expressed in scientific notation. That is, an uppercase or lowercase "e" is used to represent "ten to the power of". JScript represents numbers using the eight byte IEEE 754 floating-point standard for numerical representation. This means you can write numbers as large as 1.7976931348623157x10308, and as small as 5x10-324. A number that begins with a single "0" and contains a decimal point is interpreted as a decimal floating-point number.

Notice that a number that begins with "0x" or "00" and contains a decimal point will generate an error. Here are some examples of JScript numbers.

Number | Description | Decimal Equivalent
.0001, 0.0001, 1e-4, 1.0e-4 | Four equivalent floating-point numbers. | 0.0001
3.45e2 | A floating-point number. | 345
42 | An integer. | 42
0378 | An integer. Although this looks like an octal number (it begins with a zero), 8 is not a valid octal digit, so the number is treated as a decimal. | 378
0377 | An octal integer. Notice that although it only appears to be one less than the number above, its actual value is quite different. | 255
0.0001 | A floating point number. Even though this begins with a zero, it is not an octal number because it has a decimal point. | 0.0001
00.0001 | This is an error. The two leading zeros mark the number as an octal, but octals are not allowed a decimal component. | N/A (compiler error)
0Xff | A hexadecimal integer. | 255
0x37CF | A hexadecimal integer. | 14287
0x3e7 | A hexadecimal integer. Notice that the 'e' is not treated as exponentiation. | 999
0x3.45e2 | This is an error. Hexadecimal numbers cannot have decimal parts. | N/A (compiler error)

Additionally, JScript contains numbers with special values. These are:

  • NaN (not a number). This is used when a mathematical operation is performed on inappropriate data, such as strings or the undefined value

  • Positive Infinity. This is used when a positive number is too large to represent in JScript

  • Negative Infinity. This is used when a negative number is too large to represent in JScript

  • Positive and Negative 0. JScript differentiates between positive and negative zero.

Boolean Data Type

Whereas the string and number data types can have a virtually unlimited number of different values, the Boolean data type can only have two. They are the literals true and false. A Boolean value is a truth-value — it expresses the validity of a condition (tells whether the condition is true or not).

Comparisons you make in your scripts always have a Boolean outcome. Consider the following line of JScript code.

CopyCode image Copy Code
y = (x == 2000);

Here, the value of the variable x is tested to see if it is equal to the number 2000. If it is, the result of the comparison is the Boolean value true, which is assigned to the variable y. If x is not equal to 2000, then the result of the comparison is the Boolean value false.

Boolean values are especially useful in control structures. Here, you combine a comparison that creates a Boolean value directly with a statement that uses it. Consider the following JScript code sample.

CopyCode image Copy Code
if (x == 2000)
    z = z + 1;
else
    x = x + 1;

The if/else statement in JScript performs one action if a Boolean value is true (in this case, z = z + 1), and an alternate action if the Boolean value is false (x = x + 1).

You can use any expression as a comparative expression. Any expression that evaluates to 0, null, undefined, or an empty string is interpreted as false. An expression that evaluates to any other value is interpreted as true. For example, you could use an expression such as:

CopyCode image Copy Code
if (x = y + z) // This may not do what you expect — see below!

Note that the above line does not check if x is equal to y + z, since only a single equal sign (assignment) is used. Instead, the code above assigns the value of y + z to the variable x, and then checks if the result of the entire expression (the value of x) is zero. To check if x is equal to y + z, use the following code.

CopyCode image Copy Code
if (x == y + z) // This is different to the code above!

For more information on comparisons, see Controlling Program Flow.

Null Data Type

The null data type has only one value in JScript: null. The null keyword cannot be used as the name of a function or variable.

A variable that contains null contains "no value" or "no object." In other words, it holds no valid number, string, Boolean, array, or object. You can erase the contents of a variable (without deleting the variable) by assigning it the null value.

Notice that in JScript, null is not the same as 0 (as it is in C and C++). Also note that the typeof operator in JScript will report null values as being of type Object, not of type null. This potentially confusing behavior is for backwards compatibility.

Undefined Data Type

The undefined value is returned when you use:

  • an object property that does not exist,

  • a variable that has been declared, but has never had a value assigned to it.

Notice that you cannot test to see if a variable exists by comparing it to undefined, although you can check if its type is "undefined". In the following code example, assume that the programmer is trying to test if the variable x has been declared:

CopyCode image Copy Code
// This method will not work
if (x == undefined)
    // do something

// This method also won't work - you must check for
// the string "undefined"
if (typeof(x) == undefined)
    // do something

// This method will work
if (typeof(x) == "undefined")
    // do something

Consider comparing the undefined value to null.

CopyCode image Copy Code
someObject.prop == null;

This comparison is true,

  • if the property someObject.prop contains the value null,

  • if the property someObject.prop does not exist.

To check if an object property exists, you can use the new in operator:

CopyCode image Copy Code
if ("prop" in someObject)
    // someObject has the property 'prop'


Operators (JScript 5.6)

JScript
Operators (JScript 5.6)
DropDown image

JScript has a full range of operators, including arithmetic, logical, bitwise, assignment, as well as some miscellaneous operators.

Computational Operators

Description | Symbol
Unary negation | -
Increment | ++
Decrement | --
Multiplication | *
Division | /
Modulus arithmetic | %
Addition | +
Subtraction | -

Logical Operators

Description | Symbol
Logical NOT | !
Less than | <
Greater than | >
Less than or equal to | <=
Greater than or equal to | >=
Equality | ==
Inequality | !=
Logical AND | &&
Logical OR | ||
Conditional (ternary) | ?:
Comma | ,
Strict Equality | ===
Strict Inequality | !==

Bitwise Operators

Description | Symbol
Bitwise NOT | ~
Bitwise Left Shift | <<
Bitwise Right Shift | >>
Unsigned Right Shift | >>>
Bitwise AND | &
Bitwise XOR | ^
Bitwise OR | |

Assignment Operators

Description | Symbol
Assignment | =
Compound Assignment | OP=

Miscellaneous Operators

Description | Symbol
delete | delete
typeof | typeof
void | void
instanceof | instanceof
new | new
in | in

The difference between == (equality) and === (strict equality) is that the equality operator will coerce values of different types before checking for equality. For example, comparing the string "1" with the number 1 will compare as true. The strict equality operator, on the other hand, will not coerce values to different types, and so the string "1" will not compare as equal to the number 1.

Primitive strings, numbers, and Booleans are compared by value. If they have the same value, they will compare as equal. Objects (including Array, Function, String, Number, Boolean, Error, Date and RegExp objects) compare by reference. Even if two variables of these types have the same value, they will only compare as true if they refer to exactly the same object.

For example:

CopyCode image Copy Code
// Two primitive strings with the same value.
var string1 = "Hello";
var string2 = "Hello";

// Two String objects, with the same value.
var StringObject1 = new String(string1);
var StringObject2 = new String(string2);

// This will be true.
if (string1 == string2)
     // do something (this will be executed)

// This will be false.
if (StringObject1 == StringObject2)
    // do something (this will not be executed)

// To compare the value of String objects,
// use the toString() or valueOf() methods.
if (StringObject1.valueOf() == StringObject2)
     // do something (this will be executed)


Operator Precedence (JScript 5.6)

JScript
Operator Precedence (JScript 5.6)
DropDown image

Operator precedence is a set of rules in JScript. It controls the order in which operations are performed when an expression is evaluated. Operations with a higher precedence are performed before those with a lower one. For example, multiplication is performed before addition.

JScript Operators

The following table lists the JScript operators, ordered from highest to lowest precedence. Operators with the same precedence are evaluated left to right.

Operator | Description
. [] () | Field access, array indexing, function calls, and expression grouping
++ -- - ~ ! delete new typeof void | Unary operators, return data type, object creation, undefined values
* / % | Multiplication, division, modulo division
+ - + | Addition, subtraction, string concatenation
<< >> >>> | Bit shifting
< <= > >= instanceof | Less than, less than or equal, greater than, greater than or equal, instanceof
== != === !== | Equality, inequality, strict equality, and strict inequality
& | Bitwise AND
^ | Bitwise XOR
| | Bitwise OR
&& | Logical AND
|| | Logical OR
?: | Conditional
= OP= | Assignment, assignment with operation
, | Multiple evaluation

Parentheses are used to alter the order of evaluation determined by operator precedence. This means an expression within parentheses is fully evaluated before its value is used in the remainder of the expression.

For example:

CopyCode image Copy Code
z = 78 * (96 + 3 + 45)

There are five operators in this expression: =, *, (), +, and another +. According to the rules of operator precedence, they are evaluated in the following order: (), +, +, *, =.

  1. Evaluation of the expression within the parentheses occurs first. Within the parentheses, there are two addition operators. Since the addition operators both have the same precedence, they are evaluated from left to right. 96 and 3 are added together first, then 45 is added to this total, resulting in a value of 144.

  2. Multiplication occurs next. 78 is multiplied by 144, resulting in a value of 11232.

  3. Assignment occurs last. 11232 is assigned to z.


Controlling Program Flow

JScript
Controlling Program Flow
DropDown image

Normally, statements in a JScript script are executed one after the other, in the order in which they are written. This is called sequential execution, and is the default direction of program flow.

An alternative to sequential execution transfers the program flow to another part of your script. That is, instead of executing the next statement in the sequence, another statement is executed instead.

To make a script useful, this transfer of control must be done in a logical manner. Transfer of program control is based upon a decision, the result of which is a truth statement (returning a Boolean true or false). You create an expression, then test whether its result is true. There are two main kinds of program structures that accomplish this.

The first is the selection structure. You use it to specify alternate courses of program flow, creating a junction in your program (like a fork in a road). There are four selection structures available in JScript.

  • the single-selection structure (if),

  • the double-selection structure (if/else),

  • the inline ternary operator ?:

  • the multiple-selection structure (switch).

The second type of program control structure is the repetition structure. You use it to specify that an action is to be repeated while some condition remains true. When the conditions of the control statement have been met (usually after some specific number of iterations), control passes to the next statement beyond the repetition structure. There are four repetition structures available in JScript.

  • the expression is tested at the top of the loop (while),

  • the expression is tested at the bottom of the loop (do/while),

  • operate on each of an object's properties (for/in).

  • counter controlled repetition (for).

You can create quite complex scripts by nesting and stacking selection and repetition control structures.

A third form of structured program flow is provided by exception handling, which is not covered in this document.

Using Conditional Statements

JScript supports if and if...else conditional statements. In if statements a condition is tested, and if the condition meets the test, the relevant JScript code is executed. In the if...else statement, different code is executed if the condition fails the test. The simplest form of an if statement can be written on one line, but multiline if and if...else statements are much more common.

The following examples demonstrate syntaxes you can use with if and if...else statements. The first example shows the simplest kind of Boolean test. If (and only if) the item between the parentheses evaluates to (or can be coerced to) true, the statement or block of statements after the if is executed.

CopyCode image Copy Code
// The smash() function is defined elsewhere in the code.
// Boolean test of whether newShip is true.
if (newShip)
   smash(champagneBottle,bow);

// In this example, the test fails unless both conditions are true.
if (rind.color == "deep yellow " && rind.texture == "large and small wrinkles")
{
   theResponse = ("Is it a Crenshaw melon?");
}

// In this example, the test succeeds if either condition is true.
var theReaction = "";
if ((dayOfWeek == "Saturday") || (dayOfWeek == "Sunday"))
{
   theReaction = ("I'm off to the beach!");
}
else
{
   theReaction = ("Hi ho, hi ho, it's off to work I go!");
}

Conditional Operator

JScript also supports an implicit conditional form. It uses a question mark after the condition to be tested (rather than the word if before the condition). It also specifies two alternatives, one to be used if the condition is met and one if it is not. A colon must separate these alternatives.

CopyCode image Copy Code
var hours = "";

// Code specifying that hours contains either the contents of
// theHour, or theHour - 12.

hours += (theHour >= 12) ? " PM" : " AM";

If you have several conditions to be tested together, and you know that one is more likely to pass or fail than the others, you can use a feature called 'short circuit evaluation' to speed the execution of your script. When JScript evaluates a logical expression, it only evaluates as many sub-expressions as required to get a result.

For example, if you have an AND expression such as ((x == 123) && (y == 42)), JScript first checks if x is 123. If it is not, the entire expression cannot be true, even if y is equal to 42. Hence, the test for y is never made, and JScript returns the value false.

Similarly, if only one of several conditions must be true (using the || operator), testing stops as soon as any one condition passes the test. This is effective if the conditions to be tested involve the execution of function calls or other complex expressions. With this in mind, when you write Or expressions, place the conditions most likely to be true first. When you write And expressions, place the conditions most likely to be false first.

A benefit of designing your script in this manner is that runsecond() will not be executed in the following example if runfirst() returns 0 or false.

CopyCode image Copy Code
if ((runfirst() == 0) || (runsecond() == 0)) {
    // some code
}

Using Loops

There are several ways to execute a statement or block of statements repeatedly. In general, repetitive execution is called looping or iteration. An iteration is simply a single execution of a loop. It is typically controlled by a test of a variable, where the value of which is changed each time the loop is executed. JScript supports four types of loops: for loops, for...in loops, while loops, do...while loops.

Using for Loops

The for statement specifies a counter variable, a test condition, and an action that updates the counter. Before each iteration of the loop, the condition is tested. If the test is successful, the code inside the loop is executed. If the test is unsuccessful, the code inside the loop is not executed, and the program continues on the first line of code immediately following the loop. After the loop is executed, the counter variable is updated before the next iteration begins.

If the condition for looping is never met, the loop is never executed. If the test condition is always met, an infinite loop results. While the former may be desirable in certain cases, the latter rarely is, so be cautious when writing your loop conditions.

CopyCode image Copy Code
/*
The update expression ("icount++" in the following examples)
is executed at the end of the loop, after the block of statements that forms the
body of the loop is executed, and before the condition is tested.
*/

var howFar = 10; // Sets a limit of 10 on the loop.

var sum = new Array(howFar); // Creates an array called sum with 10 members, 0 through 9.
var theSum = 0;
sum[0] = 0;

for(var icount = 0; icount < howFar; icount++) { // Counts from 0 through 9 in this case.
theSum += icount;
sum[icount] = theSum;
}

var newSum = 0;
for(var icount = 0; icount > howFar; icount++) { // This isn't executed at all, since icount is not greater than howFar
newSum += icount;
}

var sum = 0;
for(var icount = 0; icount >= 0; icount++) { // This is an infinite loop.
sum += icount;
}

Using for...in Loops

JScript provides a special kind of loop for stepping through all the user-defined properties of an object, or all the elements of an array. The loop counter in a for...in loop is a string, not a number. It contains the name of current property or the index of the current array element.

The following code sample should be run from within Internet Explorer, since it uses the alert method, which is not a part of JScript.

CopyCode image Copy Code
// Create an object with some properties
var myObject = new Object();
myObject.name = "James";
myObject.age = "22";
myObject.phone = "555 1234";

// Enumerate (loop through)_all the properties in the object
for (prop in myObject)
{
    // This displays "The property 'name' is James", etc.
    window.alert("The property '" + prop + "' is " + myObject[prop]);
}

Although for...in loops look similar to VBScript's For Each...Next loops, they do not work the same way. The JScript for...in loop iterates over properties of JScript objects. The VBScript For Each...Next loop iterates over items in a collection. To loop over collections in JScript, you need to use the Enumerator object. Although some objects, such as those in Internet Explorer, support both VBScript's For Each...Next and JScript's for...in loops, most objects do not.

Using while Loops

A while loop is similar to a for loop. The difference is, a while loop does not have a built-in counter variable or update expression. If you want to control repetitive execution of a statement or block of statements, but need a more complex rule than simply "run this code n times", use a while loop. The following example uses the Internet Explorer object model and a while loop to ask the user a simple question.

CopyCode image Copy Code
var x = 0;
while ((x != 42) && (x != null))
{
    x = window.prompt("What is my favourite number?", x);
}

if (x == null)
    window.alert("You gave up!");
else
    window.alert("Yep - it's the Ultimate Answer!");
Note Note

Because while loops do not have explicit built-in counter variables, they are more vulnerable to infinite looping than the other types of loops. Moreover, because it is not necessarily easy to discover where or when the loop condition is updated, it is easy to write a while loop in which the condition never gets updated. For this reason, you should be careful when you design while loops.

As noted above, there is also a do...while loop in JScript that is similar to the while loop, except that it is guaranteed to always execute at least once, since the condition is tested at the end of the loop, rather than at the start. For example, the loop above can be re-written as:

CopyCode image Copy Code
var x = 0;
do
{
    x = window.prompt("What is my favourite number?", x);
} while ((x != 42) && (x != null));

if (x == null)
    window.alert("You gave up!");
else
    window.alert("Yep - it's the Ultimate Answer!");

Using break and continue Statements

In Microsoft JScript, the break statement is used to stop the execution of a loop, if some condition is met. (Note that break is also used to exit a switch block). The continue statement can be used to jump immediately to the next iteration, skipping the rest of the code block, while updating the counter variable if the loop is a for or for...in loop.

The following example builds on the previous example to use the break and continue statements to control the loop.

CopyCode image Copy Code
var x = 0;
do
{
    x = window.prompt("What is my favourite number?", x);

    // Did the user cancel? If so, break out of the loop
    if (x == null)
        break;

    // Did they enter a number?
    // If so, no need to ask them to enter a number.
    if (Number(x) == x)
        continue;

    // Ask user to only enter in numbers
    window.alert("Please only enter in numbers!");

} while (x != 42)

if (x == null)
    window.alert("You gave up!");
else
    window.alert("Yep - it's the Ultimate Answer!");


Functions (JScript 5.6)

JScript
Functions (JScript 5.6)
DropDown image

Microsoft JScript functions perform actions; they can also return values. Sometimes these are the results of calculations or comparisons. Functions are also called "global methods".

Functions combine several operations under one name. This lets you streamline your code. You can write out a set of statements, name it, and then execute the entire set by calling it and passing to it any information it needs.

You pass information to a function by enclosing the information in parentheses after the name of the function. Pieces of information that are passed to a function are called arguments or parameters. Some functions do not take any arguments at all while others take one or more arguments. In some functions, the number of arguments depends on how you are using the function.

JScript supports two kinds of functions: those that are built into the language, and those you create yourself.

Special Built-in Functions

The JScript language includes several built-in functions. Some let you handle expressions and special characters, while others convert strings to numeric values. A useful built-in function is eval(). This function evaluates any valid JScript code that is presented in string form. The eval() function takes one argument, the code to be evaluated. Here is an example using this function.

CopyCode image Copy Code
var anExpression = "6 * 9 % 7";
var total = eval(anExpression); // Assigns the value 5 to the variable total.
var yetAnotherExpression = "6 * (9 % 7)";
total = eval(yetAnotherExpression) // Assigns the value 12 to the variable total.
// Assign a string to totality (note the nested quotes)
var totality = eval("'...surrounded by acres of clams.'");

Consult the language reference for more information about these and other built-in functions.

Creating Your Own Functions

You can create your own functions and use them where needed. A function definition consists of a function statement and a block of JScript statements.

The checkTriplet function in the following example takes the lengths of the sides of a triangle as its arguments. It calculates from them whether the triangle is a right triangle by checking whether the three numbers constitute a Pythagorean triplet (the square of the length of the hypotenuse of a right triangle is equal to the sum of the squares of the lengths of the other two sides). The checkTriplet function calls one of two other functions to make the actual test.

Notice the use of a very small number ("epsilon") as a testing variable in the floating-point version of the test. Because of uncertainties and round-off errors in floating-point calculations, it is not practical to make a direct test of whether the three numbers constitute a Pythagorean triplet unless all three values in question are known to be integers. Because a direct test is more accurate, the code in this example determines whether it is appropriate and, if it is, uses it.

CopyCode image Copy Code
var epsilon = 0.00000000001; // Some very small number to test against.

// The test function for integers.
function integerCheck(a, b, c)
{
   // The test itself.
   if ( (a*a) == ((b*b) + (c*c)) )
      return true;

   return false;
} // End of the integer checking function.

// The test function for floating-point numbers.
function floatCheck(a, b, c)
{
   // Make the test number.
   var delta = ((a*a) - ((b*b) + (c*c)))

   // The test requires the absolute value
   delta = Math.abs(delta);

   // If the difference is less than epsilon, then it's pretty close.
   if (delta < epsilon)
      return true;

   return false;
} // End of the floating-poing check function.

// The triplet checker.
function checkTriplet(a, b, c)
{
   // Create a temporary variable for swapping values
   var d = 0;

   // First, move the longest side to position "a".

   // Swap a and b if necessary
   if (b > a)
   {
      d = a;
      a = b;
      b = d;
   }

   // Swap a and c if necessary
   if (c > a)
   {
      d = a;
      a = c;
      c = d;
   }

   // Test all 3 values. Are they integers?
   if (((a % 1) == 0) && ((b % 1) == 0) && ((c % 1) == 0))
   {
      // If so, use the precise check.
      return integerCheck(a, b, c);
   }
   else
   {
      // If not, get as close as is reasonably possible.
      return floatCheck(a, b, c);
   }
} // End of the triplet check function.

// The next three statements assign sample values for testing purposes.
var sideA = 5;
var sideB = 5;
var sideC = Math.sqrt(50.001);

// Call the function. After the call, 'result' contains the result.
var result = checkTriplet(sideA, sideB, sideC);


Objects (JScript 5.6)

JScript
Objects (JScript 5.6)
DropDown image

JScript objects are collections of properties and methods. A method is a function that is a member of an object. A property is a value or set of values (in the form of an array or object) that is a member of an object. JScript supports four kinds of objects: intrinsic objects, objects you create, host objects, which are provided by the host (such as window and document in Internet Explorer) and Active X objects (external components).

Objects as Arrays

In JScript, objects and arrays are handled almost identically. Both can have arbitrary properties assigned to them, and indeed Arrays are merely a special kind of Object. The difference between Arrays and Objects is that arrays have a "magic" length property, whilst objects do not. This means that if you assign a value to an element of an array that is greater than every other element — for example, myArray[100] = "hello" — then the length property will automatically be updated to be 101 (the new length). Similarly, if you modify the length property of an array, it will delete any elements that are no longer part of the array.

All objects in JScript support "expando" properties, or properties that can be added and removed dynamically at run time. These properties can have any name, including numbers. If the name of the property is a simple identifier<<ref for identifier rules>>, it can be written after the object name with a period, such as:

CopyCode image Copy Code
var myObj = new Object();

// Add two expando properties, 'name' and 'age'
myObj.name = "Fred";
myObj.age = 42;

If the name of the property is not a simple identifier, or it is not known at the time you write the script, you can use an arbitrary expression inside square brackets to index the property. The names of all expando properties in JScript are converted to strings before being added to the object.

CopyCode image Copy Code
var myObj = new Object();

// Add two expando properties that cannot be written in the
// object.property syntax.
// The first contains invalid characters (spaces), so must be
// written inside square brackets.
myObj["not a valid identifier"] = "This is the property value";

// The second expando name is a number, so it also must
// be placed inside square brackets
myObj[100] = "100";

Traditionally, array elements are given numeric indices, starting at zero. It is these elements that interact with the length property. Nevertheless, because all arrays are also objects, they support expando properties as well. Note, though, that expando properties do not interact with the length property in any way. For example:

CopyCode image Copy Code
// An array with three elements
var myArray = new Array(3);

// Add some data
myArray[0] = "Hello";
myArray[1] = 42;
myArray[2] = new Date(2000, 1, 1);

// This will display 3, the length of the array
window.alert(myArray.length);

// Add some expando properties
myArray.expando = "JScript!";
myArray["another Expando"] = "Windows";

// This will still display 3, since the two expando properties
// don't affect the length.
window.alert(myArray.length);

Although JScript does not directly support multi-dimensional arrays, you can store any sort of data inside array elements — including other arrays. So you can get the behavior of multi-dimensional arrays by storing arrays within the elements of another array. For example, the following code builds a multiplication table for the numbers up to 5:

CopyCode image Copy Code
// Change this number for a bigger table
var iMaxNum = 5;
// Loop counters
var i, j;

// New array. Make it iMaxNum + 1 because arrays start
// counting at zero, not 1.
var MultiplicationTable = new Array(iMaxNum + 1);

// Loop for each major number (each row in the table)
for (i = 1; i <= iMaxNum; i++)
{
    // Create the columns in the table
    MultiplicationTable[i] = new Array(iMaxNum + 1);

    // Fill the row with the results of the multiplication
    for (j = 1; j <= iMaxNum; j++)
    {
        MultiplicationTable[i][j] = i * j;
    }
}

window.alert(MultiplicationTable[3][4]); // Displays 12
window.alert(MultiplicationTable[5][2]); // Displays 10
window.alert(MultiplicationTable[1][4]); // Displays 4


Intrinsic Objects (JScript 5.6)

JScript
Intrinsic Objects (JScript 5.6)
DropDown image

Microsoft JScript provides eleven intrinsic (or "built-in") objects. They are the Array, Boolean, Date, Function, Global, Math, Number, Object, RegExp, Error, and String objects. Each of the intrinsic objects has associated methods and properties that are described in detail in the language reference. Certain objects are also described in this section.

Array Object

The subscripts of an array can be thought of as properties of an object, are referred to by their numeric index. Note that named properties added to an Array cannot be indexed by number; they are separate from the array elements.

To create a new array, use the new operator and the Array() constructor, as in the following example.

CopyCode image Copy Code
var theMonths = new Array(12);
theMonths[0] = "Jan";
theMonths[1] = "Feb";
theMonths[2] = "Mar";
theMonths[3] = "Apr";
theMonths[4] = "May";
theMonths[5] = "Jun";
theMonths[6] = "Jul";
theMonths[7] = "Aug";
theMonths[8] = "Sep";
theMonths[9] = "Oct";
theMonths[10] = "Nov";
theMonths[11] = "Dec";

When you create an array using the Array keyword, JScript includes a length property, which records the number of entries. If you do not specify a number, the length is set to 0, and the array has no entries. If you specify a number, the length is set to that number. If you specify more than one parameter, the parameters are used as entries in the array. In addition, the number of parameters is assigned to the length property, as in the following example, which is equivalent to the preceding example.

CopyCode image Copy Code
var theMonths = new Array("Jan", "Feb", "Mar", "Apr", "May", "Jun",
"Jul", "Aug", "Sep", "Oct", "Nov", "Dec");

JScript automatically changes the value of length when you add elements to an array that you created with the Array keyword. Array indices in JScript always start at 0, not 1, so the length property is always one greater than the largest index in the array.

String Object

In JScript, you can treat strings (and numbers) as if they were objects. The string Object has certain built-in methods, which you can use with your strings. One of these is the substring Method, which returns part of the string. It takes two numbers as its arguments.

CopyCode image Copy Code
aString = "0123456789";
var aChunk = aString.substring(4, 7);  // Sets aChunk to "456".
var aNotherChunk = aString.substring(7, 4);  // Sets aNotherChunk to "456".
// Using the preceding Array creation example:
firstLetter = theMonths[5].substring(0,1);  // Sets the firstLetter variable to "J".

Another property of the String object is the length property. This property contains the number of characters in the string (0 for an empty string). This a numeric value, and can be used directly in calculations.

CopyCode image Copy Code
var howLong = "Hello World".length  // Sets the howLong variable to 11.

Math Object

The Math object has a number of predefined properties and methods. The properties are specific numbers. One of these specific numbers is the value of pi (approximately 3.14159...). This is the Math.PI property, shown in the following example.

CopyCode image Copy Code
// A radius variable is declared and assigned a numeric value.
var circleArea = Math.PI * radius * radius;  // Note capitalization of Math and PI.

One of the built-in methods of the Math object is the exponentiation method, or pow, which raises a number to a specified power. The following example uses both pi and exponentiation.

CopyCode image Copy Code
// This formula calculates the volume of a sphere with the given radius.
volume = (4/3)*(Math.PI*Math.pow(radius,3));

Date Object

The Date object can be used to represent arbitrary dates and times, to get the current system date, and to calculate differences between dates. It has several properties and methods, all predefined. In general, the Date object provides the day of the week; the month, day, and year; and the time in hours, minutes, and seconds. This information is based on the number of milliseconds since January 1, 1970, 00:00:00.000 GMT, which is Greenwich Mean Time (the preferred term is UTC, or "Universal Coordinated Time," which refers to signals issued by the World Time Standard). JScript can handle dates that are in the approximate range 250,000 B.C. to 255,000 A.D.

To create a new Date object, use the new operator. The following example calculates, for the current year, the number of days that have passed and the number of days that are left.

CopyCode image Copy Code
/*
This example uses the array of month names defined previously.
The first statement assigns today's date, in "Day Month Date 00:00:00 Year"
format, to the thisIsToday variable.
*/
var thisIsToday = new Date();

var toDay = new Date();  // Capture today's date.

// Extract the year, the month, and the day.
var thisYear = toDay.getFullYear();
var thisMonth = theMonths[toDay.getMonth()];
var thisDay = thisMonth  + " " + toDay.getDate() + ", " + thisYear;

Number Object

In addition to the special numeric properties (PI, for example) that are available in the Math object, several other properties are available in Microsoft JScript through the Number object.

Property | Description
MAX_VALUE | Largest possible number, about 1.79E+308; can be positive or negative. (Value varies slightly from system to system.)
MIN_VALUE | Smallest possible number, about 2.22E-308; can be positive or negative. (Value varies slightly from system to system.)
NaN | Special nonnumeric value, "not a number."
POSITIVE_INFINITY | Any positive value larger than the largest positive number (Number.MAX_VALUE) is automatically converted to this value; represented as infinity.
NEGATIVE_INFINITY | Any value more negative than the largest negative number (-Number.MAX_VALUE) is automatically converted to this value; represented as -infinity.

Number.NaN is a special property that is defined as "not a number." Division by zero, for example, returns NaN. An attempt to parse a string that cannot be parsed as a number also returns Number.NaN. NaN compares unequal to any number and to itself. To test for a NaN result, do not compare against Number.NaN; use the isNaN() function instead.


Creating Your Own Objects

JScript
Creating Your Own Objects
DropDown image

To create instances of your own objects, you must first define a constructor function for them. A constructor function creates a new object, giving it properties and, if appropriate, methods. For instance, the following example defines a constructor function for pasta objects. Notice the use of the this keyword, which refers to the current object.

Example

CopyCode image Copy Code
// pasta is a constructor that takes four parameters.
function pasta(grain, width, shape, hasEgg)
{
    // What grain is it made of?
    this.grain = grain;

    // How wide is it? (number)
    this.width = width;

    // What is the cross-section? (string)
    this.shape = shape;

    // Does it have egg yolk as a binder? (boolean)
    this.hasEgg = hasEgg;
}

Once you define an object constructor, you create instances of it with the new operator.

CopyCode image Copy Code
var spaghetti = new pasta("wheat", 0.2, "circle", true);
var linguine = new pasta("wheat", 0.3, "oval", true);

You can add properties to one instance of an object to change that instance, but those properties do not become part of the definition of other objects made with the same constructor, and do not show up in other instances unless you specifically add them. If you want the extra properties to show up in all instances of the object, you must add them to the constructor function, or to the constructor's prototype object (prototypes are discussed in the Advanced documentation).

CopyCode image Copy Code
// Additional properties for spaghetti.
spaghetti.color = "pale straw";
spaghetti.drycook = 7;
spaghetti.freshcook = 0.5;

var chowFun = new pasta("rice", 3, "flat", false);
// Neither the chowFun object, nor any of the other existing
// pasta objects have the three new properties that were added
// to the spaghetti object.

// Adding the 'foodgroup' property to the pasta prototyp object
// makes it available to all instances of pasta objects,
// including those that have already been created.
pasta.prototype.foodgroup = "carbohydrates"

// now spaghetti.foodgroup, chowFun.foodgroup, etc. all
// contain the value "carbohydrates"

Including Methods in the Definition

It is possible to include methods (functions) in the definition of an object. One way to do this is to add include a property in the constructor function that refers to a function defined elsewhere. For instance, the following example expands on the pasta constructor function defined above to include a toString method that will be called if you display the value of the object.

CopyCode image Copy Code
// pasta is a constructor that takes four parameters.
// The first part is the same as above
function pasta(grain, width, shape, hasEgg)
{
    // What grain is it made of?
    this.grain = grain;

    // How wide is it? (number)
    this.width = width;

    // What is the cross-section? (string)
    this.shape = shape;

    // Does it have egg yolk as a binder? (boolean)
    this.hasEgg = hasEgg;

    // Here we add the toString method (which is defined below).
    // Note that we don't put the parentheses after the name of
    // the function; this is not a function call, but a
    // reference to the function itself.
    this.toString = pastaToString;
}

// The actual function to display the contents of a pasta object.
function pastaToString()
{
    // return the properties of the object

    return "Grain: " + this.grain + "\n" +
        "Width: " + this.width + "\n" +
        "Shape: " + this.shape + "\n" +
        "Egg?: " + Boolean(this.hasEgg);
}

var spaghetti = new pasta("wheat", 0.2, "circle", true);
// This will call toString() and display the properties
// of the spaghetti object (required Internet Explorer).
window.alert(spaghetti);


Displaying Information in the Browser (JScript 5.6)

JScript
Displaying Information in the Browser (JScript 5.6)
DropDown image

Microsoft JScript provides two ways to display data directly in your browser. You can use the write( ) and writeln( ), which are methods of the document object. You can also display information in forms within the browser, and in alert, prompt, and confirm message boxes.

Using document.write( ) and document.writeln( )

The most common way to display information is the write( ) method of the document object. It takes one argument, a string, which it displays in the browser. The string can be either plain text or HTML.

Strings can be enclosed in either single or double quotation marks. This lets you quote something that contains quote marks or apostrophes.

CopyCode image Copy Code
document.write("Pi is approximately equal to " + Math.PI);
document.write( );
Note Note

The following simple function is a way around having to type "document.write" every time you want something to appear in the browser window. This function does not inform you if something that you attempt to write is undefined, but does let you issue the command "w();", which displays a blank line.

CopyCode image Copy Code
function w(m) { // Write function.
m = "" + m + ""; //  Make sure that the m variable is a string.
if ("undefined" != m) { // Test for empty write or other undefined item.
   document.write(m);
   }
document.write("<br>");
}

w('<IMG SRC="horse.gif">');
w();
w("This is an engraving of a horse.");
w();

The writeln( ) method is almost identical to the write( ) method, except that it appends a newline character to whatever string you provide. In HTML this ordinarily results only in a space after your item; but if you're using <PRE> and <XMP> tags, the newline character is interpreted literally and the browser displays it.

When you call the write( ) method, it opens and clears the document if the document is not in the process of being opened and parsed when the write( ) method is called, so it can be dangerous. The example shows a script that is intended to display the time once a minute, but fails to do so after the first time because it clears itself in the process.

CopyCode image Copy Code
<HTML>
<HEAD>
<SCRIPT LANGUAGE="JScript">
function singOut()  {
var theMoment = new Date();
var theHour = theMoment.getHours();
var theMinute = theMoment.getMinutes();
var theDisplacement = (theMoment.getTimezoneOffset() / 60);
theHour -= theDisplacement;
if (theHour > 23)  {
theHour -= 24
}
document.write(theHour + " hours, " + theMinute + " minutes, Coordinated Universal Time.");
window.setTimeout("singOut();", 60000);
}
</SCRIPT>
</HEAD>
<BODY>
<SCRIPT>
singOut();
</SCRIPT>
</BODY>
</HTML>

If you use the alert() method of the window object instead of document.write(), the script works.

CopyCode image Copy Code
window.alert(theHour + " hours, " + theMinute + " minutes, Coordinated Universal Time.");
window.setTimeout("singOut();", 60000);
}

Clearing the Current Document

The clear() method of the document object empties the current document. This method also clears your script (along with the rest of the document), so be very careful how and when you use it.

CopyCode image Copy Code
document.clear();


Using Message Boxes (JScript 5.6)

JScript
Using Message Boxes (JScript 5.6)
DropDown image

Message boxes display information to users or request input before completing a procedure.

Using alert, prompt, and confirm

Use alert, confirm, and prompt message boxes to obtain input from your user. The boxes are methods of the interface window object. Because the window object is at the top of the object hierarchy, you do not actually have to use the full name (for example, "window.alert()") of any of these message boxes, but it is a good idea to do so, because it helps you remember to which object they belong.

Alert Message Box

The alert method has one argument, the string of text you want to display to the user. The string is not HTML. The message box provides an OK button so the user can close it and is modal, that is, the user must close the message box before continuing.

CopyCode image Copy Code
window.alert("Welcome! Press OK to continue.");

Confirm Message Box

The confirm message box lets you ask the user a "yes-or-no" question, and gives the user the option of clicking either an OK button or a Cancel button. The confirm method returns either true or false. This message box is also modal: the user must respond to it (click a button), and thereby close it, before proceeding.

CopyCode image Copy Code
var truthBeTold = window.confirm("Click OK to continue. Click Cancel to stop.");
if (truthBeTold) {
window.alert("Welcome to our Web page!");
} else  window.alert("Bye for now!");

Prompt Message Box

The prompt message box provides a text field in which the user can type an answer in response to your prompt. This box has an OK button and a Cancel button. If you provide a second string argument, the prompt message box displays that second string in the text field, as the default response. Otherwise, the default text is "<undefined>".

Like the alert( ) and confirm( ) methods, prompt displays a modal message box. The user must close it before continuing.

CopyCode image Copy Code
var theResponse = window.prompt("Welcome?","Enter your name here.");


JScript Reserved Words (JScript 5.6)

JScript
JScript Reserved Words (JScript 5.6)
DropDown image

JScript has a number of reserved words that you cannot use as identifiers. Reserved words have a specific meaning to the JScript language, as they are part of the language syntax. Using a reserved word causes a compilation error when loading your script.

JScript also has a list of future reserved words. These words are not currently part of the JScript language, although they are reserved for future use.

Reserved Words
break | delete | function | return | typeof
case | do | if | switch | var
catch | else | in | this | void
continue | false | instanceof | throw | while
debugger | finally | new | true | with
default | for | null | try |

Future Reserved Words

abstract | double | goto | native | static
boolean | enum | implements | package | super
byte | export | import | private | synchronized
char | extends | int | protected | throws
class | final | interface | public | transient
const | float | long | short | volatile

When choosing identifiers it is also important to avoid any words that are already the names of intrinsic JScript objects or functions, such as String or parseInt.


Advanced JScript

JScript
Advanced JScript
DropDown image

These sections explain advanced JScript functionality, such as recursion, arrays, troubleshooting, and so on.

In This Section

Advanced Object Creation

Explains how to use constructors to instantiate and initialize a particular type of object.

Recursion

Explains how JScript uses recursion and looping.

Variable Scope

Describes the distinction between global and local scopes.

Copying, Passing, and Comparing Data

Explains the concept of passing by value or by reference.

Using Arrays

Describes the concept of arrays in JScript.

Special Characters

Lists the characters that allow you to include in strings characters you cannot type directly.

Troubleshooting Your Scripts

Explains how to find common script errors.

Conditional Compilation

Describes the statements that JScript uses compile depending on specific conditions.

Conditional Compilation Variables

Lists the variables that are available for conditional compilation.

Related Sections

VBScript User's Guide

Provides information about how to use VBScript and includes a guide to regular expressions.

VBScript Language Reference

Explains the elements that comprise the VBScript language.


Advanced Object Creation (JScript 5.6)

JScript
Advanced Object Creation (JScript 5.6)
DropDown image

A constructor is a function you call to instantiate and initialize a particular type of object. You invoke a constructor with the new keyword. Here are a few examples of using constructors.

Constructor Examples

CopyCode image Copy Code
var myObject = new Object();             // Creates a generic object with no properties.
var myBirthday = new Date(1961, 5, 10);  // Creates a Date object.
var myCar = new Car();                   // Creates a user defined object, and initializes its properties.

The constructor is passed a reference to a newly created empty object as the value of the special this keyword. It is then responsible for performing appropriate initialization for the new object (creating properties and giving them initial values). When completed, the constructor returns a reference to the object it constructed.

Writing Constructors

You can create objects and initialize them using the new operator in conjunction with predefined constructor functions such as Object(), Date(), and Function(). A powerful feature of object-oriented programming is the ability to define custom constructor functions to create custom objects for use in your scripts. You create custom constructors so you can create objects with properties already defined. Here is an example of a custom constructor (note the use of the this keyword).

CopyCode image Copy Code
function Circle (xPoint, yPoint, radius) {
    this.x = xPoint;  // The x component of the center of the circle.
    this.y = yPoint;  // The y component of the center of the circle.
    this.r = radius;  // The radius of the circle.
}

When you invoke the Circle constructor, you supply values for the circle's center point and the radius (these elements are all that is needed to completely define a unique circle object). You end up with a Circle object that contains three properties. Here is how you would instantiate a Circle object.

CopyCode image Copy Code
var aCircle = new Circle(5, 11, 99);

Using Prototypes to Create Objects

When you write a constructor, you can use properties of the prototype object (which is itself a property of every constructor) to create inherited properties, and shared methods. Prototype properties and methods are copied by reference into each object of a class, so they all have the same values. You can change the value of a prototype property in one object, and the new value overrides the default, but only in that one instance. Other objects that are members of the class are not affected by the change. Here is an example that makes use of the custom constructor, Circle (note the use of the this keyword).

CopyCode image Copy Code
Circle.prototype.pi = Math.PI;
function ACirclesArea () {
    return this.pi * this.r * this.r; // The formula for the area of a circle is r<SUP>2</SUP>.
}
Circle.prototype.area = ACirclesArea; // The function that calculates the area of a circle is now a method of the Circle Prototype object.
var a = ACircle.area();               // This is how you would invoke the area function on a Circle object.

Using this principle, you can define additional properties for predefined constructor functions (which all have prototype objects). For example, if you want to be able to remove leading and trailing spaces from strings (similar to VBScript's Trim function), you can create your own method on the String prototype object, and all strings in your script will automatically inherit the method.

CopyCode image Copy Code
// Add a function called trim as a method of the prototype
// object of the String constructor.
String.prototype.trim = function()
{
    // Use a regular expression to replace leading and trailing
    // spaces with the empty string
    return this.replace(/(^\s*)|(\s*$)/g, "");
}

// A string with spaces in it
var s = "    leading and trailing spaces    ";

// Displays "    leading and trailing spaces     (35)"
window.alert(s + " (" + s.length + ")");

// Remove the leading and trailing spaces
s = s.trim();
// Displays "leading and trailing spaces (27)"
window.alert(s + " (" + s.length + ")");


Recursion (JScript 5.6)

JScript
Recursion (JScript 5.6)
DropDown image

Recursion is an important programming technique. It is used to have a function call itself from within itself. One example is the calculation of factorials. The factorial of 0 is defined specifically to be 1. The factorials of larger numbers are calculated by multiplying 1 * 2 * ..., incrementing by 1 until you reach the number for which you are calculating the factorial.

An Example of Recursion

The following paragraph is a function, defined in words, that calculates a factorial.

"If the number is less than zero, reject it. If it is not an integer, round it down to the next integer. If the number is zero, its factorial is one. If the number is larger than zero, multiply it by the factorial of the next lesser number."

To calculate the factorial of any number that is larger than zero, you need to calculate the factorial of at least one other number. The function you use to do that is the function you're in the middle of already; the function must call itself for the next smaller number, before it can execute on the current number. This is an example of recursion.

Recursion and iteration (looping) are strongly related - anything that can be done with recursion can be done with iteration, and vice-versa. Usually a particular computation will lend itself to one technique or the other, and you simply need to choose the most natural approach, or the one you feel most comfortable with.

Clearly, there is a way to get in trouble here. You can easily create a recursive function that does not ever get to a definite result, and cannot reach an endpoint. Such a recursion causes the computer to execute a so-called "infinite" loop. Here's an example: omit the first rule (the one about negative numbers) from the verbal description of calculating a factorial, and try to calculate the factorial of any negative number. This fails, because in order to calculate the factorial of, say, -24 you first have to calculate the factorial of -25; but in order to do that you first have to calculate the factorial of -26; and so on. Obviously, this never reaches a stopping place.

Thus, it is extremely important to design recursive functions with great care. If you even suspect that there is any chance of an infinite recursion, you can have the function count the number of times it calls itself. If the function calls itself too many times (whatever number you decide that should be) it automatically quits.

Here is the factorial function again, this time written in JScript code.

CopyCode image Copy Code
// Function to calculate factorials. If an invalid
// number is passed in (ie, one less than zero), -1
// is returned to signify an error. Otherwise, the
// number is converted to the nearest integer, and its
// factorial is returned.
function factorial(aNumber)  {
aNumber = Math.floor(aNumber);  // If the number is not an integer, round it down.
if (aNumber < 0)  {  // If the number is less than zero, reject it.
    return -1;
    }
      if (aNumber == 0)  {  // If the number is 0, its factorial is 1.
      return 1;
      }
        else return (aNumber * factorial(aNumber - 1));  // Otherwise, recurse until done.
}


Variable Scope

JScript
Variable Scope
DropDown image

JScript has two scopes: global and local. If you declare a variable outside of any function definition, it is a global variable, and its value is accessible and modifiable throughout your program. If you declare a variable inside of a function definition, that variable is local. It is created and destroyed every time the function is executed; it cannot be accessed by anything outside the function.

Types of Scope

Languages such as C++ also have "block scope." Here, any set of braces "{}" defines a new scope. JScript does not support block scopes.

A local variable can have the same name as a global variable, but it is entirely distinct and separate. Consequently, changing the value of one variable has no effect on the other. Inside the function in which the local variable is declared, only the local version has meaning.

CopyCode image Copy Code
var aCentaur = "a horse with rider,"; // Global definition of aCentaur.

// JScript code, omitted for brevity.
function antiquities() // A local aCentaur variable is declared in this function.
{

// JScript code, omitted for brevity.
var aCentaur = "A centaur is probably a mounted Scythian warrior";

// JScript code, omitted for brevity.
   aCentaur += ", misreported; that is, "; // Adds to the local variable.

// JScript code, omitted for brevity.
} // End of the function.

var nothinginparticular = antiquities();
aCentaur += " as seen from a distance by a naive innocent.";

/*
Within the function, the variable contains "A centaur is probably a mounted Scythian warrior,
misreported; that is, "; outside the function, the variable contains the rest of the sentence:
"a horse with rider, as seen from a distance by a naive innocent."
*/

It's important to note that variables act as if they were declared at the beginning of whatever scope they exist in. Sometimes this results in unexpected behaviors.

CopyCode image Copy Code
tweak();
var aNumber = 100;
function tweak()  {
    var newThing = 0;  // Explicit declaration of the newThing variable.

    // This statement assigns the value undefined to newThing because there is a local variable with the name aNumber.
    newThing = aNumber;

    // The next statement assigns the value 42 to the local aNumberaNumber = 42;
    if (false)  {
        var aNumber;  // This statement is never executed.
        aNumber = 123;  // This statement is never executed.
        }  // End of the conditional.

}  // End of the function definition.

When JScript executes a function, it first looks for all variable declarations,

CopyCode image Copy Code
var someVariable;

and creates the variables with an initial value of undefined. If a variable is declared with a value,

CopyCode image Copy Code
var someVariable = "something";

then it still initially has the value undefined, and will take on the declared value only when the line containing the declaration is executed, if ever.

JScript processes variable declarations before executing any code, so it does not matter whether the declaration is inside a conditional block or some other construct. Once JScript has found all the variables, it executes the code in the function. If a variable is implicitly declared inside a function - that is, if it appears on the left-hand-side of an assignment expression but has not been declared with var - then it is created as a global variable.


Copying, Passing, and Comparing Data (JScript 5.6)

JScript
Copying, Passing, and Comparing Data (JScript 5.6)
DropDown image

In JScript, how data is handled depends on its data type.

By Value vs. By Reference

Numbers and Boolean values (true and false) are copied, passed, and compared by value. When you copy or pass by value, you allocate a space in computer memory and copy the value of the original into it. If you then change the original, the copy is not affected (and vice versa), because the two are separate entities.

Objects, arrays, and functions are copied, passed, and compared by reference. When you copy or pass by reference, you essentially create a pointer to the original item, and use the pointer as if it were a copy. If you then change the original, you change both the original and the copy (and vice versa). There is really only one entity; the "copy" is not actually a copy, it's just another reference to the data.

When comparing by reference, the two variables must refer to exactly the same entity for the comparison to succeed. For example, two distinct Array objects will always compare as unequal, even if they contain the same elements. One of the variables must be a reference to the other one for the comparison to succeed. To check if two Arrays hold the same elements, compare the results of the toString() method.

Last, strings are copied and passed by reference, but are compared by value. Note that if you have two String objects (created with new String("something")), they are compared by reference, but if one or both of the values is a string value, they are compared by value.

Note Note

Because of the way the ASCII and ANSI character sets are constructed, capital letters precede lowercase ones in sequence order. For example, "Zoo" compares as less than "aardvark." You can call toUpperCase() or toLowerCase() on both strings if you want to perform a case-insensitive match.

Passing Parameters to Functions

When you pass a parameter to a function by value, you are making a separate copy of that parameter, a copy that exists only inside the function. Even though objects and arrays are passed by reference, if you directly overwrite them with a new value in the function, the new value is not reflected outside the function. Only changes to properties of objects, or elements of arrays, are visible outside the function.

For example (using the Internet Explorer object model):

CopyCode image Copy Code
// This clobbers (over-writes) its parameter, so the change
// is not reflected in the calling code.
function Clobber(param)
{
    // clobber the parameter; this will not be seen in
    // the calling code
    param = new Object();
    param.message = "This will not work";
}

// This modifies a property of the parameter, which
// can be seen in the calling code.
function Update(param)
{
    // Modify the property of the object; this will be seen
    // in the calling code.
    param.message = "I was changed";
}

// Create an object, and give it a property.
var obj = new Object();
obj.message = "This is the original";

// Call Clobber, and print obj.message. Note that it hasn't changed.
Clobber(obj);
window.alert(obj.message); // Still displays "This is the original".

// Call Update, and print obj.message. Note that is has changed.
Update(obj);
window.alert(obj.message); // Displays "I was changed".

Testing Data

When you perform a test by value, you compare two distinct items to see whether they are equal to each other. Usually, this comparison is performed on a byte-by-byte basis. When you test by reference, you are checking to see whether two items are pointers to a single original item. If they are, then they compare as equal; if not, even if they contain the exact same values, byte-for-byte, they compare as unequal.

Copying and passing strings by reference saves memory; but because you cannot change strings once they are created, it becomes possible to compare them by value. This lets you test whether two strings have the same content even if one was generated entirely separately from the other.


Using Arrays (JScript 5.6)

JScript
Using Arrays (JScript 5.6)
DropDown image

Arrays in JScript are sparse. That is, if you have an array with three elements that are numbered 0, 1, and 2, you can create element 50 without worrying about elements 3 through 49. If the array has an automatic length variable (see Intrinsic Objects for an explanation of automatic monitoring of array length), the length variable is set to 51, rather than to 4. You can certainly create arrays in which there are no gaps in the numbering of elements, but you are not required to.

In JScript, objects and arrays are almost identical to each other. The two main differences are that normal objects do not have an automatic length property, and arrays do not have the properties and methods of an object.

Addressing Arrays

You address arrays by using brackets "[]". The brackets enclose either a numeric value, or an expression that evaluates to a whole number. The following example assumes that the entryNum variable is defined and assigned a value elsewhere in the script.

CopyCode image Copy Code
theListing = addressBook[entryNum];
theFirstLine = theListing[1];

Objects as Associative Arrays

Normally, you use the dot operator "." to access an object's properties. For example,

CopyCode image Copy Code
myObject.aProperty

Here, the property name is an identifier. You can also access an object's properties using the index operator "[]". Here, you are treating the object as an associative array. An associative array is a data structure that allows you to dynamically associate arbitrary data values with arbitrary strings. For example,

CopyCode image Copy Code
myObject["aProperty"] // Same as above.

Although the use of the index operator is more commonly associated with accessing array elements, when used with objects, the index is always the property name expressed as a string literal.

Notice the important difference between the two ways of accessing object properties.

Operator | The property name is treated as | Meaning the property name
Dot "." | an identifier | cannot be manipulated as data
Index "[]" | a string literal | can be manipulated as data

This difference becomes useful when you do not know what the property names will be until runtime (for example, when you are constructing objects based on user input). To extract all the properties from an associative array, you must use the for in loop.


Special Characters (JScript 5.6)

JScript
Special Characters (JScript 5.6)
DropDown image

JScript provides special characters that allow you to include in strings some characters you cannot type directly. Each of these characters begins with a backslash. The backslash is an escape character you use to inform the JScript interpreter that the next character is special.

Escape Sequence

Escape Sequence | Character
\b | Backspace
\f | Form feed
\n | Line feed (newline)
\r | Carriage return
\t | Horizontal tab (Ctrl-I)
\' | Single quotation mark
\" | Double quotation mark
\\ | Backslash

Notice that because the backslash itself is used as the escape character, you cannot directly type one in your script. If you want to write a backslash, you must type two of them together (\\).

CopyCode image Copy Code
document.write('The image path is C:\\webstuff\\mypage\\gifs\\garden.gif.');
document.write('The caption reads, "After the snow of \'97. Grandma\'s house is covered."');


Troubleshooting Your Scripts (JScript 5.6)

JScript
Troubleshooting Your Scripts (JScript 5.6)
DropDown image

There are places in any programming language where you can get caught if you are not careful, and every language has specific surprises in it. Take, for example, the null value: The one in JScript behaves differently than the Null value in the C or C++ languages.

Here are some of the trouble areas that you may run into as you write JScript scripts.

Syntax Errors

Because syntax is much more rigid in programming languages than in natural languages, it is important to pay strict attention to detail when you write scripts. If, for example, you mean for a particular parameter to be a string, you will run into trouble if you forget to enclose it in quotation marks when you type it.

Order of Script Interpretation

JScript interpretation is part of the your Web browser's HTML parsing process. So, if you place a script inside the <HEAD> tag in a document, it is interpreted before any of the <BODY> tag is examined. If you have objects that are created in the <BODY> tag, they do not exist at the time the <HEAD> is being parsed, and cannot be manipulated by the script.

Note Note

This behavior is specific to Internet Explorer. ASP and WSH have different execution models (as would other hosts).

Automatic Type Coercion

JScript is a loosely typed language with automatic coercion. Consequently, despite the fact that values having different types are not equal, the expressions in the following example evaluate to true.

CopyCode image Copy Code
"100" == 100;
false == 0;

To check that both the type and value are the same, use the strict equality operator, ===. the following both evaluate to false:

CopyCode image Copy Code
"100" === 100;
false === 0;

Operator Precedence

When a particular operation is performed during the evaluation of an expression has more to do with operator precedence than with the location of the expression. Thus, in the following example, multiplication is performed before subtraction, even though the subtraction appears first in the expression.

CopyCode image Copy Code
theRadius = aPerimeterPoint - theCenterpoint * theCorrectionFactor;

Using for...in Loops with Objects

When you step through the properties of an object with a for...in loop, you cannot necessarily predict or control the order in which the fields of the object are assigned to the loop counter variable. Moreover, the order may be different in different implementations of the language.

with Keyword

The with statement is convenient for addressing properties that already exist in a specified object, but cannot be used to add properties to an object. To create new properties in an object, you must refer to the object specifically.

this Keyword

Although you use the this keyword inside the definition of an object, to refer to the object itself, you cannot ordinarily use this or similar keywords to refer to the currently executing function when that function is not an object definition. You can, if the function is to be assigned to an object as a method, use the this keyword within the function, to refer to the object.

Writing a Script That Writes a Script in Internet Explorer

The </SCRIPT> tag terminates the current script if the interpreter encounters it. To display "</SCRIPT>" itself, rewrite this as at least two strings, for example, "</SCR" and "IPT>", which you can then concatenate together in the statement that writes them out.

Implicit Window References in Internet Explorer

Because more than one window can be open at a time, any window reference that is implicit is taken to point to the current window. For other windows, you must use an explicit reference.


Conditional Compilation (JScript 5.6)

JScript
Conditional Compilation (JScript 5.6)
DropDown image

Conditional compilation allows the use of new JScript language features without sacrificing compatibility with older versions that do not support the features.

Statements

Conditional compilation is activated by using the @cc_on statement, or using an @if or @set statement. Some typical uses for conditional compilation include using new features in JScript, embedding debugging support into a script, and tracing code execution.

Always place conditional compilation code in comments, so that hosts (like Netscape Navigator) that do not understand conditional compilation will ignore it. Here is an example.

CopyCode image Copy Code
/*@cc_on @*/
/*@if (@_jscript_version >= 4)
   alert("JScript version 4 or better");
   @else @*/
   alert("You need a more recent script engine.");
/*@end @*/

This example uses special comment delimiters that are only used if conditional compilation is activated by the @cc_on statement. Scripting engines that do not support conditional compilation only see the message informing of the need for a new scripting engine.


Conditional Compilation Variables (JScript 5.6)

JScript
Conditional Compilation Variables (JScript 5.6)
DropDown image

The following predefined variables are available for conditional compilation. If a variable is not true, it is not defined and behaves as NaN when accessed.

Variables

Variable | Description
@_win32 | True if running on a Win32 system.
@_win16 | True if running on a Win16 system.
@_mac | True if running on an Apple Macintosh system.
@_alpha | True if running on a DEC Alpha processor.
@_x86 | True if running on an Intel processor.
@_mc680x0 | True if running on a Motorola 680x0 processor.
@_PowerPC | True if running on a Motorola PowerPC processor.
@_jscript | Always true.
@_jscript_build | Contains the build number of the JScript scripting engine.
@_jscript_version | Contains the JScript version number in major.minor format.


Introduction to Regular Expressions (Scripting)

JScript
Introduction to Regular Expressions (Scripting)
DropDown image

These sections introduce the concept of regular expressions and explain how to create and use them.

While each topic stands on its own, it is recommended that you peruse these topics sequentially to develop the best understanding of the material. Many topics rely upon the understanding of a feature or concept that was introduced in a previous topic in the sequence.

In This Section

Regular Expressions

Explains the concept of regular expressions.

Early Beginnings

Explains the history of regular expressions.

Uses for Regular Expressions

Illustrates circumstances that would benefit from the use of regular expressions.

Regular Expression Syntax

Demonstrates the elements that comprise the regular expression syntax.

Build a Regular Expression

Explains how you combine elements to produce a regular expression.

Order of Precedence

Lists the operators and the order in which they are evaluated in a regular expression.

Ordinary Characters

Explains the concept of ordinary characters that apply to regular expressions.

Special Characters

Explains the concept of special characters that apply to regular expressions.

Non-Printable Characters

Lists the non-printing characters that apply to regular expressions.

Character Matching

Explains how special characters match printing or non-printing characters in regular expressions.

Quantifiers

Lists the quantifier characters and explains how to use them in regular expressions.

Anchors

Explains the concept of anchors which allow you to fix a regular expression to either the beginning or end of a line.

Alternation and Grouping

Explains how to use the '|' character for choices between to alternatives and how grouping effect the outcome of expressions.

Backreferences

Provides information about how you can store part of a matched pattern for later use.

Related Sections

JScript User's Guide

Provides information about how to use JScript and includes a guide to regular expressions.

VBScript User's Guide

Provides information about how to use VBScript and includes a guide to regular expressions.


Regular Expressions (Scripting)

JScript
Regular Expressions (Scripting)
CollapseAll image DropDown image

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.

Expand image The Concept of Regular Expressions

Think about how you search for files on your hard disk. You most likely use the ? and * characters to find files. 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.


Early Beginnings (Scripting)

JScript
Early Beginnings (Scripting)
CollapseAll image DropDown image

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.

Expand image Introduction of the Concept of Regular Expressions

In 1956, a 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.


Uses for Regular Expressions (Scripting)

JScript
Uses for Regular Expressions (Scripting)
CollapseAll image DropDown image

In a typical search and replace operation, you must provide the exact text for which you are searching. 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.

Expand image Flexibility of Regular Expressions

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 is not 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.


Regular Expression Syntax (Scripting)

JScript
Regular Expression Syntax (Scripting)
CollapseAll image DropDown image

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.

Expand image Examples of Regular Expressions

JScript | VBScript | Matches
/^\s[ \t]*$/ | "^\s*$" | Match a blank line.
/\d{2}-\d{5}/ | "\d{2}-\d{5}" | Validate an ID number consisting of 2 digits, a hyphen, and another 5 digits.

The following table contains the complete list of metacharacters and their behavior in the context of regular expressions:

Character | Description
\ | Marks the next character as 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 character or subexpression zero or more times. For example, zo* matches "z" and "zoo". * is equivalent to {0,}.
+ | Matches the preceding character or subexpression one or more times. For example, 'zo+' matches "zo" and "zoo", but not "z". + is equivalent to {1,}.
? | Matches the preceding character or subexpression zero or one time. For example, "do(es)?" matches the "do" in "do" or "does". ? is equivalent to {0,1}
{n} | 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,} | 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*'.
{n,m} | 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 '[\s\S].
(pattern) | 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 '\)'.
(?:pattern) | 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'.
(?=pattern) | 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.
(?!pattern) | 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.
x|y | Matches either x or y. For example, 'z|food' matches "z" or "food". '(z|f)ood' matches "zood" or "food".
[xyz] | A character set. Matches any one of the enclosed characters. For example, '[abc]' matches the 'a' in "plain".
[^xyz] | A negative character set. Matches any character not enclosed. For example, '[^abc]' matches the 'p' in "plain".
[a-z] | 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-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'.
\b | 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".
\B | Matches a nonword boundary. 'er\B' matches the 'er' in "verb" but not the 'er' in "never".
\cx | 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.
\d | Matches a digit character. Equivalent to [0-9].
\D | Matches a nondigit character. Equivalent to [^0-9].
\f | Matches a form-feed character. Equivalent to \x0c and \cL.
\n | Matches a newline character. Equivalent to \x0a and \cJ.
\r | Matches a carriage return character. Equivalent to \x0d and \cM.
\s | Matches any white space character including space, tab, form-feed, and so on. Equivalent to [ \f\n\r\t\v].
\S | Matches any non-white space character. Equivalent to [^ \f\n\r\t\v].
\t | Matches a tab character. Equivalent to \x09 and \cI.
\v | Matches a vertical tab character. Equivalent to \x0b and \cK.
\w | Matches any word character including underscore. Equivalent to '[A-Za-z0-9_]'.
\W | Matches any nonword character. Equivalent to '[^A-Za-z0-9_]'.
\xn | 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.
\num | Matches num, where num is a positive integer. A reference back to captured matches. For example, '(.)\1' matches two consecutive identical characters.
\n | 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).
\nm | 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 exist, \nm matches octal escape value nm when n and m are octal digits (0-7).
\nml | Matches octal escape value nml when n is an octal digit (0-3) and m and l are octal digits (0-7).
\un | Matches n, where n is a Unicode character expressed as four hexadecimal digits. For example, \u00A9 matches the copyright symbol (©).


Build a Regular Expression (Scripting)

JScript
Build a Regular Expression (Scripting)
CollapseAll image DropDown image

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.

Expand image Constructing a Regular Expression

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:

CopyCode image Copy Code
/expression/

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

CopyCode image Copy Code
"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.


Order of Precedence (Scripting)

JScript
Order of Precedence (Scripting)
CollapseAll image DropDown image

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.

Expand image From Highest to Lowest, the Order of Precedence of the Regular Expression Operators:

Operator(s) | Description
\ | Escape
(), (?:), (?=), [] | Parentheses and Brackets
*, +, ?, {n}, {n,}, {n,m} | Quantifiers
^, $, \anymetacharacter | Anchors and Sequences
| | Alternation

Characters have higher precedence than the alternation operator, which allows 'm|food' to match "m" or "food". To match "mood" or "food", use parentheses to create a subexpression, which results in '(m|f)ood'.


Ordinary Characters (Scripting)

JScript
Ordinary Characters (Scripting)
CollapseAll image DropDown image

Ordinary characters consist of all printable and non-printable characters that are not explicitly designated as metacharacters. This includes all uppercase and lowercase alphabetic characters, all digits, all punctuation marks, and some symbols.

Expand image Examples of Regular Expressions

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:

CopyCode image Copy Code
/a/
/7/
/M/

The equivalent VBScript single-character regular expressions are:

CopyCode image Copy Code
"a"
"7"
"M"

You can combine a number of single characters 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'.

CopyCode image Copy Code
/a7M/

The equivalent VBScript expression is:

CopyCode image Copy Code
"a7M"

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


Special Characters (Scripting)

JScript
Special Characters (Scripting)
CollapseAll image DropDown image

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 (\).

Expand image Special Characters and Associated 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 character or subexpression zero or more times. To match the * character, use \*.
+ | Matches the preceding character or 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 these characters, use \[ and \].
? | Matches the preceding character or 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 "(".
/ | Denotes the start or end of a literal regular expression. To match the '/' character, use '\/'.
^ | 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 these characters, use \{ and \}.
| | Indicates a choice between two items. To match |, use \|.


Non-Printable Characters (Scripting)

JScript
Non-Printable Characters (Scripting)
CollapseAll image DropDown image

There are a number of useful non-printing characters that must be used occasionally.

Expand image Escape Sequences that Represent Non-printing Characters

Character | Meaning
\cx | 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.
\f | Matches a form-feed character. Equivalent to \x0c and \cL.
\n | Matches a newline character. Equivalent to \x0a and \cJ.
\r | Matches a carriage return character. Equivalent to \x0d and \cM.
\s | Matches any white space character including space, tab, form-feed, and so on. Equivalent to [\f\n\r\t\v].
\S | Matches any non-white space character. Equivalent to [^ \f\n\r\t\v].
\t | Matches a tab character. Equivalent to \x09 and \cI.
\v | Matches a vertical tab character. Equivalent to \x0b and \cK.


Character Matching (Scripting)

JScript
Character Matching (Scripting)
DropDown image

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':

Example

CopyCode image Copy Code
/a.c/

The equivalent VBScript regular expression is:

CopyCode image Copy Code
"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':

CopyCode image Copy Code
/filename\.ext/

For VBScript, the equivalent expression appears as follows:

CopyCode image Copy Code
"filename\.ext"

These expressions are still pretty limited. They only let you match any single character. Many times, it is 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, and so on, 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 is 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':

CopyCode image Copy Code
/Chapter [12345]/

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

CopyCode image Copy Code
"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.

CopyCode image Copy Code
/Chapter [1-5]/

The same expression for VBScript appears as follows:

CopyCode image Copy Code
"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:

    CopyCode image Copy Code
    [\-]

  • Put the hyphen character at the beginning or the end of the bracketed list. The following expressions matches all lowercase letters and the hyphen:

    CopyCode image Copy Code
    [-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:

    CopyCode image Copy Code
    [!--]
[!-~]

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':

CopyCode image Copy Code
/Chapter [^12345]/

For VBScript use:

CopyCode image Copy Code
"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:

CopyCode image Copy Code
/Chapter [^1-5]/

or for VBScript:

CopyCode image Copy Code
"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:

CopyCode image Copy Code
/[A-Za-z0-9]/

The equivalent expression for VBScript is:

CopyCode image Copy Code
"[A-Za-z0-9]"


Quantifiers in JScript 56

JScript
Quantifiers in JScript 56
CollapseAll image DropDown image

Sometimes, you do not 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.

Expand image Quantifiers and Associated Meanings

Character | Description
* | Matches the preceding character or subexpression zero or more times. For example, 'zo*' matches "z" and "zoo". * is equivalent to {0,}.
+ | Matches the preceding character or subexpression one or more times. For example, 'zo+' matches "zo" and "zoo", but not "z". + is equivalent to {1,}.
? | Matches the preceding character or subexpression zero or one time. For example, 'do(es)?' matches the "do" in "do" or "does". ? is equivalent to {0,1}
{n} | 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,} | 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*'.
{n,m} | 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:

CopyCode image Copy Code
/Chapter [1-9][0-9]*/

The following VBScript regular expression performs the identical match:

CopyCode image Copy Code
"Chapter [1-9][0-9]*"

Notice that the quantifier appears after the range expression. Therefore, it applies to the entire range expression which, 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.

CopyCode image Copy Code
/Chapter [0-9]{1,2}/

For VBScript, use the following regular expression:

CopyCode image Copy Code
"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. A better JScript expression for matching only two digits are the following:

CopyCode image Copy Code
/Chapter [1-9][0-9]?/

-or-

CopyCode image Copy Code
/Chapter [1-9][0-9]{0,1}/

For VBScript, the following expressions are equivalent:

CopyCode image Copy Code
"Chapter [1-9][0-9]?"

-or-

CopyCode image Copy Code
"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 is 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:

CopyCode image Copy Code
<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.

CopyCode image Copy Code
/<.*>/

The VBScript regular expression is:

CopyCode image Copy Code
"<.*>"

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

CopyCode image Copy Code
/<.*?>/

-or-

CopyCode image Copy Code
"<.*?>"

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


Anchors (Scripting)

JScript
Anchors (Scripting)
CollapseAll image DropDown image

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.

Expand image The Purpose of Anchors

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 | 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'.
\b | Matches a word boundary, that is, the position between a word and a space.
\B | 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. Do not confuse this use of the '^' with the use within a bracket expression.

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:

CopyCode image Copy Code
/^Chapter [1-9][0-9]{0,1}/

For VBScript the same regular expressions appears as:

CopyCode image Copy Code
"^Chapter [1-9][0-9]{0,1}"

Not only does a true chapter heading occur at the beginning of a line, it is also the only text on the line, so it also must be at the end of a line as well. The following expression ensures that the match 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.

CopyCode image Copy Code
/^Chapter [1-9][0-9]{0,1}$/

For VBScript use:

CopyCode image Copy Code
"^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 nonword 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:

CopyCode image Copy Code
/\bCha/

or for VBScript:

CopyCode image Copy Code
"\bCha"

The position of the '\b' operator is critical. If it is positioned at the beginning of a string to be matched, it looks for the match at the beginning of the word; if it is 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:

CopyCode image Copy Code
/ter\b/

and

CopyCode image Copy Code
"ter\b"

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

CopyCode image Copy Code
/\Bapt/

and

CopyCode image Copy Code
"\Bapt"

The string 'apt' occurs on a nonword boundary in the word 'Chapter' but on a word boundary in the word 'aptitude'. For the \B nonword boundary operator, position is not important because the match is not relative to the beginning or end of a word.


Alternation and Grouping (Scripting)

JScript
Alternation and Grouping (Scripting)
DropDown image

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 is 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:

Example

CopyCode image Copy Code
/^Chapter|Section [1-9][0-9]{0,1}$/
"^Chapter|Section [1-9][0-9]{0,1}$"

Unfortunately, the regular expressions shown above matches 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 is 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 also used to create subexpressions and possibly capture them for later use, something that is covered in the section on backreferences. 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:

CopyCode image Copy Code
/^(Chapter|Section) [1-9][0-9]{0,1}$/

For VBScript:

CopyCode image Copy Code
"^(Chapter|Section) [1-9][0-9]{0,1}$"

Although these expressions work properly, the parentheses around 'Chapter|Section' also cause either of the two matching words to be captured for future use. Since there is 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.

In the above example, you merely want to use the parentheses to group a choice between the words 'Chapter' and 'Section'. To prevent the match from being saved for possible later use, place '?:' before the regular expression pattern inside the parentheses. The following modification provides the same capability without saving the submatch:

CopyCode image Copy Code
/^(?:Chapter|Section) [1-9][0-9]{0,1}$/

For VBScript:

CopyCode image Copy Code
"^(?: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:

CopyCode image Copy Code
/Windows(?=95 |98 |NT )/

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

CopyCode image Copy Code
"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'.


Backreferences in JScript 56

JScript
Backreferences in JScript 56
CollapseAll image DropDown image

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 '?!'.

Expand image Storing Submatches

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:

CopyCode image Copy Code
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.

CopyCode image Copy Code
/\b([a-z]+) \1\b/gi

The equivalent VBScript expression is:

CopyCode image Copy Code
"\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. Otherwise, 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 is specified by the case insensitivity ('i') flag at the end of the expression. 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:

CopyCode image Copy Code
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:

CopyCode image Copy Code
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 would 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, and so on), the domain address, and the page/path:

CopyCode image Copy Code
http://msdn.microsoft.com:80/scripting/default.htm

The following regular expressions provide that functionality. For JScript:

CopyCode image Copy Code
/(\w+):\/\/([^/:]+)(:\d*)?([^# ]*)/

For VBScript:

CopyCode image Copy Code
"(\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"


JScript Language Reference

JScript
JScript Language Reference
DropDown image

These sections explain the elements that comprise the JScript language.

In This Section

Feature Information

Provides links to topics that explain the features of JScript.

Errors

Includes links to run-time and syntax errors.

Functions

Provides a list of functions with links to information about each function.

Methods

Provides a list of methods with links to information about each method.

Objects

Provides a list of objects with links to information about each object.

Operators

Provides a list of operators with links to information about each operator.

Properties

Provides a list of properties with links to information about each property.

Statements

Provides a list of statements with links to information about each statement.

Related Sections

JScript User's Guide

Provides information about how to use VBScript and how to construct and use regular expressions.


Feature Information (JScript 5.6)

JScript
Feature Information (JScript 5.6)
CollapseAll image DropDown image

The following table lists JScript features.

Expand image Features

Description | Language Element
List of JScript versions by host application and list of features by version. | Version Information
List of ECMA features currently in JScript. | JScript Features (ECMA)
List of non-ECMA features currently in JScript. | JScript Features (Non-ECMA)


Version Information (JScript 5.6)

JScript
Version Information (JScript 5.6)
DropDown image

The following table lists the version of Microsoft JScript implemented by host applications.

Versions

Host Application | 1.0 | 2.0 | 3.0 | 4.0 | 5.0 | 5.1 | 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 Visual Studio 6.0 |  |  |  | x |  |  |  |
Microsoft Internet Explorer 5.0 |  |  |  |  | x |  |  |
Microsoft Internet Explorer 5.01 |  |  |  |  |  | x |  |
Microsoft Windows 2000 |  |  |  |  |  | x |  |
Microsoft Internet Explorer 5.5 |  |  |  |  |  |  | x |
Microsoft Windows Millennium Edition |  |  |  |  |  |  | x |
Microsoft Internet Explorer 6.0 |  |  |  |  |  |  |  | x
Microsoft Windows XP |  |  |  |  |  |  |  | x

The following table lists JScript language features and the version when first introduced.

Language Element | 1.0 | 2.0 | 3.0 | 4.0 | 5.0 | 5.5
0n Property |  |  |  |  |  | x
$1...$9 Properties |  |  | x |  |  |
abs Method | x |  |  |  |  |
acos Method | x |  |  |  |  |
ActiveXObject Object |  |  | x |  |  |
Addition Assignment Operator (+=) | x |  |  |  |  |
Addition Operator (+) | x |  |  |  |  |
anchor Method | x |  |  |  |  |
apply Method |  |  |  |  |  | x
arguments Object | x |  |  |  |  |
arguments Property |  | x |  |  |  |
Array Object |  | x |  |  |  |
asin Method | x |  |  |  |  |
Assignment Operator (=) | x |  |  |  |  |
atan Method | x |  |  |  |  |
atan2 Method | x |  |  |  |  |
atEnd Method |  |  | x |  |  |
big Method | x |  |  |  |  |
Bitwise AND Assignment Operator (&=) | x |  |  |  |  |
Bitwise AND Operator (&) | x |  |  |  |  |
Bitwise Left Shift Operator (<<) | x |  |  |  |  |
Bitwise NOT Operator (~) | x |  |  |  |  |
Bitwise OR Assignment Operator (|=) | x |  |  |  |  |
Bitwise OR Operator (|) | x |  |  |  |  |
Bitwise Right Shift Operator (>>) | x |  |  |  |  |
Bitwise XOR Assignment Operator (^=) | x |  |  |  |  |
Bitwise XOR Operator (^) | x |  |  |  |  |
blink Method | x |  |  |  |  |
bold Method | x |  |  |  |  |
Boolean Object |  | x |  |  |  |
break Statement | x |  |  |  |  |
call Method |  |  |  |  |  | x
callee Property |  |  |  |  |  | x
caller Property |  | x |  |  |  |
catch Statement |  |  |  |  | x |
@cc_on Statement |  |  | x |  |  |
ceil Method | x |  |  |  |  |
charAt Method | x |  |  |  |  |
charCodeAt Method |  |  |  |  |  | x
Comma Operator (,) | x |  |  |  |  |
// (Single-line Comment Statement) | x |  |  |  |  |
/*..*/ (Multiline Comment Statement) | x |  |  |  |  |
Comparison Operators | x |  |  |  |  |
compile Method |  |  | x |  |  |
concat Method (Array) |  |  | x |  |  |
concat Method (String) |  |  | x |  |  |
Conditional Compilation |  |  | x |  |  |
Conditional Compilation Variables |  |  | x |  |  |
Conditional (Ternary) Operator (?:) | x |  |  |  |  |
constructor Property |  | x |  |  |  |
continue Statement | x |  |  |  |  |
cos Method | x |  |  |  |  |
Data Type Conversion |  |  | x |  |  |
Date Object | x |  |  |  |  |
Debug Object |  |  | x |  |  |
debugger Statement |  |  | x |  |  |
decodeURI Method |  |  |  |  |  | x
DecodeURIComponent Method |  |  |  |  |  | x
Decrement Operator (--) | x |  |  |  |  |
delete Operator |  |  | x |  |  |
description Property |  |  |  |  | x |
dimensions Method |  |  | x |  |  |
Division Assignment Operator (/=) | x |  |  |  |  |
Division Operator (/) | x |  |  |  |  |
do...while Statement |  |  | x |  |  |
E Property | x |  |  |  |  |
encodeURI Method |  |  |  |  |  | x
encodeURI Component Method |  |  |  |  |  | x
Enumerator Object |  |  | x |  |  |
Equality Operator (==) | x |  |  |  |  |
Error Object |  |  |  |  | x |
escape Method | x |  |  |  |  |
eval Method | x |  |  |  |  |
exec Method |  |  | x |  |  |
exp Method | x |  |  |  |  |
finally Statement |  |  |  |  | x |
fixed Method | x |  |  |  |  |
floor Method | x |  |  |  |  |
fontcolor Method | x |  |  |  |  |
fontsize Method | x |  |  |  |  |
for Statement | x |  |  |  |  |
for...in Statement |  |  |  |  | x |
fromCharCode Method |  |  | x |  |  |
Function Object |  | x |  |  |  |
function Statement | x |  |  |  |  |
getDate Method | x |  |  |  |  |
getDay Method | x |  |  |  |  |
getFullYear Method |  |  | x |  |  |
getHours Method | x |  |  |  |  |
getItem Method |  |  | x |  |  |
getMilliseconds Method |  |  | x |  |  |
getMinutes Method | x |  |  |  |  |
getMonth Method | x |  |  |  |  |
GetObject Function |  |  | x |  |  |
getSeconds Method | x |  |  |  |  |
getTime Method | x |  |  |  |  |
getTimezoneOffset Method | x |  |  |  |  |
getUTCDate Method |  |  | x |  |  |
getUTCDay Method |  |  | x |  |  |
getUTCFullYear Method |  |  | x |  |  |
getUTCHours Method |  |  | x |  |  |
getUTCMilliseconds Method |  |  | x |  |  |
getUTCMinutes Method |  |  | x |  |  |
getUTCMonth Method |  |  | x |  |  |
GetUTCSeconds Method |  |  | x |  |  |
getVarDate Method |  |  | x |  |  |
getYear Method | x |  |  |  |  |
Global Object |  |  | x |  |  |
global Property |  |  |  |  |  | x
Greater than Operator (>) | x |  |  |  |  |
Greater than or equal to Operator (>=) | x |  |  |  |  |
hasOwnProperty Method |  |  |  |  |  | x
Identity Operator (===) | x |  |  |  |  |
@if Statement |  |  | x |  |  |
if...else Statement | x |  |  |  |  |
ignoreCase Property |  |  |  |  |  | x
In Operator | x |  |  |  |  |
Increment Operator (++) | x |  |  |  |  |
index Property |  |  | x |  |  |
indexOf Method | x |  |  |  |  |
Inequality Operator (!=) | x |  |  |  |  |
Infinity Property |  |  | x |  |  |
input Property ($_) |  |  | x |  |  |
instanceof Operator |  |  |  |  | x |
isFinite Method |  |  | x |  |  |
isNaN Method | x |  |  |  |  |
IsPrototypeOf Method |  |  |  |  |  | x
italics Method | x |  |  |  |  |
item Method |  |  | x |  |  |
join Method |  | x |  |  |  |
Labeled Statement |  |  | x |  |  |
lastIndex Property |  |  | x |  |  |
lastIndexOf Method | x |  |  |  |  |
lastMatch Property ($&) |  |  |  |  |  | x
lastParen Property ($+) |  |  |  |  |  | x
lbound Method |  |  | x |  |  |
leftContext Property ($') |  |  |  |  |  | x
Left Shift Assignment Operator (<<=) | x |  |  |  |  |
length Property (Arguments) |  |  |  |  |  | x
length Property (Array) |  | x |  |  |  |
length Property (Function) |  | x |  |  |  |
length Property (String) | x |  |  |  |  |
Less than Operator (<) | x |  |  |  |  |
Less than or equal to Operator (<=) | x |  |  |  |  |
link Method | x |  |  |  |  |
LN2 Property | x |  |  |  |  |
LN10 Property | x |  |  |  |  |
localeCompare Method |  |  |  |  |  | x
log Method | x |  |  |  |  |
LOG2E Property | x |  |  |  |  |
LOG10E Property | x |  |  |  |  |
Logical AND Operator (&&) | x |  |  |  |  |
Logical NOT Operator (!) | x |  |  |  |  |
Logical OR Operator (||) | x |  |  |  |  |
match Method |  |  | x |  |  |
Math Object | x |  |  |  |  |
max Method | x |  |  |  |  |
MAX_VALUE Property |  | x |  |  |  |
message Property |  |  |  |  |  | x
min Method | x |  |  |  |  |
MIN_VALUE Property |  | x |  |  |  |
Modulus Assignment Operator (%=) | x |  |  |  |  |
Modulus Operator (%) | x |  |  |  |  |
moveFirst Method |  |  | x |  |  |
moveNext Method |  |  | x |  |  |
multiline Property |  |  |  |  |  | x
Multiplication Assignment Operator (*=) | x |  |  |  |  |
Multiplication Operator (*) | x |  |  |  |  |
name Property |  |  |  |  |  | x
NaN Property (Global) |  |  | x |  |  |
NaN Property (Number) |  | x |  |  |  |
NEGATIVE_INFINITY Property |  | x |  |  |  |
new Operator | x |  |  |  |  |
Nonidentity Operator (!==) | x |  |  |  |  |
Number Object |  | x |  |  |  |
number Property |  |  |  |  | x |
Object Object |  |  | x |  |  |
Operator Precedence | x |  |  |  |  |
parse Method | x |  |  |  |  |
parseFloat Method | x |  |  |  |  |
parseInt Method | x |  |  |  |  |
PI Property | x |  |  |  |  |
pop Method |  |  |  |  |  | x
POSITIVE_INFINITY Property |  | x |  |  |  |
pow Method | x |  |  |  |  |
prototype Property |  | x |  |  |  |
propertyIsEnumerable Property |  |  |  |  |  | x
push Method |  |  |  |  |  | x
random Method | x |  |  |  |  |
RegExp Object |  |  | x |  |  |
Regular Expression Object |  |  | x |  |  |
Regular Expression Syntax |  |  | x |  |  |
replace Method | x |  |  |  |  |
return Statement | x |  |  |  |  |
reverse Method |  | x |  |  |  |
rightContext Property ($') |  |  |  |  |  | x
Right Shift Assignment Operator (>>=) | x |  |  |  |  |
round Method | x |  |  |  |  |
ScriptEngine Function |  | x |  |  |  |
ScriptEngineBuildVersion Function |  | x |  |  |  |
ScriptEngineMajorVersion Function |  | x |  |  |  |
ScriptEngineMinorVersion Function |  | x |  |  |  |
search Method |  |  | x |  |  |
@set Statement |  |  | x |  |  |
setDate Method | x |  |  |  |  |
setFullYear Method |  |  | x |  |  |
setHours Method | x |  |  |  |  |
setMilliseconds Method |  |  | x |  |  |
setMinutes Method | x |  |  |  |  |
setMonth Method | x |  |  |  |  |
setSeconds Method | x |  |  |  |  |
setTime Method | x |  |  |  |  |
setUTCDate Method |  |  | x |  |  |
setUTCFullYear Method |  |  | x |  |  |
setUTCHours Method |  |  | x |  |  |
setUTCMilliseconds Method |  |  | x |  |  |
setUTCMinutes Method |  |  | x |  |  |
setUTCMonth Method |  |  | x |  |  |
setUTCSeconds Method |  |  | x |  |  |
setYear Method | x |  |  |  |  |
shift Method |  |  |  |  |  | x
sin Method | x |  |  |  |  |
slice Method (Array) |  |  | x |  |  |
slice Method (String) |  |  | x |  |  |
small Method | x |  |  |  |  |
sort Method |  | x |  |  |  |
source Property |  |  | x |  |  |
splice Method |  |  |  |  |  | x
split Method |  |  | x |  |  |
sqrt Method | x |  |  |  |  |
SQRT1_2 Property | x |  |  |  |  |
SQRT2 Property | x |  |  |  |  |
strike Method | x |  |  |  |  |
String Object | x |  |  |  |  |
sub Method | x |  |  |  |  |
substr Method |  |  | x |  |  |
substring Method | x |  |  |  |  |
Subtraction Assignment Operator (-=) | x |  |  |  |  |
Subtraction Operator (-) | x |  |  |  |  |
sup Method | x |  |  |  |  |
switch Statement |  |  | x |  |  |
tan Method | x |  |  |  |  |
test Method |  |  | x |  |  |
this Statement | x |  |  |  |  |
throw Statement |  |  |  |  | x |
toArray Method |  |  | x |  |  |
toDateString Method |  |  |  |  |  | x
toExponential Method |  |  |  |  |  | x
toFixed Method |  |  |  |  |  | x
toGMTString Method | x |  |  |  |  |
toLocaleDateString Method |  |  |  |  |  | x
toLocaleLowercase Method |  |  |  |  |  | x
toLocaleString Method | x |  |  |  |  |
toLocaleTimeString Method |  |  |  |  |  | x
toLocaleUppercase Method |  |  |  |  |  | x
toLowerCase Method | x |  |  |  |  |
toPrecision Method |  |  |  |  |  | x
toString Method |  | x |  |  |  |
toTimeString Method |  |  |  |  |  | x
toUpperCase Method | x |  |  |  |  |
toUTCString Method |  |  | x |  |  |
try Statement |  |  |  |  | x |
typeof Operator | x |  |  |  |  |
ubound Method |  |  | x |  |  |
Unary Negation Operator (-) | x |  |  |  |  |
undefined Property |  |  |  |  |  | x
unescape Method | x |  |  |  |  |
unshift Method |  |  |  |  |  | x
Unsigned Right Shift Assignment Operator (>>>=) | x |  |  |  |  |
Unsigned Right Shift Operator (>>>) | x |  |  |  |  |
UTC Method | x |  |  |  |  |
valueOf Method |  | x |  |  |  |
var Statement | x |  |  |  |  |
VBArray Object |  |  | x |  |  |
void Operator |  | x |  |  |  |
while Statement | x |  |  |  |  |
with Statement | x |  |  |  |  |
write Method |  |  | x |  |  |
writeln Method |  |  | x |  |  |


Microsoft JScript Features - ECMA (JScript 5.6)

JScript
Microsoft JScript Features - ECMA (JScript 5.6)
CollapseAll image DropDown image

The following table lists JScript features compliant with ECMA standards.

Expand image Features

Category Feature/Keyword

Array Handling

Array

join

length

reverse

sort

Assignments

Assign (=)

Compound Assign (OP=)

Booleans

Boolean

Comments

/*...*/ or //

Constants/Literals

NaN

null

true, false

Infinity

undefined

Control flow

Break

continue

for

for...in

if...else

return

while

Dates and Time

Date

getDate, getDay, getFullYear, getHours, getMilliseconds, getMinutes, getMonth, getSeconds, getTime, getTimezoneOffset, getYear

getUTCDate, getUTCDay, getUTCFullYear, getUTCHours, getUTCMilliseconds, getUTCMinutes, getUTCMonth, getUTCSeconds

setDate, setFullYear, setHours, setMilliseconds, setMinutes, setMonth, setSeconds, setTime, setYear, setUTCDate, setUTCFullYear, setUTCHours, setUTCMilliseconds, setUTCMinutes, setUTCMonth, setUTCSeconds

toGMTString, toLocaleString, toUTCString, parse, UTC

Declarations

Function

new

this

var

with

Function Creation

Function

arguments

length

Global Methods

Global

escape

unescape

eval

isFinite

isNaN

parseInt

parseFloat

Math

Math

abs, acos, asin, atan, atan2, ceil, cos, exp, floor, log, max, min, pow, random, round, sin, sqrt, tan, E, LN2, LN10, LOG2E, LOG10E, PI, SQRT1_2, SQRT2

Numbers

Number

MAX_VALUE, MIN_VALUE

NaN

NEGATIVE_INFINITY, POSITIVE_INFINITY

Object Creation

Object

new

constructor, prototype, instanceof, toString, valueOf

Operators

Addition (+), Subtraction (-)

Modulus arithmetic (%)

Multiplication (*), Division (/)

Negation (-)

Equality (==), Inequality (!=)

Less Than (<), Less Than or Equal To (<=)

Greater Than (>), Greater Than or Equal To (>=)

Logical And(&&), Or (||), Not (!)

Bitwise And (&), Or (|), Not (~), Xor (^)

Bitwise Left Shift (<<), Shift Right (>>)

Unsigned Shift Right (>>>)

Conditional (?:)

Comma (,)

delete, typeof, void

Decrement (--), Increment (++)

Objects

Array

Boolean

Date

Function

Global

Math

Number

Object

String

Strings

String

charAt, charCodeAt, fromCharCode

indexOf, lastIndexOf

split

toLowerCase, toUpperCase

length


Microsoft JScript Features - Non-ECMA (JScript 5.6)

JScript
Microsoft JScript Features - Non-ECMA (JScript 5.6)
CollapseAll image DropDown image

The following table lists JScript features that are not compliant with ECMA standards.

Expand image Features

Category | Feature/Keyword
Array Handling | concat, slice VBArray dimensions, getItem, lbound, toArray, ubound
Conditional Compilation | @cc_on @if Statement @set Statement Conditional Compilation Variables
Control flow | do...while Labeled switch
Dates and Time | getVarDate
Enumeration | Enumerator atEnd, item, moveFirst, moveNext
Error Handling | Error description, number throw, try...catch
Function Creation | caller
Operators | Identity (===), Nonidentity (!==)
Objects | Enumerator RegExp Regular Expression VBArray ActiveXObject GetObject
Regular Expressions and Pattern Matching | RegExp index, input, lastIndex, $1...$9, source, compile, exec, test Regular Expression Syntax
Script Engine Identification | ScriptEngine ScriptEngineBuildVersion ScriptEngineMajorVersion ScriptEngineMinorVersion
Strings | concat, slice match, replace, search anchor, big, blink, bold, fixed, fontcolor, fontsize, italics, link, small, strike, sub, sup


JScript Errors

JScript
JScript Errors
CollapseAll image DropDown image

The following table lists the types of JScript errors.

Expand image Error Types

For more information about | See
List of JScript run-time errors | Run-time Errors
List of JScript syntax errors | Syntax Errors


JScript Run-time Errors (JScript 5.6)

JScript
JScript Run-time Errors (JScript 5.6)
See Also
CollapseAll image DropDown image

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

Expand image Errors

Error Number | Description
5029 | Array length must be a finite positive integer
5030 | Array length must be assigned a finite positive number
5028 | Array or arguments object expected
5010 | Boolean expected
5003 | Cannot assign to a function result
5000 | Cannot assign to 'this'
5006 | Date object expected
5015 | Enumerator object expected
5022 | Exception thrown and not caught
5020 | Expected ')' in regular expression
5019 | Expected ']' in regular expression
5023 | Function does not have a valid prototype object
5002 | Function expected
5008 | Illegal assignment
5021 | Invalid range in character set
5014 | JScript object expected
5001 | Number expected
5007 | Object expected
5012 | Object member expected
5016 | Regular Expression object expected
5005 | String expected
5017 | Syntax error in regular expression
5026 | The number of fractional digits is out of range
5027 | The precision is out of range
5025 | The URI to be decoded is not a valid encoding
5024 | The URI to be encoded contains an invalid character
5009 | Undefined identifier
5018 | Unexpected quantifier
5013 | VBArray expected

Expand image See Also

Reference

JScript Syntax Errors (JScript 5.6)


JScript Syntax Errors (JScript 5.6)

JScript
JScript Syntax Errors (JScript 5.6)
See Also
CollapseAll image DropDown image

JScript syntax errors are errors that result when the structure of one of your JScript statements violates one or more of the grammatical rules of the JScript scripting language. JScript syntax errors occur during the program compilation stage, before the program has begun to be executed.

Expand image Errors

Error Number | Description
1019 | Can't have 'break' outside of loop
1020 | Can't have 'continue' outside of loop
1030 | Conditional compilation is turned off
1027 | 'default' can only appear once in a 'switch' statement
1005 | Expected '('
1006 | Expected ')'
1012 | Expected '/'
1003 | Expected ':'
1004 | Expected ';'
1032 | Expected '@'
1029 | Expected '@end'
1007 | Expected ']'
1008 | Expected '{'
1009 | Expected '}'
1011 | Expected '='
1033 | Expected 'catch'
1031 | Expected constant
1023 | Expected hexadecimal digit
1010 | Expected identifier
1028 | Expected identifier, string or number
1024 | Expected 'while'
1014 | Invalid character
1026 | Label not found
1025 | Label redefined
1018 | 'return' statement outside of function
1002 | Syntax error
1035 | Throw must be followed by an expression on the same source line
1016 | Unterminated comment
1015 | Unterminated string constant

Expand image See Also

Reference

JScript Run-time Errors (JScript 5.6)


JScript Functions (JScript 5.6)

JScript
JScript Functions (JScript 5.6)
CollapseAll image DropDown image

The following table lists JScript functions.

Expand image Functions

Description | Language Element
Returns a reference to an Automation object from a file. | GetObject Function
Returns a string representing the scripting language in use. | ScriptEngine Function
Returns the build version number of the scripting engine in use. | ScriptEngineBuildVersion Function
Returns the major version number of the scripting engine in use. | ScriptEngineMajorVersion Function
Returns the minor version number of the scripting engine in use. | ScriptEngineMinorVersion Function


GetObject Function (JScript 5.6)

JScript
GetObject Function (JScript 5.6)
See Also
CollapseAll image DropDown image

Returns a reference to an Automation object from a file.

GetObject([pathname] [, class])

Expand image Arguments

pathname

Optional. Full path and name of the file containing the object to retrieve. If pathname is omitted, class is required.

class

Optional. Class of the object.

The class argument uses the syntax appname.objectype and has these parts:

appname

Required. Name of the application providing the object.

objectype

Required. Type or class of object to create.

Expand image Remarks

Use the GetObject function to access an Automation object from a file. Assign the object returned by GetObject to the object variable. For example:

CopyCode image Copy Code
var CADObject;
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. To do so, 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:

CopyCode image Copy Code
var LayerObject = GetObject("C:\\CAD\\SCHEMA.CAD!Layer3");

If you do not specify the object's class, Automation determines which application to start and which 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:

CopyCode image Copy Code
var MyObject;
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:

CopyCode image Copy Code
MyObject.Line(9, 90);
MyObject.InsertText(9, 100, "Hello, world.");
MyObject.SaveAs("C:\\DRAWINGS\\SAMPLE.DRW");
Note 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 ActiveXObject object.

If an object has registered itself as a single-instance object, only one instance of the object is created, no matter how many times ActiveXObject 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.

Expand image Requirements

Version 5

Expand image See Also

Reference

ActiveXObject Object (JScript 5.6)


ScriptEngine Function (JScript 5.6)

JScript
ScriptEngine Function (JScript 5.6)
See Also Example
CollapseAll image DropDown image

Returns a string representing the scripting language in use.

ScriptEngine( )

Expand image Remarks

The ScriptEngine function can return any of the following strings:

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

Expand image Example

The following example illustrates the use of the ScriptEngine function:

CopyCode image Copy Code
function GetScriptEngineInfo(){
   var s;
   s = ""; // Build string with necessary info.
   s += ScriptEngine() + " Version ";
   s += ScriptEngineMajorVersion() + ".";
   s += ScriptEngineMinorVersion() + ".";
   s += ScriptEngineBuildVersion();
   return(s);
}

Expand image Requirements

Version 5

Expand image See Also

Reference

ScriptEngineBuildVersion Function (JScript 5.6)
ScriptEngineMajorVersion Function (JScript 5.6)
ScriptEngineMinorVersion Function (JScript 5.6)


ScriptEngineBuildVersion Function (JScript 5.6)

JScript
ScriptEngineBuildVersion Function (JScript 5.6)
See Also Example
CollapseAll image DropDown image

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

ScriptEngineBuildVersion( )

Expand image Remarks

The return value corresponds directly to the version information contained in the dynamic-link library (DLL) for the scripting language in use.

Expand image Example

The following example illustrates the use of the ScriptEngineBuildVersion function:

CopyCode image Copy Code
function GetScriptEngineInfo(){
   var s;
   s = ""; // Build string with necessary info.
   s += ScriptEngine() + " Version ";
   s += ScriptEngineMajorVersion() + ".";
   s += ScriptEngineMinorVersion() + ".";
   s += ScriptEngineBuildVersion();
   return(s);
}

Expand image Requirements

Version 5

Expand image See Also

Reference

ScriptEngine Function (JScript 5.6)
ScriptEngineMajorVersion Function (JScript 5.6)
ScriptEngineMinorVersion Function (JScript 5.6)


ScriptEngineMajorVersion Function (JScript 5.6)

JScript
ScriptEngineMajorVersion Function (JScript 5.6)
See Also Example
CollapseAll image DropDown image

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

ScriptEngineMajorVersion( )

Expand image Remarks

The return value corresponds directly to the version information contained in the dynamic-link library (DLL) for the scripting language in use.

Expand image Example

The following example illustrates the use of the ScriptEngineMajorVersion function:

CopyCode image Copy Code
function GetScriptEngineInfo(){
   var s;
   s = ""; // Build string with necessary info.
   s += ScriptEngine() + " Version ";
   s += ScriptEngineMajorVersion() + ".";
   s += ScriptEngineMinorVersion() + ".";
   s += ScriptEngineBuildVersion();
   return(s);
}

Expand image Requirements

Version 5

Expand image See Also

Reference

ScriptEngine Function (JScript 5.6)
ScriptEngineBuildVersion Function (JScript 5.6)
ScriptEngineMinorVersion Function (JScript 5.6)


ScriptEngineMinorVersion Function (JScript 5.6)

JScript
ScriptEngineMinorVersion Function (JScript 5.6)
See Also Example
CollapseAll image DropDown image

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

ScriptEngineMinorVersion( )

Expand image Remarks

The return value corresponds directly to the version information contained in the dynamic-link library (DLL) for the scripting language in use.

Expand image Example

The following example illustrates the use of the ScriptEngineMinorVersion function.

CopyCode image Copy Code
function GetScriptEngineInfo(){
   var s;
   s = ""; // Build string with necessary info.
   s += ScriptEngine() + " Version ";
   s += ScriptEngineMajorVersion() + ".";
   s += ScriptEngineMinorVersion() + ".";
   s += ScriptEngineBuildVersion();
   return(s);
}

Expand image Requirements

Version 5

Expand image See Also

Reference

ScriptEngine Function (JScript 5.6)
ScriptEngineBuildVersion Function (JScript 5.6)
ScriptEngineMajorVersion Function (JScript 5.6)


JScript Methods

JScript
JScript Methods
CollapseAll image DropDown image

The following table lists JScript Methods.

Expand image Methods

Description | Language Element
Returns the absolute value of a number. | abs Method
Returns the arccosine of a number. | acos Method
Places an HTML anchor with a NAME attribute around specified text in the object. | anchor Method
Applies a method of an object, substituting another object for the current object. | apply Method
Returns the arcsine of a number. | asin Method
Returns the arctangent of a number. | atan Method
Returns the angle (in radians) from the X axis to a point (y,x). | atan2 Method
Returns a Boolean value indicating if the enumerator is at the end of the collection. | atEnd Method
Places HTML <BIG> tags around text in a String object. | big Method
Places HTML <BLINK> tags around text in a String object. | blink Method
Places HTML <B> tags around text in a String object. | bold Method
Calls a method of an object, substituting another object for the current object. | call Method
Returns the smallest integer greater than or equal to its numeric argument. | ceil Method
Returns the character at the specified index. | charAt Method
Returns the Unicode encoding of the specified character. | charCodeAt Method
Compiles a regular expression into an internal format. | compile Method
Returns a new array consisting of a combination of two arrays. | concat Method (Array)
Returns a String object containing the concatenation of two supplied strings. | concat Method (String)
Returns the cosine of a number. | cos Method
Returns the unencoded version of an encoded Uniform Resource Identifier. | decodeURI Method
Returns the unencoded version of an encoded component of a Uniform Resource Identifier. | decodeURIComponent Method
Returns the number of dimensions in a VBArray. | dimensions Method
Encodes a text string as a valid Uniform Resource Identifier. | encodeURI Method
Encodes a text string as a valid component of a Uniform Resource Identifier. | encodeURIComponent Method
Encodes String objects so they can be read on all computers. | escape Method
Evaluates JScript code and executes it. | eval Method
Executes a search for a match in a specified string. | exec Method
Returns e (the base of natural logarithms) raised to a power. | exp Method
Places HTML <TT> tags around text in a String object. | fixed Method
Returns the greatest integer less than or equal to its numeric argument. | floor Method
Places an HTML <FONT> tag with the COLOR attribute around the text in a String object. | fontcolor Method
Places an HTML <FONT> tag with the SIZE attribute around the text in a String object. | fontsize Method
Returns a string from a number of Unicode character values. | fromCharCode Method
Returns the day of the month value in a Date object using local time. | getDate Method
Returns the day of the week value in a Date object using local time. | getDay Method
Returns the year value in the Date object using local time. | getFullYear Method
Returns the hours value in a Date object using local time. | getHours Method
Returns the item at the specified location. | getItem Method
Returns the milliseconds value in a Date object using local time. | getMilliseconds Method
Returns the minutes value stored in a Date object using local time. | getMinutes Method
Returns the month value in the Date object using local time. | getMonth Method
Returns seconds value stored in a Date object using local time. | getSeconds Method
Returns the time value in a Date object. | getTime Method
Returns the difference in minutes between the time on the host computer and Universal Coordinated Time (UTC). | getTimezoneOffset Method
Returns the date value in a Date object using Universal Coordinated Time (UTC). | getUTCDate Method
Returns the day of the week value in a Date object using Universal Coordinated Time (UTC). | getUTCDay Method
Returns the year value in a Date object using Universal Coordinated Time (UTC). | getUTCFullYear Method
Returns the hours value in a Date object using Universal Coordinated Time (UTC). | getUTCHours Method
Returns the milliseconds value in a Date object using Universal Coordinated Time (UTC). | getUTCMilliseconds Method
Returns the minutes value in a Date object using Universal Coordinated Time (UTC). | getUTCMinutes Method
Returns the month value in a Date object using Universal Coordinated Time (UTC). | getUTCMonth Method
Returns the seconds value in a Date object using Universal Coordinated Time (UTC). | getUTCSeconds Method
Returns the VT_DATE value in a Date object. | getVarDate Method
Returns the year value in a Date object. | getYear Method
Returns a Boolean value indicating whether an object has a property with the specified name. | hasOwnProperty Method
Returns the character position where the first occurrence of a substring occurs within a String object. | indexOf Method
Returns a Boolean value that indicates if a supplied number is finite. | isFinite Method
Returns a Boolean value that indicates whether a value is the reserved value NaN (not a number). | isNaN Method
Returns a Boolean value indicating whether an object exists in another object's prototype chain. | isPrototypeOf Method
Places HTML <I> tags around text in a String object. | italics Method
Returns the current item in the collection. | item Method
Returns a String object consisting of all the elements of an array concatenated together. | join Method
Returns the last occurrence of a substring within a String object. | lastIndexOf Method
Returns the lowest index value used in the specified dimension of a VBArray. | lbound Method
Places an HTML anchor with an HREF attribute around the text in a String object. | link Method
Returns a value indicating whether two strings are equivalent in the current locale. | localeCompare Method
Returns the natural logarithm of a number. | log Method
Returns, as an array, the results of a search on a string using a supplied Regular Expression object. | match Method
Returns the greater of two supplied numeric expressions. | max Method
Returns the lesser of two supplied numbers. | min Method
Resets the current item in the collection to the first item. | moveFirst Method
Moves the current item to the next item in the collection. | moveNext Method
Parses a string containing a date, and returns the number of milliseconds between that date and midnight, January 1, 1970. | parse Method
Returns a floating-point number converted from a string. | parseFloat Method
Returns an integer converted from a string. | parseInt Method
Removes the last element from an array and returns it. | pop Method
Returns the value of a base expression raised to a specified power. | pow Method
Appends new elements to an array, and returns the new length of the array. | push Method
Returns a pseudorandom number between 0 and 1. | random Method
Returns a copy of a string with text replaced using a regular expression. | replace Method
Returns an Array object with the elements reversed. | reverse Method
Returns a specified numeric expression rounded to the nearest integer. | round Method
Returns the position of the first substring match in a regular expression search. | search Method
Sets the numeric date of the Date object using local time. | setDate Method
Sets the year value in the Date object using local time. | setFullYear Method
Sets the hour value in the Date object using local time. | setHours Method
Sets the milliseconds value in the Date object using local time. | setMilliseconds Method
Sets the minutes value in the Date object using local time. | setMinutes Method
Sets the month value in the Date object using local time. | setMonth Method
Sets the seconds value in the Date object using local time. | setSeconds Method
Sets the date and time value in the Date object. | setTime Method
Sets the numeric date in the Date object using Universal Coordinated Time (UTC). | setUTCDate Method
Sets the year value in the Date object using Universal Coordinated Time (UTC). | setUTCFullYear Method
Sets the hours value in the Date object using Universal Coordinated Time (UTC). | setUTCHours Method
Sets the milliseconds value in the Date object using Universal Coordinated Time (UTC). | setUTCMilliseconds Method
Sets the minutes value in the Date object using Universal Coordinated Time (UTC). | setUTCMinutes Method
Sets the month value in the Date object using Universal Coordinated Time (UTC). | setUTCMonth Method
Sets the seconds value in the Date object using Universal Coordinated Time (UTC). | setUTCSeconds Method
Sets the year value in the Date object. | setYear Method
Removes the first element from an array and returns it. | shift Method
Returns the sine of a number. | sin Method
Returns a section of an array. | slice Method (Array)
Returns a section of a string. | slice Method (String)
Places HTML <SMALL> tags around text in a String object. | small Method
Returns an Array object with the elements sorted. | sort Method
Removes elements from an array and, if necessary, inserts new elements in their place, returning the deleted elements. | splice Method
Returns the array of strings that results when a string is separated into substrings. | split Method
Returns the square root of a number. | sqrt Method
Places HTML <STRIKE> tags around text in a String object. | strike Method
Places HTML <SUB> tags around text in a String object. | sub Method
Returns a substring beginning at a specified location and having a specified length. | substr Method
Returns the substring at a specified location within a String object. | substring Method
Places HTML <SUP> tags around text in a String object. | sup Method
Returns the tangent of a number. | tan Method
Returns a Boolean value that indicates whether or not a pattern exists in a searched string. | test Method
Returns a standard JScript array converted from a VBArray. | toArray Method
Returns a date as a string value. | toDateString Method
Returns a string containing a number represented in exponential notation. | toExponential Method
Returns a string representing a number in fixed-point notation. | toFixed Method
Returns a date converted to a string using Greenwich Mean Time (GMT). | toGMTString Method
Returns a date as a string value appropriate to the host environment's current locale. | toLocaleDateString Method
Returns a string where all alphabetic characters have been converted to lowercase, taking into account the host environment's current locale. | toLocaleLowerCase Method
Returns a date converted to a string using the current locale. | toLocaleString Method
Returns a time as a string value appropriate to the host environment's current locale. | toLocaleTimeString Method
Returns a string where all alphabetic characters have been converted to uppercase, taking into account the host environment's current locale. | toLocaleUpperCase Method
Returns a string where all alphabetic characters have been converted to lowercase. | toLowerCase Method
Returns a string containing a number represented either in exponential or fixed-point notation with a specified number of digits. | toPrecision Method
Returns a string representation of an object. | toString Method
Returns a time as a string value. | toTimeString Method
Returns a string where all alphabetic characters have been converted to uppercase. | toUpperCase Method
Returns a date converted to a string using Universal Coordinated Time (UTC). | toUTCString Method
Returns the highest index value used in the specified dimension of the VBArray. | ubound Method
Decodes String objects encoded with the escape method. | unescape Method
Returns an array with specified elements inserted at the beginning. | unshift Method
Returns the number of milliseconds between midnight, January 1, 1970 Universal Coordinated Time (UTC) (or GMT) and the supplied date. | UTC Method
Returns the primitive value of the specified object. | valueOf Method
Sends strings to the script debugger. | write Method
Sends strings to the script debugger, followed with a newline character. | writeln Method


abs Method (JScript 5.6)

JScript
abs Method (JScript 5.6)
See Also Example
CollapseAll image DropDown image

Returns the absolute value of a number.

Math.abs(number)

Expand image Remarks

The required number argument is a numeric expression for which the absolute value is needed.

The return value is the absolute value of the number argument.

Expand image Example

The following example illustrates the use of the abs method.

CopyCode image Copy Code
function ComparePosNegVal(n)
{
   var s;
   var v1 = Math.abs(n);
   var v2 = Math.abs(-n);
   if (v1 == v2)
      s = "The absolute values of " + n + " and "
      s += -n + " are identical.";
   return(s);
}

Expand image Requirements

Version 1

Applies To: Math Object (JScript 5.6)

Expand image See Also

Reference

Math Object (JScript 5.6)


acos Method (JScript 5.6)

JScript
acos Method (JScript 5.6)
See Also
CollapseAll image DropDown image

Returns the arccosine of a number.

Math.acos(number)

Expand image Remarks

The required number argument is a numeric expression for which the arccosine is needed.

The return value is the arccosine of the number argument.

Applies To: Math Object (JScript 5.6)

Expand image Requirements

Version 1

Expand image See Also

Reference

asin Method (JScript 5.6)
atan Method (JScript 5.6)
cos Method (JScript 5.6)
sin Method (JScript 5.6)
tan Method (JScript 5.6)
Math Object (JScript 5.6)


anchor Method (JScript 5.6)

JScript
anchor Method (JScript 5.6)
See Also
CollapseAll image DropDown image

Places an HTML anchor with a NAME attribute around specified text in the object.

strVariable.anchor(anchorString)

Expand image Arguments

strVariable

Required. Any String object or literal.

anchorString

Required. Text you want to place in the NAME attribute of an HTML anchor.

Expand image Remarks

Call the anchor method to create a named anchor out of a String object. The following example demonstrates how the anchor method accomplishes this:

CopyCode image Copy Code
var strVariable = "This is an anchor";
strVariable = strVariable.anchor("Anchor1");

The value of strVariable after the last statement is:

CopyCode image Copy Code
<A NAME="Anchor1">This is an anchor</A>

No checking is done to see if the tag has already been applied to the string.

Applies To: String Object (JScript 5.6)

Expand image Requirements

Version 1

Expand image See Also

Reference

link Method (JScript 5.6)
String Object (JScript 5.6)


apply Method (JScript 5.6)

JScript
apply Method (JScript 5.6)
See Also
CollapseAll image DropDown image

Applies a method of an object, substituting another object for the current object.

apply([thisObj[,argArray]])

Expand image Arguments

thisObj

Optional. The object to be used as the current object.

argArray

Optional. Array of arguments to be passed to the function.

Expand image Remarks

If argArray is not a valid array or is not the arguments object, then a TypeError results.

If neither argArray nor thisObj are supplied, the global object is used as thisObj and is passed no arguments.

Applies To: Function Object (JScript 5.6)

Expand image Requirements

Version 5.5

Expand image See Also

Reference

Function Object (JScript 5.6)


asin Method (JScript 5.6)

JScript
asin Method (JScript 5.6)
See Also
CollapseAll image DropDown image

Returns the arcsine of a number.

Math.asin(number)

Expand image Remarks

The required number argument is a numeric expression for which the arcsine is needed.

The return value is the arcsine of its numeric argument.

Applies To: Math Object (JScript 5.6)

Expand image Requirements

Version 1

Expand image See Also

Reference

acos Method (JScript 5.6)
atan Method (JScript 5.6)
cos Method (JScript 5.6)
sin Method (JScript 5.6)
tan Method (JScript 5.6)
Math Object (JScript 5.6)


atan Method (JScript 5.6)

JScript
atan Method (JScript 5.6)
See Also
CollapseAll image DropDown image

Returns the arctangent of a number.

Math.atan(number)

Expand image Remarks

The required number argument is a numeric expression for which the arctangent is needed.

The return value is the arctangent of its numeric argument.

Applies To: Math Object (JScript 5.6)

Expand image Requirements

Version 1

Expand image See Also

Reference

acos Method (JScript 5.6)
asin Method (JScript 5.6)
atan2 Method (JScript 5.6)
cos Method (JScript 5.6)
sin Method (JScript 5.6)
tan Method (JScript 5.6)
Math Object (JScript 5.6)


atan2 Method (JScript 5.6)

JScript
atan2 Method (JScript 5.6)
See Also
CollapseAll image DropDown image

Returns the angle (in radians) from the X axis to a point (y,x).

Math.atan2(y, x)

Expand image Arguments

x

Required. A numeric expression representing the cartesian x-coordinate.

y

Required. A numeric expression representing the cartesian y-coordinate.

Expand image Remarks

The return value is between -pi and pi, representing the angle of the supplied (y,x) point.

Applies To: Math Object (JScript 5.6)

Expand image Requirements

Version 1

Expand image See Also

Reference

atan Method (JScript 5.6)
tan Method (JScript 5.6)
Math Object (JScript 5.6)


atEnd Method (JScript 5.6)

JScript
atEnd Method (JScript 5.6)
See Also Example
CollapseAll image DropDown image

Returns a Boolean value indicating if the enumerator is at the end of the collection.

myEnum.atEnd()

Expand image Remarks

The required myEnum reference is any Enumerator object.

The atEnd method returns true if the current item is the last one in the collection, the collection is empty, or the current item is undefined. Otherwise, it returns false.

Expand image Example

In following code, the atEnd method is used to determine if the end of a list of drives has been reached:

CopyCode image Copy Code
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);
}

Expand image Requirements

Version 2

Applies To: Enumerator Object (JScript 5.6)

Expand image See Also

Reference

item Method (JScript 5.6)
moveFirst Method (JScript 5.6)
moveNext Method (JScript 5.6)
Enumerator Object (JScript 5.6)


big Method (JScript 5.6)

JScript
big Method (JScript 5.6)
See Also
CollapseAll image DropDown image

Places HTML <BIG> tags around text in a String object.

strVariable.big( )

Expand image Remarks

The required strVariable reference is any String object or literal.

The example that follows shows how the big method works:

CopyCode image Copy Code
var strVariable = "This is a string object";
strVariable = strVariable.big( );

The value of strVariable after the last statement is:

CopyCode image Copy Code
<BIG>This is a string object</BIG>

No checking is done to see if the tag has already been applied to the string.

Applies To: String Object (JScript 5.6)

Expand image Requirements

Version 1

Expand image See Also

Reference

small Method (JScript 5.6)
String Object (JScript 5.6)


blink Method (JScript 5.6)

JScript
blink Method (JScript 5.6)
See Also
CollapseAll image DropDown image

Places HTML <BLINK> tags around text in a String object.

strVariable.blink( )

Expand image Remarks

The required strVariable reference is any String object or literal.

The following example demonstrates how the blink method works:

CopyCode image Copy Code
var strVariable = "This is a string object";
strVariable = strVariable.blink( );

The value of strVariable after the last statement is:

CopyCode image Copy Code
<BLINK>This is a string object</BLINK>

No checking is done to see if the tag has already been applied to the string.

The <BLINK> tag is not supported in Microsoft Internet Explorer.

Applies To: String Object (JScript 5.6)

Expand image Requirements

Version 1

Expand image See Also

Reference

String Object (JScript 5.6)


bold Method (JScript 5.6)

JScript
bold Method (JScript 5.6)
See Also
CollapseAll image DropDown image

Places HTML <B> tags around text in a String object.

strVariable.bold()

Expand image Remarks

The required strVariable reference is any String object or literal.

The following example demonstrates how the bold method works:

CopyCode image Copy Code
var strVariable = "This is a string object";
strVariable = strVariable.bold( );

The value of strVariable after the last statement is:

CopyCode image Copy Code
<B>This is a string object</B>

No checking is done to see if the tag has already been applied to the string.

Applies To: String Object (JScript 5.6)

Expand image Requirements

Version 1

Expand image See Also

Reference

italics Method (JScript 5.6)
String Object (JScript 5.6)


call Method (JScript 5.6)

JScript
call Method (JScript 5.6)
See Also
CollapseAll image DropDown image

Calls a method of an object, substituting another object for the current object.

call([thisObj[, arg1[, arg2[,  [, argN]]]]])

Expand image Arguments

thisObj

Optional. The object to be used as the current object.

arg1, arg2, , argN

Optional. List of arguments to be passed to the method.

Expand image Remarks

The call method is used to call a method on behalf of another object. The call method allows you to change the object context of a function from the original context to the new object specified by thisObj.

If thisObj is not supplied, the global object is used as thisObj.

Applies To: Function Object (JScript 5.6)

Expand image Requirements

Version 5.5

Expand image See Also

Reference

Function Object (JScript 5.6)


ceil Method (JScript 5.6)

JScript
ceil Method (JScript 5.6)
See Also
CollapseAll image DropDown image

Returns the smallest integer greater than or equal to its numeric argument.

Math.ceil(number)

Expand image Remarks

The required number argument is a numeric expression.

The return value is an integer value equal to the smallest integer greater than or equal to its numeric argument.

Applies To: Math Object (JScript 5.6)

Expand image Requirements

Version 1

Expand image See Also

Reference

floor Method (JScript 5.6)
Math Object (JScript 5.6)


charAt Method (JScript 5.6)

JScript
charAt Method (JScript 5.6)
See Also Example
CollapseAll image DropDown image

Returns the character at the specified index.

strObj.charAt(index)

Expand image Arguments

strObj

Required. Any String object or literal.

index

Required. Zero-based index of the desired character. Valid values are between 0 and the length of the string minus 1.

Expand image Remarks

The charAt method returns a character value equal to the character at the specified index. The first character in a string is at index 0, the second is at index 1, and so forth. Values of index out of valid range return an empty string.

Expand image Example

The following example illustrates the use of the charAt method:
CopyCode image Copy Code
function charAtTest(n){
   var str = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"; // Initialize variable.
   var s;                                  // Declare variable.
   s = str.charAt(n - 1);                  // Get correct character
                                           // from position n – 1.
   return(s);                              // Return character.
}

Expand image Requirements

Version 1

Applies To: String Object (JScript 5.6)

Expand image See Also

Reference

String Object (JScript 5.6)


charCodeAt Method (JScript 5.6)

JScript
charCodeAt Method (JScript 5.6)
See Also Example
CollapseAll image DropDown image

Returns an integer representing the Unicode encoding of the character at the specified location.

strObj.charCodeAt(index)

Expand image Arguments

strObj

Required. Any String object or literal.

index

Required. Zero-based index of the desired character. Valid values are between 0 and the length of the string minus 1.

Expand image Remarks

The first character in a string is at index 0, the second is at index 1, and so forth.

If there is no character at the specified index, NaN is returned.

Expand image Example

The following example illustrates the use of the charCodeAt method.

CopyCode image Copy Code
function charCodeAtTest(n){
  var str = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"; //Initialize variable.
   return str.charCodeAt(n - 1);  //Return Unicode value of the character.
}

Expand image Requirements

Version 5.5

Applies To: String Object (JScript 5.6)

Expand image See Also

Reference

fromCharCode Method (JScript 5.6)


compile Method (JScript 5.6)

JScript
compile Method (JScript 5.6)
See Also Example
CollapseAll image DropDown image

Compiles a regular expression into an internal format for faster execution.

rgExp.compile(pattern, [flags])

Expand image Arguments

rgExp

Required. An instance of a Regular Expression object. Can be a variable name or a literal.

pattern

Required. A string expression containing a regular expression pattern to be compiled

flags

Optional. Available flags, which may be combined, are:

  • g (global search for all occurrences of pattern)

  • i (ignore case)

  • m (multiline search)

Expand image Remarks

The compile method converts pattern into an internal format for faster execution. This allows for more efficient use of regular expressions in loops, for example. A compiled regular expression speeds things up when reusing the same expression repeatedly. No advantage is gained, however, if the regular expression changes.

Expand image Example

The following example illustrates the use of the compile method:

CopyCode image Copy Code
function CompileDemo(){
   var rs;
   var s = "AaBbCcDdEeFfGgHhIiJjKkLlMmNnOoPp"
   // Create regular expression for uppercase only.
   var r = new RegExp("[A-Z]", "g");
   var a1 = s.match(r)              // Find matches.
   // Compile the regular expression for lowercase only.
   r.compile("[a-z]", "g");
   var a2 = s.match(r)              // Find matches.
   return(a1 + "\n" + a2;
}

Expand image Requirements

Version 3

Applies To: Regular Expression Object (JScript 5.6)

Expand image See Also

Reference

Regular Expression Syntax (Scripting)


concat Method (Array) (JScript 5.6)

JScript
concat Method (Array) (JScript 5.6)
See Also Example
CollapseAll image DropDown image

Returns a new array consisting of a combination of two or more arrays.

array1.concat([item1[, item2[, . . . [, itemN]]]])

Expand image Arguments

array1

Required. The Array object to which all other arrays are concatenated.

item1,. . ., itemN

Optional. Additional items to add to the end of array1.

Expand image Remarks

The concat method returns an Array object containing the concatenation of array1 and any other supplied items.

The items to be added (item1 itemN) to the array are added, in order, from left to right. If one of the items is an array, its contents are added to the end of array1. If the item is anything other than an array, it is added to the end of the array as a single array element.

Elements of source arrays are copied to the resulting array as follows:

  • For an object reference copied from any of the arrays being concatenated to the new array, the object reference continues to point to the same object. A change in either the new array or the original array will result in a change to the other.

  • For a numeric or string value being concatenated to the new array, only the value is copied. Changes in a value in one array does not affect the value in the other.

Expand image Example

The following example illustrates the use of the concat method when used with an array:

CopyCode image Copy Code
function ConcatArrayDemo(){
   var a, b, c, d;
   a = new Array(1,2,3);
   b = "JScript";
   c = new Array(42, "VBScript);
   d = a.concat(b, c);
   //Returns the array [1, 2, 3, "JScript", 42, "VBScript"]
   return(d);
}

Expand image Requirements

Version 3

Applies To: Array Object (JScript 5.6)

Expand image See Also

Reference

concat Method (String) (JScript 5.6)
join Method (JScript 5.6)
String Object (JScript 5.6)


concat Method (String) (JScript 5.6)

JScript
concat Method (String) (JScript 5.6)
See Also Example
CollapseAll image DropDown image

Returns a string value containing the concatenation of two or more supplied strings.

string1.concat([string2[, string3[, . . . [, stringN]]]])

Expand image Arguments

string1

Required. The String object or literal to which all other specified strings are concatenated.

string2,. . ., stringN

Optional. String objects or literals to concatenate to the end of string1.

Expand image Remarks

The result of the concat method is equivalent to: result = string1 + string2 + string3 + + stringN. A change of value in either a source or result string does not affect the value in the other string. If any of the arguments are not strings, they are first converted to strings before being concatenated to string1.

Expand image Example

The following example illustrates the use of the concat method when used with a string:
CopyCode image Copy Code
function concatDemo(){
   var str1 = "ABCDEFGHIJKLM"
   var str2 = "NOPQRSTUVWXYZ";
   var s = str1.concat(str2);
   // Return concatenated string.
   return(s);
}

Expand image Requirements

Version 3

Applies To: String Object (JScript 5.6)

Expand image See Also

Reference

Addition Operator (+) (JScript 5.6)
Array Object (JScript 5.6)
concat Method (Array) (JScript 5.6)


cos Method (JScript 5.6)

JScript
cos Method (JScript 5.6)
See Also
CollapseAll image DropDown image

Returns the cosine of a number.

Math.cos(number)

Expand image Remarks

The required number argument is a numeric expression for which the cosine is needed.

The return value is the cosine of its numeric argument.

Applies To: Math Object (JScript 5.6)

Expand image Requirements

Version 1

Expand image See Also

Reference

acos Method (JScript 5.6)
asin Method (JScript 5.6)
atan Method (JScript 5.6)
sin Method (JScript 5.6)
tan Method (JScript 5.6)


decodeURI Method (JScript 5.6)

JScript
decodeURI Method (JScript 5.6)
See Also
CollapseAll image DropDown image

Returns the unencoded version of an encoded Uniform Resource Identifier (URI).

decodeURI(URIstring)

Expand image Remarks

The required URIstring argument is a value representing an encoded URI.

Use the decodeURI method instead of the obsolete unescape method.

The decodeURI method returns a string value.

If the URIString is not valid, a URIError occurs.

Applies To: Global Object (JScript 5.6)

Expand image Requirements

Version 5.5

Expand image See Also

Reference

decodeURIComponent Method (JScript 5.6)
encodeURI Method (JScript 5.6)
Global Object (JScript 5.6)


decodeURIComponent Method (JScript 5.6)

JScript
decodeURIComponent Method (JScript 5.6)
See Also
CollapseAll image DropDown image

Returns the unencoded version of an encoded component of a Uniform Resource Identifier (URI).

decodeURIComponent(encodedURIString)

Expand image Remarks

The required encodedURIString argument is a value representing an encoded URI component.

A URIComponent is part of a complete URI.

If the encodedURIString is not valid, a URIError occurs.

Applies To: Global Object (JScript 5.6)

Expand image Requirements

Version 5.5

Expand image See Also

Reference

decodeURI Method (JScript 5.6)
encodeURI Method (JScript 5.6)


dimensions Method (JScript 5.6)

JScript
dimensions Method (JScript 5.6)
See Also Example
CollapseAll image DropDown image

Returns the number of dimensions in a VBArray.

array.dimensions( )

Expand image Remarks

The required array is a VBArray object.

Expand image Example

The dimensions method provides a way to retrieve the number of dimensions in a specified VBArray.

The following example consists of three parts. The first part is VBScript code to create a Visual Basic safe array. The second part is JScript code that determines the number of dimensions in the safe array and the upper bound of each dimension. Both of these parts go into the <HEAD> section of an HTML page. The third part is the JScript code that goes in the <BODY> section to run the other two parts.

CopyCode image Copy Code
<HEAD>
<SCRIPT LANGUAGE="VBScript">
<!--
Function CreateVBArray()
   Dim i, j, k
   Dim a(2, 2)
   k = 1
   For i = 0 To 2
      For j = 0 To 2
         a(j, i) = k
         k = k + 1
      Next
   Next
   CreateVBArray = a
End Function
-->
</SCRIPT>

<SCRIPT LANGUAGE="JScript">
<!--
function VBArrayTest(vba)
{
   var i, s;
   var a = new VBArray(vba);
   for (i = 1; i <= a.dimensions(); i++)
   {
      s = "The upper bound of dimension ";
      s += i + " is ";
      s += a.ubound(i)+ ".<BR>";
   }
   return(s);
}
-->
</SCRIPT>
</HEAD>

<BODY>
<SCRIPT language="jscript">
   document.write(VBArrayTest(CreateVBArray()));
</SCRIPT>
</BODY>

Expand image Requirements

Version 3

Applies To: VBArray Object (JScript 5.6)

Expand image See Also

Reference

getItem Method (JScript 5.6)
lbound Method (JScript 5.6)
toArray Method (JScript 5.6)
ubound Method (JScript 5.6)


encodeURI Method (JScript 5.6)

JScript
encodeURI Method (JScript 5.6)
See Also
CollapseAll image DropDown image

Encodes a text string as a valid Uniform Resource Identifier (URI)

encodeURI(URIString)

Expand image Remarks

The required URIString argument is a value representing an encoded URI.

The encodeURI method returns an encoded URI. If you pass the result to decodeURI, the original string is returned. The encodeURI method does not encode the following characters: ":", "/", ";", and "?". Use encodeURIComponent to encode these characters.

Applies To: Global Object (JScript 5.6)

Expand image Requirements

Version 5.5

Expand image See Also

Reference

decodeURI Method (JScript 5.6)
decodeURIComponent Method (JScript 5.6)


encodeURIComponent Method (JScript 5.6)

JScript
encodeURIComponent Method (JScript 5.6)
See Also
CollapseAll image DropDown image

Encodes a text string as a valid component of a Uniform Resource Identifier (URI).

encodeURIComponent(encodedURIString)

Expand image Remarks

The required encodedURIString argument is a value representing an encoded URI component.

The encodeURIComponent method returns an encoded URI. If you pass the result to decodeURIComponent, the original string is returned. Because the encodeURIComponent method encodes all characters, be careful if the string represents a path such as /folder1/folder2/default.html. The slash characters will be encoded and will not be valid if sent as a request to a web server. Use the encodeURI method if the string contains more than a single URI component.

Applies To: Global Object (JScript 5.6)

Expand image Requirements

Version 5.5

Expand image See Also

Reference

decodeURI Method (JScript 5.6)
decodeURIComponent Method (JScript 5.6)


escape Method (JScript 5.6)

JScript
escape Method (JScript 5.6)
See Also
CollapseAll image DropDown image

Encodes String objects so they can be read on all computers.

escape(charString)

Expand image Remarks

The required charString argument is any String object or literal to be encoded.

The escape method returns a string value (in Unicode format) that contains the contents of charstring. All spaces, punctuation, accented characters, and any other non-ASCII characters are replaced with %xx encoding, where xx is equivalent to the hexadecimal number representing the character. For example, a space is returned as "%20."

Characters with a value greater than 255 are stored using the %u xxxx format.

Note Note

The escape method should not be used to encode Uniform Resource Identifiers (URI). Use encodeURI and encodeURIComponent methods instead.

Applies To: Global Object (JScript 5.6)

Expand image Requirements

Version 1

Expand image See Also

Reference

encodeURI Method (JScript 5.6)
encodeURIComponent Method (JScript 5.6)
String Object (JScript 5.6)
unescape Method (JScript 5.6)


eval Method (JScript 5.6)

JScript
eval Method (JScript 5.6)
See Also
CollapseAll image DropDown image

Evaluates JScript code and executes it.

eval(codeString)

Expand image Remarks

The required codeString argument is a string value that contains valid JScript code. This string is parsed by the JScript parser and executed.

The eval function allows dynamic execution of JScript source code. For example, the following code creates a new variable mydate that contains a Date object:

CopyCode image Copy Code
        eval("var mydate = new Date();");

The code passed to the eval method is executed in the same context as the call to the eval method.

Applies To: Global Object (JScript 5.6)

Expand image Requirements

Version 1

Expand image See Also

Reference

String Object (JScript 5.6)


exec Method (JScript 56)

JScript
exec Method (JScript 56)
See Also Example
CollapseAll image DropDown image

Executes a search on a string using a regular expression pattern, and returns an array containing the results of that search.

rgExp.exec(str)

Expand image Arguments

rgExp

Required. An instance of a Regular Expression object containing the regular expression pattern and applicable flags.

str

Required. The String object or string literal on which to perform the search.

Expand image Remarks

If the exec method does not find a match, it returns null. If it finds a match, exec returns an array, and the properties of the global RegExp object are updated to reflect the results of the match. Element zero of the array contains the entire match, while elements 1 – n contain any submatches that have occurred within the match. This behavior is identical to the behavior of the match method without the global flag (g) set.

If the global flag is set for a regular expression, exec searches the string beginning at the position indicated by the value of lastIndex. If the global flag is not set, exec ignores the value of lastIndex and searches from the beginning of the string.

The array returned by the exec method has three properties, input, index and lastIndex. The input property contains the entire searched string. The index property contains the position of the matched substring within the complete searched string. The lastIndex property contains the position following the last character in the match.

Expand image Example

The following example illustrates the use of the exec method:
CopyCode image Copy Code
function RegExpTest(){
  var ver = Number(ScriptEngineMajorVersion() + "." + ScriptEngineMinorVersion())
  if (ver >= 5.5){                 //Test JScript version.
    var src = "The rain in Spain falls mainly in the plain.";
    var re = /\w+/g;               //Create regular expression pattern.
    var arr;
    while ((arr = re.exec(src)) != null)
       document.write(arr.index + "-" + arr.lastIndex + "\t" + arr);
  }
  else{
    alert("You need a newer version of JScript for this to work");
  }
}

Expand image Requirements

Version 3

Applies To: Regular Expression Object (JScript 5.6)

Expand image See Also

Reference

match Method (JScript 5.6)
RegExp Object (JScript 5.6)
Regular Expression Syntax (Scripting)
search Method (JScript 5.6)
test Method (JScript 5.6)


exp Method (JScript 5.6)

JScript
exp Method (JScript 5.6)
See Also
CollapseAll image DropDown image

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

Math.exp(number)

Expand image Remarks

The required number argument is numeric expression representing the power of e.

The return value is enumber. The constant e is Euler's constant, approximately equal to 2.178 and number is the supplied argument.

Applies To: Math Object (JScript 5.6)

Expand image Requirements

Version 1

Expand image See Also

Reference

E Property (JScript 5.6)


fixed Method (JScript 5.6)

JScript
fixed Method (JScript 5.6)
See Also
CollapseAll image DropDown image

Places HTML <TT> tags around text in a String object.

strVariable.fixed( )

Expand image Remarks

The required strVariable reference is any String object or literal.

The following example demonstrates how the fixed method works:

CopyCode image Copy Code
var strVariable = "This is a string object";
strVariable = strVariable.fixed();

The value of strVariable after the last statement is:

CopyCode image Copy Code
<TT>This is a string object</TT>

No checking is done to see if the tag has already been applied to the string.

Applies To: String Object (JScript 5.6)

Expand image Requirements

Version 1

Expand image See Also

Reference

String Object (JScript 5.6)


floor Method (JScript 5.6)

JScript
floor Method (JScript 5.6)
See Also
CollapseAll image DropDown image

Returns the greatest integer less than or equal to its numeric argument.

Math.floor(number)

Expand image Remarks

The required number argument is a numeric expression.

The return value is an integer value equal to the greatest integer less than or equal to its numeric argument.

Applies To: Math Object (JScript 5.6)

Expand image Requirements

Version 1

Expand image See Also

Reference

ceil Method (JScript 5.6)


fontcolor Method (JScript 5.6)

JScript
fontcolor Method (JScript 5.6)
See Also
CollapseAll image DropDown image

Places an HTML <FONT> tag with the COLOR attribute around the text in a String object.

strVariable.fontcolor(colorVal)

Expand image Arguments

strVariable

Required. Any String object or literal.

colorVal

Required. String value containing a color value. This can either be the hexadecimal value for a color, or the predefined name for a color.

Expand image Remarks

The following example demonstrates the fontcolor method:

CopyCode image Copy Code
var strVariable = "This is a string";
strVariable = strVariable.fontcolor("red");

The value of strVariable after the last statement is:

CopyCode image Copy Code
<FONT COLOR="RED">This is a string</FONT>

Valid predefined color names depend on your JScript host (browser, server, and so forth). They may also vary from version to version of your host. Check your host documentation for more information.

No checking is done to see if the tag has already been applied to the string.

Applies To: String Object (JScript 5.6)

Expand image Requirements

Version 1

Expand image See Also

Reference

fontsize Method (JScript 5.6)


fontsize Method (JScript 5.6)

JScript
fontsize Method (JScript 5.6)
See Also
CollapseAll image DropDown image

Places an HTML <FONT> tag with the SIZE attribute around the text in a String object.

strVariable.fontsize(intSize)

Expand image Arguments

strVariable

Required. Any String object or literal.

intSize

Required. Integer value that specifies the size of the text.

Expand image Remarks

The following example demonstrates the fontsize method:

CopyCode image Copy Code
var strVariable = "This is a string";
strVariable = strVariable.fontsize(-1);

The value of strVariable after the last statement is:

CopyCode image Copy Code
<FONT SIZE="-1">This is a string</FONT>

Valid integer values depend on your Microsoft JScript host. See your host documentation for more information.

No checking is done to see if the tag has already been applied to the string.

Applies To: String Object (JScript 5.6)

Expand image Requirements

Version 1

Expand image See Also

Reference

fontcolor Method (JScript 5.6)


fromCharCode Method (JScript 5.6)

JScript
fromCharCode Method (JScript 5.6)
See Also
CollapseAll image DropDown image

Returns a string from a number of Unicode character values.

String.fromCharCode([code1[, code2[, ...[, codeN]]]])

Expand image Arguments

String

Required. The String object.

code1, . . . , codeN

Optional. A series of Unicode character values to convert to a string. If no arguments are supplied, the result is the empty string.

Expand image Remarks

A String object need not be created before calling fromCharCode.

In the following example, test contains the string "plain":

CopyCode image Copy Code
var test = String.fromCharCode(112, 108, 97, 105, 110);

Expand image Requirements

Version 3

Applies To: String Object (JScript 5.6)

Expand image See Also

Reference

charCodeAt Method (JScript 5.6)


getDate Method (JScript 5.6)

JScript
getDate Method (JScript 5.6)
See Also Example
CollapseAll image DropDown image

Returns the day of the month value in a Date object using local time.

dateObj.getDate()

Expand image Remarks

The required dateObj reference is a Date object.

To get the date value using Universal Coordinated Time (UTC), use the getUTCDate method.

The return value is an integer between 1 and 31 that represents the date value in the Date object.

Expand image Example

The following example illustrates the use of the getDate method.

CopyCode image Copy Code
function DateDemo(){
   var d, s = "Today's date is: ";
   d = new Date();
   s += (d.getMonth() + 1) + "/";
   s += d.getDate() + "/";
   s += d.getYear();
   return(s);
}

Expand image Requirements

Version 1

Applies To: Date Object (JScript 5.6)

Expand image See Also

Reference

getUTCDate Method (JScript 5.6)
setDate Method (JScript 5.6)
setUTCDate Method (JScript 5.6)


getDay Method (JScript 5.6)

JScript
getDay Method (JScript 5.6)
See Also
CollapseAll image DropDown image

Returns the day of the week value in a Date object using local time.

dateObj.getDay()

Expand image Remarks

The required dateObj reference is a Date object.

To get the day using Universal Coordinated Time (UTC), use the getUTCDay method.

The value returned from the getDay method is an integer between 0 and 6 representing the day of the week and corresponds to a day of the week as follows:

Value | Day of the Week
0 | Sunday
1 | Monday
2 | Tuesday
3 | Wednesday
4 | Thursday
5 | Friday
6 | Saturday

The following example illustrates the use of the getDay method.

CopyCode image Copy Code
function DateDemo(){
   var d, day, x, s = "Today is: ";
   var x = new Array("Sunday", "Monday", "Tuesday");
   var x = x.concat("Wednesday","Thursday", "Friday");
   var x = x.concat("Saturday");
   d = new Date();
   day = d.getDay();
   return(s += x[day]);
}

Expand image Requirements

Version 1

Applies To: Date Object (JScript 5.6)

Expand image See Also

Reference

getUTCDay Method (JScript 5.6)


getFullYear Method (JScript 5.6)

JScript
getFullYear Method (JScript 5.6)
See Also Example
CollapseAll image DropDown image

Returns the year value in the Date object using local time.

dateObj.getFullYear()

Expand image Remarks

The required dateObj reference is a Date object.

To get the year using Universal Coordinated Time (UTC), use the getUTCFullYear method.

The getFullYear method returns the year as an absolute number. For example, the year 1976 is returned as 1976. This avoids the year 2000 problem where dates beginning with January 1, 2000 are confused with those beginning with January 1, 1900.

Expand image Example

The following example illustrates the use of the GetFullYear method.
CopyCode image Copy Code
function DateDemo(){
   var d, s = "Today's UTC date is: ";
   d = new Date();
   s += (d.getMonth() + 1) + "/";
   s += d.getDate() + "/";
   s += d.getFullYear();
   return(s);
}

Expand image Requirements

Version 3

Applies To: Date Object (JScript 5.6)

Expand image See Also

Reference

getUTCFullYear Method (JScript 5.6)
setFullYear Method (JScript 5.6)
setUTCFullYear Method (JScript 5.6)


getHours Method (JScript 5.6)

JScript
getHours Method (JScript 5.6)
See Also Example
CollapseAll image DropDown image

Returns the hours value in a Date object using local time.

dateObj.getHours()

Expand image Remarks

The required dateObj reference is a Date object.

To get the hours value using Universal Coordinated Time (UTC), use the getUTCHours method.

The getHours method returns an integer between 0 and 23, indicating the number of hours since midnight. A zero occurs in two situations: the time is before 1:00:00 am, or the time was not stored in the Date object when the object was created. The only way to determine which situation you have is to also check the minutes and seconds for zero values. If they are all zeroes, it is nearly certain that the time was not stored in the Date object.

Expand image Example

The following example illustrates the use of the getHours method.

CopyCode image Copy Code
function TimeDemo(){
   var d, s = "The current local time is: ";
   var c = ":";
   d = new Date();
   s += d.getHours() + c;
   s += d.getMinutes() + c;
   s += d.getSeconds() + c;
   s += d.getMilliseconds();
   return(s);
}

Expand image Requirements

Version 1

Applies To: Date Object (JScript 5.6)

Expand image See Also

Reference

getUTCHours Method (JScript 5.6)
setHours Method (JScript 5.6)
setUTCHours Method (JScript 5.6)


getItem Method (JScript 5.6)

JScript
getItem Method (JScript 5.6)
See Also Example
CollapseAll image DropDown image

Returns the item at the specified location.

safeArray.getItem(dimension1[, dimension2, ...], dimensionN)

Expand image Arguments

safeArray

Required. A VBArray object.

dimension1, ..., dimensionN

Specifies the exact location of the desired element of the VBArray. n equals the number of dimensions in the VBArray.

Expand image Example

The following example consists of three parts. The first part is VBScript code to create a Visual Basic safe array. The second part is JScript code that iterates the Visual Basic safe array and prints out the contents of each element. Both of these parts go into the <HEAD> section of an HTML page. The third part is the JScript code that goes in the <BODY> section to run the other two parts.

CopyCode image Copy Code
<HEAD>
<SCRIPT LANGUAGE="VBScript">
<!--
Function CreateVBArray()
   Dim i, j, k
   Dim a(2, 2)
   k = 1
   For i = 0 To 2
      For j = 0 To 2
         a(i, j) = k
         document.writeln(k)
         k = k + 1
      Next
      document.writeln("<BR>")
   Next
   CreateVBArray = a
End Function
-->
</SCRIPT>
<SCRIPT LANGUAGE="JScript">
<!--
function GetItemTest(vbarray)
{
   var i, j;
   var a = new VBArray(vbarray);
   for (i = 0; i <= 2; i++)
   {
      for (j =0; j <= 2; j++)
      {
         document.writeln(a.getItem(i, j));
      }
   }
}-->
</SCRIPT>
</HEAD>
&ltBODY>
<SCRIPT LANGUAGE="JScript">
<!--
   GetItemTest(CreateVBArray());
-->
</SCRIPT>
</BODY>

Expand image Requirements

Version 1

Applies To: VBArray Object (JScript 5.6)

Expand image See Also

Reference

dimensions Method (JScript 5.6)
lbound Method (JScript 5.6)
toArray Method (JScript 5.6)
ubound Method (JScript 5.6)


getMilliseconds Method (JScript 5.6)

JScript
getMilliseconds Method (JScript 5.6)
See Also Example
CollapseAll image DropDown image

Returns the milliseconds value in a Date object using local time.

dateObj.getMilliseconds()

Expand image Remarks

The required dateObj reference is a Date object.

To get the number of milliseconds in Universal Coordinated Time (UTC), use the getUTCMilliseconds method.

The millisecond value returned can range from 0-999.

Expand image Example

The following example illustrates the use of the getMilliseconds method.

CopyCode image Copy Code
function TimeDemo(){
   var d, s = "The current local time is: ";
   var c = ":";
   d = new Date();
   s += d.getHours() + c;
   s += d.getMinutes() + c;
   s += d.getSeconds() + c;
   s += d.getMilliseconds();
   return(s);
}

Expand image Requirements

Version 3

Applies To: Date Object (JScript 5.6)

Expand image See Also

Reference

getUTCMilliseconds Method (JScript 5.6)
setMilliseconds Method (JScript 5.6)
setUTCMilliseconds Method (JScript 5.6)


getMinutes Method (JScript 5.6)

JScript
getMinutes Method (JScript 5.6)
See Also Example
CollapseAll image DropDown image

Returns the minutes value in a Date object using local time.

dateObj.getMinutes()

Expand image Remarks

The required dateObj reference is a Date object.

To get the minutes value using Universal Coordinated Time (UTC), use the getUTCMinutes method.

The getMinutes method returns an integer between 0 and 59 equal to the minutes value stored in the Date object. A zero is returned in two situations: when the time is less than one minute after the hour, or when the time was not stored in the Date object when the object was created. The only way to determine which situation you have is to also check the hours and seconds for zero values. If they are all zeroes, it is nearly certain that the time was not stored in the Date object.

Expand image Example

The following example illustrates the use of the getMinutes method.

CopyCode image Copy Code
function TimeDemo(){
   var d, s = "The current local time is: ";
   var c = ":";
   d = new Date();
   s += d.getHours() + c;
   s += d.getMinutes() + c;
   s += d.getSeconds() + c;
   s += d.getMilliseconds();
   return(s);
}

Expand image Requirements

Version 3

Applies To: Date Object (JScript 5.6)

Expand image See Also

Reference

getUTCMinutes Method (JScript 5.6)
setMinutes Method (JScript 5.6)
setUTCMinutes Method (JScript 5.6)


getMonth Method (JScript 5.6)

JScript
getMonth Method (JScript 5.6)
See Also Example
CollapseAll image DropDown image

Returns the month value in the Date object using local time.

dateObj.getMonth()

Expand image Remarks

The required dateObj reference is a Date object.

To get the month value using Universal Coordinated Time (UTC), use the getUTCMonth method.

The getMonth method returns an integer between 0 and 11 indicating the month value in the Date object. The integer returned is not the traditional number used to indicate the month. It is one less. If "Jan 5, 1996 08:47:00" is stored in a Date object, getMonth returns 0.

Expand image Example

The following example illustrates the use of the getMonth method.

CopyCode image Copy Code
function DateDemo(){
   var d, s = "Today's date is: ";
   d = new Date();
   s += (d.getMonth() + 1) + "/";
   s += d.getDate() + "/";
   s += d.getYear();
   return(s);
}

Expand image Requirements

Version 1

Applies To: Date Object (JScript 5.6)

Expand image See Also

Reference

getUTCMonth Method (JScript 5.6)
setMonth Method (JScript 5.6)
setUTCMonth Method (JScript 5.6)


getSeconds Method (JScript 5.6)

JScript
getSeconds Method (JScript 5.6)
See Also Example
CollapseAll image DropDown image

Returns the seconds value in a Date object using local time.

dateObj.getSeconds()

Expand image Remarks

The required dateObj reference is a Date object.

To get the seconds value using Universal Coordinated Time (UTC), use the getUTCSeconds method.

The getSeconds method returns an integer between 0 and 59 indicating the seconds value of the indicated Date object. A zero is returned in two situations. One occurs when the time is less than one second into the current minute. The other occurs when the time was not stored in the Date object when the object was created. The only way to determine which situation you have is to also check the hours and minutes for zero values. If they are all zeroes, it is nearly certain that the time was not stored in the Date object.

Expand image Example

The following example illustrates the use of the getSeconds method.

CopyCode image Copy Code
function TimeDemo(){
   var d, s = "The current local time is: ";
   var c = ":";
   d = new Date();
   s += d.getHours() + c;
   s += d.getMinutes() + c;
   s += d.getSeconds() + c;
   s += d.getMilliseconds();
   return(s);
}

Expand image Requirements

Version 1

Applies To: Date Object (JScript 5.6)

Expand image See Also

Reference

getUTCSeconds Method (JScript 5.6)
setSeconds Method (JScript 5.6)
setUTCSeconds Method (JScript 5.6)


getTime Method (JScript 5.6)

JScript
getTime Method (JScript 5.6)
See Also Example
CollapseAll image DropDown image

Returns the time value in a Date object.

dateObj.getTime()

Expand image Remarks

The required dateObj reference is a Date object.

The getTime method returns an integer value representing the number of milliseconds between midnight, January 1, 1970 and the time value in the Date object. The range of dates is approximately 285,616 years from either side of midnight, January 1, 1970. Negative numbers indicate dates prior to 1970.

When doing multiple date and time calculations, it is frequently useful to define variables equal to the number of milliseconds in a day, hour, or minute. For example:

CopyCode image Copy Code
var MinMilli = 1000 * 60
var HrMilli = MinMilli * 60
var DyMilli = HrMilli * 24

Expand image Example

The following example illustrates the use of the getTime method.

CopyCode image Copy Code
function GetTimeTest(){
   var d, s, t;
   var MinMilli = 1000 * 60;
   var HrMilli = MinMilli * 60;
   var DyMilli = HrMilli * 24;
   d = new Date();
   t = d.getTime();
   s = "It's been "
   s += Math.round(t / DyMilli) + " days since 1/1/70";
   return(s);
}

Expand image Requirements

Version 1

Applies To: Date Object (JScript 5.6)

Expand image See Also

Reference

setTime Method (JScript 5.6)


getTimezoneOffset Method (JScript 5.6)

JScript
getTimezoneOffset Method (JScript 5.6)
See Also Example
CollapseAll image DropDown image

Returns the difference in minutes between the time on the host computer and Universal Coordinated Time (UTC).

dateObj.getTimezoneOffset()

Expand image Remarks

The required dateObj reference is a Date object.

The getTimezoneOffset method returns an integer value representing the number of minutes between the time on the current machine and UTC. These values are appropriate to the computer the script is executed on. If it is called from a server script, the return value is appropriate to the server. If it is called from a client script, the return value is appropriate to the client.

This number will be positive if you are behind UTC (e.g., Pacific Daylight Time), and negative if you are ahead of UTC (e.g., Japan).

For example, suppose a server in New York City is contacted by a client in Los Angeles on December 1. getTimezoneOffset returns 480 if executed on the client, or 300 if executed on the server.

Expand image Example

The following example illustrates the use of the getTimezoneOffset method.

CopyCode image Copy Code
function TZDemo(){
   var d, tz, s = "The current local time is ";
   d = new Date();
   tz = d.getTimezoneOffset();
   if (tz < 0)
      s += tz / 60 + " hours before GMT";
   else if (tz == 0)
      s += "GMT";
   else
      s += tz / 60 + " hours after GMT";
   return(s);
}

Expand image Requirements

Version 1

Applies To: Date Object (JScript 5.6)

Expand image See Also

Reference

getTime Method (JScript 5.6)


getUTCDate Method (JScript 5.6)

JScript
getUTCDate Method (JScript 5.6)
See Also Example
CollapseAll image DropDown image

Returns the date in a Date object using Universal Coordinated Time (UTC).

dateObj.getUTCDate()

Expand image Remarks

The required dateObj reference is a Date object.

To get the date using local time, use the getDate method.

The return value is an integer between 1 and 31 that represents the date value in the Date object.

Expand image Example

The following example illustrates the use of the getUTCDate method.

CopyCode image Copy Code
function UTCDateDemo(){
   var d, s = "Today's UTC date is: ";
   d = new Date();
   s += (d.getUTCMonth() + 1) + "/";
   s += d.getUTCDate() + "/";
   s += d.getUTCFullYear();
   return(s);
}

Expand image Requirements

Version 3

Applies To: Date Object (JScript 5.6)

Expand image See Also

Reference

getDate Method (JScript 5.6)
setDate Method (JScript 5.6)
setUTCDate Method (JScript 5.6)


getUTCDay Method (JScript 5.6)

JScript
getUTCDay Method (JScript 5.6)
See Also Example
CollapseAll image DropDown image

Returns the day of the week value in a Date object using Universal Coordinated Time (UTC).

dateObj.getUTCDay()

Expand image Remarks

The required dateObj reference is a Date object.

To get the day of the week using local time, use the getDate method.

The value returned by the getUTCDay method is an integer between 0 and 6 representing the day of the week and corresponds to a day of the week as follows:

Value | Day of the Week
0 | Sunday
1 | Monday
2 | Tuesday
3 | Wednesday
4 | Thursday
5 | Friday
6 | Saturday

Expand image Example

The following example illustrates the use of the getUTCDay method.

CopyCode image Copy Code
function DateDemo(){
   var d, day, x, s = "Today is ";
   var x = new Array("Sunday", "Monday", "Tuesday");
   x = x.concat("Wednesday","Thursday", "Friday");
   x = x.concat("Saturday");
   d = new Date();
   day = d.getUTCDay();
   return(s += x[day]);
}

Expand image Requirements

Version 3

Applies To: Date Object (JScript 5.6)

Expand image See Also

Reference

getDay Method (JScript 5.6)


getUTCFullYear Method (JScript 5.6)

JScript
getUTCFullYear Method (JScript 5.6)
See Also Example
CollapseAll image DropDown image

Returns the year value in a Date object using Universal Coordinated Time (UTC).

dateObj.getUTCFullYear()

Expand image Remarks

The required dateObj reference is a Date object.

To get the year using local time, use the getFullYear method.

The getUTCFullYear method returns the year as an absolute number. This avoids the year 2000 problem where dates beginning with January 1, 2000 are confused with those beginning with January 1, 1900.

Expand image Example

The following example illustrates the use of the getUTCFullYear method.

CopyCode image Copy Code
function UTCDateDemo(){
   var d, s = "Today's UTC date is: ";
   d = new Date();
   s += (d.getUTCMonth() + 1) + "/";
   s += d.getUTCDate() + "/";
   s += d.getUTCFullYear();
   return(s);
}

Expand image Requirements

Version 3

Applies To: Date Object (JScript 5.6)

Expand image See Also

Reference

getFullYear Method (JScript 5.6)
setFullYear Method (JScript 5.6)
setUTCFullYear Method (JScript 5.6)


getUTCHours Method (JScript 5.6)

JScript
getUTCHours Method (JScript 5.6)
See Also Example
CollapseAll image DropDown image

Returns the hours value in a Date object using Universal Coordinated Time (UTC).

dateObj.getUTCHours()

Expand image Remarks

The required dateObj reference is a Date object.

To get the number of hours elapsed since midnight using local time, use the getHours method.

The getUTCHours method returns an integer between 0 and 23 indicating the number of hours since midnight. A zero occurs in two situations: the time is before 1:00:00 A.M., or a time was not stored in the Date object when the object was created. The only way to determine which situation you have is to also check the minutes and seconds for zero values. If they are all zeroes, it is nearly certain that the time was not stored in the Date object.

Expand image Example

The following example illustrates the use of the getUTCHours method.

CopyCode image Copy Code
function UTCTimeDemo(){
   var d, s = "Current Universal Coordinated Time (UTC) is: ";
   var c = ":";
   d = new Date();
   s += d.getUTCHours() + c;
   s += d.getUTCMinutes() + c;
   s += d.getUTCSeconds() + c;
   s += d.getUTCMilliseconds();
   return(s);
}

Expand image Requirements

Version 3

Applies To: Date Object (JScript 5.6)

Expand image See Also

Reference

getHours Method (JScript 5.6)
setHours Method (JScript 5.6)
setUTCHours Method (JScript 5.6)


getUTCMilliseconds Method (JScript 5.6)

JScript
getUTCMilliseconds Method (JScript 5.6)
See Also Example
CollapseAll image DropDown image

Returns the milliseconds value in a Date object using Universal Coordinated Time (UTC).

dateObj.getUTCMilliseconds()

Expand image Remarks

The required dateObj reference is a Date object.

To get the number of milliseconds in local time, use the getMilliseconds method.

The millisecond value returned can range from 0-999.

Expand image Example

The following example illustrates the use of the getUTCMilliseconds method.

CopyCode image Copy Code
function UTCTimeDemo(){
   var d, s = "Current Universal Coordinated Time (UTC) is: ";
   var c = ":";
   d = new Date();
   s += d.getUTCHours() + c;
   s += d.getUTCMinutes() + c;
   s += d.getUTCSeconds() + c;
   s += d.getUTCMilliseconds();
   return(s);
}

Expand image Requirements

Version 3

Applies To: Date Object (JScript 5.6)

Expand image See Also

Reference

getMilliseconds Method (JScript 5.6)
setMilliseconds Method (JScript 5.6)
setUTCMilliseconds Method (JScript 5.6)


getUTCMinutes Method (JScript 5.6)

JScript
getUTCMinutes Method (JScript 5.6)
See Also Example
CollapseAll image DropDown image

Returns the minutes value in a Date object using Universal Coordinated Time (UTC).

dateObj.getUTCMinutes()

Expand image Remarks

The required dateObj reference is a Date object.

To get the number of minutes stored using local time, use the getMinutes method.

The getUTCMinutes method returns an integer between 0 and 59 equal to the number of minutes value in the Date object. A zero occurs in two situations: the time is less than one minute after the hour, or a time was not stored in the Date object when the object was created. The only way to determine which situation you have is to also check the hours and seconds for zero values. If they are all zeroes, it is nearly certain that the time was not stored in the Date object.

Expand image Example

The following example illustrates the use of the getUTCMinutes method.

CopyCode image Copy Code
function UTCTimeDemo()
{
   var d, s = "Current Universal Coordinated Time (UTC) is: ";
   var c = ":";
   d = new Date();
   s += d.getUTCHours() + c;
   s += d.getUTCMinutes() + c;
   s += d.getUTCSeconds() + c;
   s += d.getUTCMilliseconds();
   return(s);
}

Expand image Requirements

Version 3

Applies To: Date Object (JScript 5.6)

Expand image See Also

Reference

getMinutes Method (JScript 5.6)
setMinutes Method (JScript 5.6)
setUTCMinutes Method (JScript 5.6)


getUTCMonth Method (JScript 5.6)

JScript
getUTCMonth Method (JScript 5.6)
See Also Example
CollapseAll image DropDown image

Returns the month value in a Date object using Universal Coordinated Time (UTC).

dateObj.getUTCMonth()

Expand image Remarks

The required dateObj reference is a Date object.

To get the month in local time, use the getMonth method.

The getUTCMonth method returns an integer between 0 and 11 indicating the month value in the Date object. The integer returned is not the traditional number used to indicate the month. It is one less. If "Jan 5, 1996 08:47:00.0" is stored in a Date object, getUTCMonth returns 0.

Expand image Example

The following example illustrates the use of the getUTCMonth method.

CopyCode image Copy Code
function UTCDateDemo(){
   var d, s = "Today's UTC date is: ";
   d = new Date();
   s += (d.getUTCMonth() + 1) + "/";
   s += d.getUTCDate() + "/";
   s += d.getUTCFullYear();
   return(s);
}

Expand image Requirements

Version 3

Applies To: Date Object (JScript 5.6)

Expand image See Also

Reference

getMonth Method (JScript 5.6)
setMonth Method (JScript 5.6)
setUTCMonth Method (JScript 5.6)


getUTCSeconds Method (JScript 5.6)

JScript
getUTCSeconds Method (JScript 5.6)
See Also Example
CollapseAll image DropDown image

Returns the seconds value in a Date object using Universal Coordinated Time (UTC).

dateObj.getUTCSeconds()

Expand image Remarks

The required dateObj reference is a Date object.

To get the number of seconds in local time, use the getSeconds method.

The getUTCSeconds method returns an integer between 0 and 59 indicating the seconds value of the indicated Date object. A zero occurs in two situations: the time is less than one second into the current minute, or a time was not stored in the Date object when the object was created. The only way to determine which situation you have is to also check the minutes and hours for zero values. If they are all zeroes, it is nearly certain that the time was not stored in the Date object.

Expand image Example

The following example illustrates the use of the getUTCSeconds method.

CopyCode image Copy Code
function UTCTimeDemo(){
   var d, s = "Current Universal Coordinated Time (UTC) is: ";
   var c = ":";
   d = new Date();
   s += d.getUTCHours() + c;
   s += d.getUTCMinutes() + c;
   s += d.getUTCSeconds() + c;
   s += d.getUTCMilliseconds();
   return(s);
}

Expand image Requirements

Version 3

Applies To: Date Object (JScript 5.6)

Expand image See Also

Reference

getSeconds Method (JScript 5.6)
setSeconds Method (JScript 5.6)
setUTCSeconds Method (JScript 5.6)


getVarDate Method (JScript 5.6)

JScript
getVarDate Method (JScript 5.6)
See Also
CollapseAll image DropDown image

Returns the VT_DATE value in a Date object.

dateObj.getVarDate()

Expand image Remarks

The required dateObj reference is a Date object.

The getVarDate method is used when interacting with COM objects, ActiveX® objects or other objects that accept and return date values in VT_DATE format, such as Visual Basic and VBScript. The actual format is dependent on regional settings and should not be replied upon within JScript.

Expand image Requirements

Version 3

Applies To: Date Object (JScript 5.6)

Expand image See Also

Reference

getDate Method (JScript 5.6)
parse Method (JScript 5.6)


getYear Method (JScript 5.6)

JScript
getYear Method (JScript 5.6)
See Also Example
CollapseAll image DropDown image

Returns the year value in a Date object.

dateObj.getYear()

Expand image Remarks

The required dateObj reference is a Date object.

This method is obsolete, and is provided for backwards compatibility only. Use the getFullYear method instead.

For the years 1900 though 1999, the year is a 2-digit integer value returned as the difference between the stored year and 1900. For dates outside that period, the 4-digit year is returned. For example, 1996 is returned as 96, but 1825 and 2025 are returned as-is.

Note Note

For JScript version 1.0, getYear returns a value that is the result of the subtraction of 1900 from the year value in the provided Date object, regardless of the value of the year. For example, the year 1899 is returned as -1 and the year 2000 is returned as 100.

Expand image Example

The following example illustrates the use of the getYear method:

CopyCode image Copy Code
function DateDemo(){
   var d, s = "Today's date is: ";
   d = new Date();
   s += (d.getMonth() + 1) + "/";
   s += d.getDate() + "/";
   s += d.getYear();
   return(s);
}

Expand image Requirements

Version 1

Applies To: Date Object (JScript 5.6)

Expand image See Also

Reference

getFullYear Method (JScript 5.6)
getUTCFullYear Method (JScript 5.6)
setFullYear Method (JScript 5.6)
setUTCFullYear Method (JScript 5.6)
setYear Method (JScript 5.6)


hasOwnProperty Method (JScript 5.6)

JScript
hasOwnProperty Method (JScript 5.6)
See Also Example
CollapseAll image DropDown image

Returns a Boolean value indicating whether an object has a property with the specified name.

object.hasOwnProperty(proName)

Expand image Arguments

object

Required. Instance of an object.

proName

Required. String value of a property name.

Expand image Remarks

The hasOwnProperty method returns true if object has a property of the specified name, false if it does not. This method does not check if the property exists in the object's prototype chain; the property must be a member of the object itself.

Expand image Example

In the following example, all String objects share a common split method. The following code will print false and true.

CopyCode image Copy Code
var s = new String("JScript");
print(s.hasOwnProperty("split"));
print(String.prototype.hasOwnProperty("split"));

Expand image Requirements

Version 5.5

Applies To: Object Object (JScript 5.6)

Expand image See Also

Reference

in Operator (JScript 5.6)


indexOf Method (JScript 5.6)

JScript
indexOf Method (JScript 5.6)
See Also Example
CollapseAll image DropDown image

Returns the character position where the first occurrence of a substring occurs within a String object.

strObj.indexOf(subString[, startIndex])

Expand image Arguments

strObj

Required. A String object or literal.

subString

Required. Substring to search for within the String object.

startIndex

Optional. Integer value specifying the index to begin searching within the String object. If omitted, searching starts at the beginning of the string.

Expand image Remarks

The indexOf method returns an integer value indicating the beginning of the substring within the String object. If the substring is not found, a -1 is returned.

If startindex is negative, startindex is treated as zero. If it is larger than the greatest character position index, it is treated as the largest possible index.

Searching is performed from left to right. Otherwise, this method is identical to lastIndexOf.

Expand image Example

The following example illustrates the use of the indexOf method.
CopyCode image Copy Code
function IndexDemo(str2){
   var str1 = "BABEBIBOBUBABEBIBOBU"
   var s = str1.indexOf(str2);
   return(s);
}

Expand image Requirements

Version 1

Applies To: String Object (JScript 5.6)

Expand image See Also

Reference

lastIndexOf Method (JScript 5.6)


isFinite Method (JScript 5.6)

JScript
isFinite Method (JScript 5.6)
See Also
CollapseAll image DropDown image

Returns a Boolean value that indicates if a supplied number is finite.

isFinite(number)

Expand image Remarks

The required number argument is any numeric value.

The isFinite method returns true if number is any value other than NaN, negative infinity, or positive infinity. In those three cases, it returns false.

Expand image Requirements

Version 3

Applies To: Global Object (JScript 5.6)

Expand image See Also

Reference

isNaN Method (JScript 5.6)


isNaN Method (JScript 5.6)

JScript
isNaN Method (JScript 5.6)
See Also Example
CollapseAll image DropDown image

Returns a Boolean value that indicates whether a value is the reserved value NaN (not a number).

isNaN(numValue)

Expand image Return Value

true if the value converted to the Number type is the NaN, otherwise false.

Expand image Remarks

The required numValue is the value to be tested against NAN.

You typically use this method to test return values from the parseInt and parseFloat methods.

Alternatively, a variable could be compared to itself. If it compares as unequal, it is NaN. This is because NaN is the only value that is not equal to itself.

Expand image Requirements

Version 1

Applies To: Global Object (JScript 5.6)

Expand image Example

CopyCode image Copy Code
isNaN(100);                   //Returns false
isNaN("100");                 //Returns false
isNaN("ABC");                 //Returns true
isNaN("10C");                 //Returns true
isNaN(Math.sqrt(-1));         //Returns true

Expand image See Also

Reference

isFinite Method (JScript 5.6)
NaN Property (Global) (JScript 5.6)
parseFloat Method (JScript 5.6)
parseInt Method (JScript 5.6)


isPrototypeOf Method (JScript 5.6)

JScript
isPrototypeOf Method (JScript 5.6)
See Also Example
CollapseAll image DropDown image

Returns a Boolean value indicating whether an object exists in another object's prototype chain.

object1.isPrototypeOf(object2)

Expand image Arguments

object1

Required. Instance of an object.

object2

Required. Another object whose prototype chain is to be checked.

Expand image Remarks

The isPrototypeOf method returns true if object2 has object1 in its prototype chain. The prototype chain is used to share functionality between instances of the same object type. The isPrototypeOf method returns false when object2 is not an object or when object1 does not appear in the prototype chain of the object2.

Expand image Example

The following example illustrates the use of the isPrototypeOf method.
CopyCode image Copy Code
function test(){
  var re = new RegExp();                        //Initialize variable.
  return (RegExp.prototype.isPrototypeOf(re));  //Return true.
}

Expand image Requirements

Version 5.5

Applies To: Object Object (JScript 5.6)

Expand image See Also

Reference

isFinite Method (JScript 5.6)


italics Method (JScript 5.6)

JScript
italics Method (JScript 5.6)
See Also
CollapseAll image DropDown image

Places HTML <I> tags around text in a String object.

strVariable.italics( )
"String Literal".italics( )

Expand image Remarks

The following example demonstrates how the italics method works:

CopyCode image Copy Code
var strVariable = "This is a string";
strVariable = strVariable.italics( );

The value of strVariable after the last statement is:

CopyCode image Copy Code
<I>This is a string</I>

No checking is done to see if the tag has already been applied to the string.

Expand image Requirements

Version 1

Applies To: String Object (JScript 5.6)

Expand image See Also

Reference

bold Method (JScript 5.6)


item Method (JScript 5.6)

JScript
item Method (JScript 5.6)
See Also Example
CollapseAll image DropDown image

Returns the current item in the collection.

enumObj.item()

Expand image Remarks

The required enumObj reference is any Enumerator object.

The item method returns the current item. If the collection is empty or the current item is undefined, it returns undefined.

Expand image Example

In following code, the item method is used to return a member of the Drives collection.

CopyCode image Copy Code
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);
}

Expand image Requirements

Version 3

Applies To: Enumerator Object (JScript 5.6)

Expand image See Also

Reference

atEnd Method (JScript 5.6)
moveFirst Method (JScript 5.6)
moveNext Method (JScript 5.6)


join Method (JScript 5.6)

JScript
join Method (JScript 5.6)
See Also Example
CollapseAll image DropDown image

Returns a string value consisting of all the elements of an array concatenated together and separated by the specified separator character.

arrayObj.join(separator)

Expand image Arguments

arrayObj

Required. An Array object.

separator

Required. A String object used to separate one element of an array from the next in the resulting String object. If omitted, the array elements are separated with a comma.

Expand image Remarks

If any element of the array is undefined or null, it is treated as an empty string.

Expand image Example

The following example illustrates the use of the join method.

CopyCode image Copy Code
function JoinDemo(){
   var a, b;
   a = new Array(0,1,2,3,4);
   b = a.join("-");
   return(b);
}

Expand image Requirements

Version 2

Applies To: Array Object (JScript 5.6)

Expand image See Also

Reference

String Object (JScript 5.6)


lastIndexOf Method (JScript 5.6)

JScript
lastIndexOf Method (JScript 5.6)
See Also
CollapseAll image DropDown image

Returns the last occurrence of a substring within a String object.

strObj.lastIndexOf(substring[, startindex])

Expand image Arguments

strObj

Required. A String object or literal.

substring

Required. The substring to search for within the String object.

startindex

Optional. Integer value specifying the index to begin searching within the String object. If omitted, searching begins at the end of the string.

Expand image Remarks

The lastIndexOf method returns an integer value indicating the beginning of the substring within the String object. If the substring is not found, a -1 is returned.

If startindex is negative, startindex is treated as zero. If it is larger than the greatest character position index, it is treated as the largest possible index.

Searching is performed right to left. Otherwise, this method is identical to indexOf.

The following example illustrates the use of the lastIndexOf method.

CopyCode image Copy Code
function lastIndexDemo(str2)
{
   var str1 = "BABEBIBOBUBABEBIBOBU"
   var s = str1.lastIndexOf(str2);
   return(s);
}

Expand image Requirements

Version 1

Applies To: String Object (JScript 5.6)

Expand image See Also

Reference

indexOf Method (JScript 5.6)


lbound Method (JScript 5.6)

JScript
lbound Method (JScript 5.6)
See Also Example
CollapseAll image DropDown image

Returns the lowest index value used in the specified dimension of a VBArray.

safeArray.lbound(dimension)

Expand image Arguments

safeArray

Required. A VBArray object.

dimension

Optional. The dimension of the VBArray for which the lower bound index is wanted. If omitted, lbound behaves as if a 1 was passed.

Expand image Remarks

If the VBArray is empty, the lbound method returns undefined. If dimension is greater than the number of dimensions in the VBArray, or is negative, the method generates a "Subscript out of range" error.

Expand image Example

The following example consists of three parts. The first part is VBScript code to create a Visual Basic safe array. The second part is JScript code that determines the number of dimensions in the safe array and the lower bound of each dimension. Since the safe array is created in VBScript rather than Visual Basic, the lower bound will always be zero. Both of these parts go into the <HEAD> section of an HTML page. The third part is the JScript code that goes in the <BODY> section to run the other two parts.

CopyCode image Copy Code
<HEAD>
<SCRIPT LANGUAGE="VBScript">
<!--
Function CreateVBArray()
   Dim i, j, k
   Dim a(2, 2)
   k = 1
   For i = 0 To 2
      For j = 0 To 2
         a(j, i) = k
         k = k + 1
      Next
   Next
   CreateVBArray = a
End Function
-->
</SCRIPT>

<SCRIPT LANGUAGE="JScript">
<!--
function VBArrayTest(vba){
   var i, s;
   var a = new VBArray(vba);
   for (i = 1; i <= a.dimensions(); i++)
   {
      s = "The lower bound of dimension ";
      s += i + " is ";
      s += a.lbound(i)+ ".<BR>";
      return(s);
   }
}
-->
</SCRIPT>
</HEAD>

<BODY>
<SCRIPT language="jscript">
   document.write(VBArrayTest(CreateVBArray()));
</SCRIPT>
</BODY>

Expand image Requirements

Version 3

Applies To: VBArray Object (JScript 5.6)

Expand image See Also

Reference

dimensions Method (JScript 5.6)
getItem Method (JScript 5.6)
toArray Method (JScript 5.6)
ubound Method (JScript 5.6)


link Method (JScript 5.6)

JScript
link Method (JScript 5.6)
See Also
CollapseAll image DropDown image

Places an HTML anchor with an HREF attribute around the text in a String object.

strVariable.link(linkstring)
"String Literal".link(linkstring)

Expand image Remarks

The linkstring argument is the text that you want to place in the HREF attribute of the HTML anchor.

Call the link method to create a hyperlink out of a String object. The following is an example of how the method accomplishes this:

CopyCode image Copy Code
var strVariable = "This is a hyperlink";
strVariable = strVariable.link("http://www.microsoft.com");

The value of strVariable after the last statement is:

CopyCode image Copy Code
<A HREF="http://www.microsoft.com">This is a hyperlink</A>

No checking is done to see if the tag has already been applied to the string.

Expand image Requirements

Version 1

Applies To: String Object (JScript 5.6)

Expand image See Also

Reference

anchor Method (JScript 5.6)


localeCompare Method (JScript 5.6)

JScript
localeCompare Method (JScript 5.6)
See Also
CollapseAll image DropDown image

Returns a value indicating whether two strings are equivalent in the current locale.

stringVar.localeCompare(stringExp)

Expand image Arguments

stringVar

Required. A String object or literal.

stringExp

Required. String to compare to stringVar.

Expand image Remarks

The localeCompare performs a locale-sensitive string comparison of the stringVar and the stringExp and returns -1, 0, or +1, depending on the sort order of the system default locale.

If stringVar sorts before stringExp, localeCompare returns –1; if stringVar sorts after stringExp, +1 is returned. A return value of zero means that the two strings are equivalent.

Expand image Requirements

Version 5.5

Applies To: String Object (JScript 5.6)

Expand image See Also

Reference

toLocaleString Method (JScript 5.6)


log Method (JScript 5.6)

JScript
log Method (JScript 5.6)
See Also
CollapseAll image DropDown image

Returns the natural logarithm of a number.

Math.log(number)

Expand image Remarks

The required number argument is a numeric expression for which the natural logarithm is sought.

Expand image Return Value

The return value is the natural logarithm of number. The base is e.

Expand image Requirements

Version 1

Applies To: Math Object (JScript 5.6)

Expand image See Also

Reference

sqrt Method (JScript 5.6)


match Method (JScript 5.6)

JScript
match Method (JScript 5.6)
See Also Example
CollapseAll image DropDown image

Executes a search on a string using a regular expression pattern, and returns an array containing the results of that search.

stringObj.match(rgExp)

Expand image Arguments

stringObj

Required. The String object or string literal on which to perform the search.

rgExp

Required. An instance of a Regular Expression object containing the regular expression pattern and applicable flags. Can also be a variable name or string literal containing the regular expression pattern and flags.

Expand image Remarks

If the match method does not find a match, it returns null. If it finds a match, match returns an array, and the properties of the global RegExp object are updated to reflect the results of the match.

The array returned by the match method has three properties, input, index and lastIndex. The input property contains the entire searched string. The index property contains the position of the matched substring within the complete searched string. The lastIndex property contains the position following the last character in the last match.

If the global flag (g) is not set, Element zero of the array contains the entire match, while elements 1 – n contain any submatches that have occurred within the match. This behavior is identical to the behavior of the exec method without the global flag set. If the global flag is set, elements 0 - n contain all matches that occurred.

Expand image Example

The following example illustrates the use of the match method.

CopyCode image Copy Code
function MatchDemo(){
   var r, re;         //Declare variables.
   var s = "The rain in Spain falls mainly in the plain";
   re = /ain/i;    //Create regular expression pattern.
   r = s.match(re);   //Attempt match on search string.
   return(r);         //Return first occurrence of "ain".
}

This example illustrates the use of the match method with the g flag set.

CopyCode image Copy Code
function MatchDemo(){
   var r, re;         //Declare variables.
   var s = "The rain in Spain falls mainly in the plain";
   re = /ain/ig;      //Create regular expression pattern.
   r = s.match(re);   //Attempt match on search string.
   return(r);         //Return array containing all four
                      // occurrences of "ain".
}

The following lines of code illustrate the use of a string literal with the match method.

CopyCode image Copy Code
var r, re = "Spain";
r = "The rain in Spain".replace(re, "Canada");

Expand image Requirements

Version 3

Applies To: String Object (JScript 5.6)

Expand image See Also

Reference

exec Method (JScript 56)
RegExp Object (JScript 5.6)
replace Method (JScript 56)
search Method (JScript 5.6)
test Method (JScript 5.6)


max Method (JScript 5.6)

JScript
max Method (JScript 5.6)
See Also
CollapseAll image DropDown image

Returns the greater of zero or more supplied numeric expressions.

Math.max([number1[, number2[. . . [, numberN]]]])

Expand image Remarks

The optional number1, number2, . . ., numberN arguments are numeric expressions to be evaluated.

If no arguments are provided, the return value is equal to NEGATIVE_INFINITY. If any argument is NaN, the return value is also NaN.

Expand image Requirements

Version 1

Applies To: Math Object (JScript 5.6)

Expand image See Also

Reference

min Method (JScript 5.6)
NEGATIVE_INFINITY Property (JScript 5.6)


min Method (JScript 5.6)

JScript
min Method (JScript 5.6)
See Also
CollapseAll image DropDown image

Returns the lesser of zero or more supplied numeric expressions.

Math.min([number1[, number2[. . . [,numberN]]]])

Expand image Remarks

The optional number1, number2, . . ., numberN arguments are numeric expressions to be evaluated.

If no arguments are provided, the return value is equal to POSITIVE_INFINITY. If any argument is NaN, the return value is also NaN.

Expand image Requirements

Version 1

Applies To: Math Object (JScript 5.6)

Expand image See Also

Reference

max Method (JScript 5.6)
POSITIVE_INFINITY Property (JScript 5.6)


moveFirst Method (JScript 5.6)

JScript
moveFirst Method (JScript 5.6)
See Also Example
CollapseAll image DropDown image

Resets the current item in the collection to the first item.

enumObj.moveFirst( )

Expand image Remarks

The required enumObj reference is any Enumerator object.

If there are no items in the collection, the current item is set to undefined.

Expand image Example

In following example, the moveFirst method is used to evaluate members of the Drives collection from the beginning of the list:

CopyCode image Copy Code
function ShowFirstAvailableDrive(){
   var fso, s, e, x;                //Declare variables.
   fso = new ActiveXObject("Scripting.FileSystemObject");
   e = new Enumerator(fso.Drives);  //Create Enumerator object.
   e.moveFirst();                   //Move to first drive.
   s = "";                          //Initialize s.
   do
   {
      x = e.item();                 //Test for existence of drive.
      if (x.IsReady)                //See if it's ready.
      {
         s = x.DriveLetter + ":";   //Assign 1<SUP>st</SUP> drive letter to s.
         break;
      }
      else
         if (e.atEnd())             //See if at the end of the collection.
         {
            s = "No drives are available";
            break;
         }
      e.moveNext();                 //Move to the next drive.
   }
   while (!e.atEnd());              //Do while not at collection end.
   return(s);                       //Return list of available drives.
}

Expand image Requirements

Version 3

Applies To: Enumerator Object (JScript 5.6)

Expand image See Also

Reference

atEnd Method (JScript 5.6)
item Method (JScript 5.6)
moveNext Method (JScript 5.6)


moveNext Method (JScript 5.6)

JScript
moveNext Method (JScript 5.6)
See Also Example
CollapseAll image DropDown image

Moves the current item to the next item in the collection.

enumObj.moveNext( )

Expand image Remarks

The required enumObj reference is any Enumerator object.

If the enumerator is at the end of the collection or the collection is empty, the current item is set to undefined.

Expand image Example

In following example, the moveNext method is used to move to the next drive in the Drives collection:

CopyCode image Copy Code
function ShowDriveList(){
   var fso, s, n, e, x;                 //Declare variables.
   fso = new ActiveXObject("Scripting.FileSystemObject");
   e = new Enumerator(fso.Drives);      //Create Enumerator object.
   s = "";                              //Initialize s.
   for (; !e.atEnd(); e.moveNext())
   {
      x = e.item();
      s = s + x.DriveLetter;            //Add drive letter
      s += " - ";                       //Add "-" character.
      if (x.DriveType == 3)
         n = x.ShareName;               //Add share name.
      else if (x.IsReady)
         n = x.VolumeName;              //Add volume name.
      else
         n = "[Drive not ready]";       //Indicate drive not ready.
      s +=   n + "\n";
   }
   return(s);                           //Return drive status.
}

Expand image Requirements

Version 3

Applies To: Enumerator Object (JScript 5.6)

Expand image See Also

Reference

atEnd Method (JScript 5.6)
item Method (JScript 5.6)
moveFirst Method (JScript 5.6)


parse Method (JScript 5.6)

JScript
parse Method (JScript 5.6)
See Also Example
CollapseAll image DropDown image

Parses a string containing a date, and returns the number of milliseconds between that date and midnight, January 1, 1970.

Date.parse(dateVal)

Expand image Remarks

The required dateVal argument is either a string containing a date in a format such as "Jan 5, 1996 08:47:00" or a VT_DATE value retrieved from an ActiveX® object or other object.

The parse method returns an integer value representing the number of milliseconds between midnight, January 1, 1970 and the date supplied in dateVal.

The parse method is a static method of the Date object. Because it is a static method, it is invoked as shown in the following example, rather than invoked as a method of a created Date object.

CopyCode image Copy Code
var datestring = "November 1, 1997 10:15 AM";
Date.parse(datestring)

The following rules govern what the parse method can successfully parse:

  • Short dates can use either a "/" or "-" date separator, but must follow the month/day/year format, for example "7/20/96".

  • Long dates of the form "July 10 1995" can be given with the year, month, and day in any order, and the year in 2-digit or 4-digit form. If you use the 2-digit form, the year must be greater than or equal to 70.

  • Any text inside parentheses is treated as a comment. These parentheses may be nested.

  • Both commas and spaces are treated as delimiters. Multiple delimiters are permitted.

  • Month and day names must have two or more characters. Two character names that are not unique are resolved as the last match. For example, "Ju" is resolved as July, not June.

  • The stated day of the week is ignored if it is incorrect given the remainder of the supplied date. For example, "Tuesday November 9 1996" is accepted and parsed even though that date actually falls on a Friday. The resulting Date object contains "Friday November 9 1996".

  • JScript handles all standard time zones, as well as Universal Coordinated Time (UTC) and Greenwich Mean Time (GMT).

  • Hours, minutes, and seconds are separated by colons, although all need not be specified. "10:", "10:11", and "10:11:12" are all valid.

  • If the 24-hour clock is used, it is an error to specify "PM" for times later than 12 noon. For example, "23:15 PM" is an error.

  • A string containing an invalid date is an error. For example, a string containing two years or two months is an error.

Expand image Example

The following example illustrates the use of the parse method. Provide the function with a date and the function will return the difference between the date provided and 1/1/1970:

CopyCode image Copy Code
function GetTimeTest(testdate){
   var s, t;                    //Declare variables.
   var MinMilli = 1000 * 60;       //Initialize variables.
   var HrMilli = MinMilli * 60;
   var DyMilli = HrMilli * 24;
   t = Date.parse(testdate);       //Parse testdate.
   s = "There are "                //Create return string.
   s += Math.round(Math.abs(t / DyMilli)) + " days "
   s += "between " + testdate + " and 1/1/70";
   return(s);                      //Return results.
}

Expand image Requirements

Version 1

Applies To: Date Object (JScript 5.6)

Expand image See Also

Reference

getDate Method (JScript 5.6)


parseFloat Method (JScript 5.6)

JScript
parseFloat Method (JScript 5.6)
See Also
CollapseAll image DropDown image

Returns a floating-point number converted from a string.

parseFloat(numString)

Expand image Remarks

The required numString argument is a string that contains a floating-point number.

The parseFloat method returns a numerical value equal to the number contained in numString. If no prefix of numString can be successfully parsed into a floating-point number, NaN (not a number) is returned.

CopyCode image Copy Code
        parseFloat("abc")      // Returns NaN.
parseFloat("1.2abc")   // Returns 1.2.

You can test for NaN using the isNaN method.

Expand image Requirements

Version 1

Applies To: Global Object (JScript 5.6)

Expand image See Also

Reference

isNaN Method (JScript 5.6)
parseInt Method (JScript 5.6)
String Object (JScript 5.6)


parseInt Method (JScript 5.6)

JScript
parseInt Method (JScript 5.6)
See Also
CollapseAll image DropDown image

Returns an integer converted from a string.

parseInt(numString, [radix])

Expand image Arguments

numString

Required. A string to convert into a number.

radix

Optional. A value between 2 and 36 indicating the base of the number contained in numString. If not supplied, strings with a prefix of '0x' are considered hexadecimal and strings with a prefix of '0' are considered octal. All other strings are considered decimal.

Expand image Remarks

The parseInt method returns an integer value equal to the number contained in numString. If no prefix of numString can be successfully parsed into an integer, NaN (not a number) is returned.

CopyCode image Copy Code
        parseInt("abc")     // Returns NaN.
parseInt("12abc")   // Returns 12.

You can test for NaN using the isNaN method.

Expand image Requirements

Version 1

Applies To: Global Object (JScript 5.6)

Expand image See Also

Reference

isNaN Method (JScript 5.6)
parseFloat Method (JScript 5.6)
String Object (JScript 5.6)
valueOf Method (JScript 5.6)


pop Method (JScript 5.6)

JScript
pop Method (JScript 5.6)
See Also
CollapseAll image DropDown image

Removes the last element from an array and returns it.

arrayObj.pop( )

Expand image Remarks

The required arrayObj reference is an Array object.

If the array is empty, undefined is returned.

Expand image Requirements

Version 5.5

Applies To: Array Object (JScript 5.6)

Expand image See Also

Reference

push Method (JScript 5.6)


pow Method (JScript 5.6)

JScript
pow Method (JScript 5.6)
See Also Example
CollapseAll image DropDown image

Returns the value of a base expression taken to a specified power.

Math.pow(base, exponent)

Expand image Arguments

base

Required. The base value of the expression.

exponent

Required. The exponent value of the expression.

Expand image Example

In the following example, a numeric expression equal to baseexponent returns 1000.

CopyCode image Copy Code
Math.pow(10,3);

Expand image Requirements

Version 1

Applies To: Math Object (JScript 5.6)

Expand image See Also

Reference

acos Method (JScript 5.6)


push Method (JScript 5.6)

JScript
push Method (JScript 5.6)
See Also
CollapseAll image DropDown image

Appends new elements to an array, and returns the new length of the array.

arrayObj.push([item1 [item2 [. . . [itemN ]]]])

Expand image Arguments

arrayObj

Required. An Array object.

item, item2,. . ., itemN

Optional. New elements of the Array.

Expand image Remarks

The push method appends elements in the order in which they appear. If one of the arguments is an array, it is added as a single element. Use the concat method to join the elements from two or more arrays.

Expand image Requirements

Version 5.5

Applies To: Array Object (JScript 5.6)

Expand image See Also

Reference

concat Method (Array) (JScript 5.6)
pop Method (JScript 5.6)


random Method (JScript 5.6)

JScript
random Method (JScript 5.6)
See Also
CollapseAll image DropDown image

Returns a pseudorandom number between 0 and 1.

Math.random( )

Expand image Remarks

The pseudorandom number generated is from 0 (inclusive) to 1 (exclusive), that is, the returned number can be zero, but it will always be less than one. The random number generator is seeded automatically when JScript is first loaded.

Expand image Requirements

Version 1

Applies To: Math Object (JScript 5.6)

Expand image See Also

Reference

pow Method (JScript 5.6)


replace Method (JScript 56)

JScript
replace Method (JScript 56)
See Also Example
CollapseAll image DropDown image

Returns a copy of a string with text replaced using a regular expression or search string.

stringObj.replace(rgExp, replaceText)

Expand image Arguments

stringObj

Required. The String object or string literal on which to perform the replacement. This string is not modified by the replace method.

rgExp

Required. An instance of a Regular Expression object containing the regular expression pattern and applicable flags. Can also be a String object or literal. If rgExp is not an instance of a Regular Expression object, it is converted to a string, and an exact search is made for the results; no attempt is made to convert the string into a regular expression.

replaceText

Required. A String object or string literal containing the text to replace for every successful match of rgExp in stringObj. In JScript 5.5 or later, the replaceText argument can also be a function that returns the replacement text.

Expand image Remarks

The result of the replace method is a copy of stringObj after the specified replacements have been made.

Any of the following match variables can be used to identify the most recent match and the string from which it came. The match variables can be used in text replacement where the replacement string has to be determined dynamically.

Characters | Meaning
$$ | $ (JScript 5.5 or later)
$& | Specifies that portion of stringObj that the entire pattern matched. (JScript 5.5 or later)
$` | Specifies that portion of stringObj that precedes the match described by $&. (JScript 5.5 or later)
$' | Specifies that portion of stringObj that follows the match described by $&. (JScript 5.5 or later)
$ n | The nth captured submatch, where n is a single decimal digit from 1 through 9. (JScript 5.5 or later)
$ nn | The nnth captured submatch, where nn is a two-digit decimal number from 01 through 99. (JScript 5.5 or later)

If replaceText is a function, for each matched substring the function is called with the following m + 3 arguments where m is the number of left capturing parentheses in the rgExp. The first argument is the substring that matched. The next m arguments are all of the captures that resulted from the search. Argument m + 2 is the offset within stringObj where the match occurred, and argument m + 3 is stringObj. The result is the string value that results from replacing each matched substring with the corresponding return value of the function call.

The replace method updates the properties of the global RegExp object.

Expand image Example

The following example illustrates the use of the replace method to replace the first instance of the word "The" with the word "A."

CopyCode image Copy Code
function ReplaceDemo(){
   var r, re;                    //Declare variables.
   var ss = "The man hit the ball with the bat.\n";
   ss += "while the fielder caught the ball with the glove.";
   re = /The/g;             //Create regular expression pattern.
   r = ss.replace(re, "A");    //Replace "The" with "A".
   return(r);                   //Return string with replacement made.
}

In addition, the replace method can also replace subexpressions in the pattern. The following example swaps each pair of words in the string.

CopyCode image Copy Code
function ReplaceDemo(){
   var r, re;                      //Declare variables.
   var ss = "The rain in Spain falls mainly in the plain.";
   re = /(\S+)(\s+)(\S+)/g;        //Create regular expression pattern.
   r = ss.replace(re, "$3$2$1");   //Swap each pair of words.
   return(r);                      //Return resulting string.
}

The following example, which works in JScript 5.5 and later, performs a Fahrenheit to Celsius conversion, illustrates using a function as replaceText. To see how this function works, pass in a string containing a number followed immediately by an "F" (e.g., "Water boils at 212").

CopyCode image Copy Code
function f2c(s) {
  var test = /(\d+(\.\d*)?)F\b/g;    //Initialize pattern.
  return(s.replace
    (test,
      function($0,$1,$2) {
        return((($1-32) * 5/9) + "C");
      }
    )
  );
}
document.write(f2c("Water freezes at 32F and boils at 212F."));

Expand image Requirements

Version 1

Applies To: String Object (JScript 5.6)

Expand image See Also

Reference

exec Method (JScript 56)
match Method (JScript 5.6)
RegExp Object (JScript 5.6)
search Method (JScript 5.6)
test Method (JScript 5.6)


reverse Method (JScript 5.6)

JScript
reverse Method (JScript 5.6)
See Also Example
CollapseAll image DropDown image

Returns an Array object with the elements reversed.

arrayObj.reverse( )

Expand image Remarks

The required arrayObj reference is an Array object.

The reverse method reverses the elements of an Array object in place. It does not create a new Array object during execution.

If the array is not contiguous, the reverse method creates elements in the array that fill the gaps in the array. Each of these created elements has the value undefined.

Expand image Example

The following example illustrates the use of the reverse method.

CopyCode image Copy Code
function ReverseDemo(){
   var a, l;                  //Declare variables.
   a = new Array(0,1,2,3,4);  //Create an array and populate it.
   l = a.reverse();           //Reverse the contents of the array.
   return(l);                 //Return the resulting array.
}

Expand image Requirements

Version 2

Applies To: Array Object (JScript 5.6)

Expand image See Also

Reference

concat Method (Array) (JScript 5.6)


round Method (JScript 5.6)

JScript
round Method (JScript 5.6)
See Also
CollapseAll image DropDown image

Returns a supplied numeric expression rounded to the nearest integer.

Math.round(number)

Expand image Remarks

The required number argument is the value to be rounded to the nearest integer.

If the decimal portion of number is 0.5 or greater, the return value is equal to the smallest integer greater than number. Otherwise, round returns the largest integer less than or equal to number.

Expand image Requirements

Version 1

Applies To: Math Object (JScript 5.6)

Expand image See Also

Reference

random Method (JScript 5.6)


search Method (JScript 5.6)

JScript
search Method (JScript 5.6)
See Also Example
CollapseAll image DropDown image

Returns the position of the first substring match in a regular expression search.

stringObj.search(rgExp)

Expand image Arguments

stringObj

Required. The String object or string literal on which to perform the search.

rgExp

Required. An instance of a Regular Expression object containing the regular expression pattern and applicable flags.

Expand image Remarks

The search method indicates if a match is present or not. If a match is found, the search method returns an integer value that indicates the offset from the beginning of the string where the match occurred. If no match is found, it returns -1.

Expand image Example

The following example illustrates the use of the search method.
CopyCode image Copy Code
function SearchDemo(){
   var r, re;                   //Declare variables.
   var s = "The rain in Spain falls mainly in the plain.";
   re = /falls/i;            //Create regular expression pattern.
   r = s.search(re);            //Search the string.
   return(r);                   //Return the Boolean result.
}

Expand image Requirements

Version 3

Applies To: String Object (JScript 5.6)

Expand image See Also

Reference

exec Method (JScript 56)
match Method (JScript 5.6)
Regular Expression Object (JScript 5.6)
Regular Expression Syntax (Scripting)
replace Method (JScript 56)
test Method (JScript 5.6)


setDate Method (JScript 5.6)

JScript
setDate Method (JScript 5.6)
See Also Example
CollapseAll image DropDown image

Sets the numeric date of the Date object using local time.

dateObj.setDate(numDate)

Expand image Arguments

dateObj

Required. Any Date object.

numDate

Required. A numeric value equal to the numeric date.

Expand image Remarks

To set the date value using Universal Coordinated Time (UTC), use the setUTCDate method.

If the value of numDate is greater than the number of days in the month stored in the Date object or is a negative number, the date is set to a date equal to numDate minus the number of days in the stored month. For example, if the stored date is January 5, 1996, and setDate(32) is called, the date changes to February 1, 1996. Negative numbers have a similar behavior.

Expand image Example

The following example illustrates the use of the setDate method.

CopyCode image Copy Code
function SetDateDemo(newdate){
   var d, s;                  //Declare variables.
   d = new Date();            //Create date object.
   d.setDate(newdate);        //Set date to newdate.
   s = "Current setting is ";
   s += d.toLocaleString();
   return(s);                 //Return newly set date.
}

Expand image Requirements

Version 3

Applies To: Date Object (JScript 5.6)

Expand image See Also

Reference

getDate Method (JScript 5.6)
getUTCDate Method (JScript 5.6)
setUTCDate Method (JScript 5.6)


setFullYear Method (JScript 5.6)

JScript
setFullYear Method (JScript 5.6)
See Also Example
CollapseAll image DropDown image

Sets the year value in the Date object using local time.

dateObj.setFullYear(numYear[, numMonth[, numDate]])

Expand image Arguments

dateObj

Required. Any Date object.

numYear

Required. A numeric value equal to the year.

numMonth

Optional. A numeric value equal to the month. Must be supplied if numDate is supplied.

numDate

Optional. A numeric value equal to the date.

Expand image Remarks

All set methods taking optional arguments use the value returned from corresponding get methods, if you do not specify the optional argument. For example, if the numMonth argument is optional, but not specified, JScript uses the value returned from the getMonth method.

In addition, if the value of an argument is greater than its range or is a negative number, other stored values are modified accordingly.

To set the year using Universal Coordinated Time (UTC), use the setUTCFullYear method.

The range of years supported in the date object is approximately 285,616 years from either side of 1970.

Expand image Example

The following example illustrates the use of the setFullYear method:

CopyCode image Copy Code
function SetFullYearDemo(newyear){
   var d, s;                 //Declare variables.
   d = new Date();           //Create Date object.
   d.setFullYear(newyear);   //Set year.
   s = "Current setting is ";
   s += d.toLocaleString();
   return(s);                //Return new date setting.
}

Expand image Requirements

Version 3

Applies To: Date Object (JScript 5.6)

Expand image See Also

Reference

getFullYear Method (JScript 5.6)
getUTCFullYear Method (JScript 5.6)
setUTCFullYear Method (JScript 5.6)


setHours Method (JScript 5.6)

JScript
setHours Method (JScript 5.6)
See Also Example
CollapseAll image DropDown image

Sets the hour value in the Date object using local time.

dateObj.setHours(numHours[, numMin[, numSec[, numMilli]]])

Expand image Arguments

dateObj

Required. Any Date object.

numHours

Required. A numeric value equal to the hours value.

numMin

Optional. A numeric value equal to the minutes value. Must be supplied if either of the following arguments is used.

numSec

Optional. A numeric value equal to the seconds value. Must be supplied if the following argument is used.

numMilli

Optional. A numeric value equal to the milliseconds value.

Expand image Remarks

All set methods taking optional arguments use the value returned from corresponding get methods, if you do not specify an optional argument. For example, if the numMinutes argument is optional, but not specified, JScript uses the value returned from the getMinutes method.

To set the hours value using Universal Coordinated Time (UTC), use the setUTCHours method.

If the value of an argument is greater than its range or is a negative number, other stored values are modified accordingly. For example, if the stored date is "Jan 5, 1996 00:00:00", and setHours(30) is called, the date is changed to "Jan 6, 1996 06:00:00." Negative numbers have a similar behavior.

Expand image Example

The following example illustrates the use of the setHours method.

CopyCode image Copy Code
function SetHoursDemo(nhr, nmin, nsec){
   var d, s;                     //Declare variables.
   d = new Date();               //Create Date object.
   d.setHours(nhr, nmin, nsec);  //Set hours, minutes, & seconds.
   s = "Current setting is " + d.toLocaleString()
   return(s);                    //Return new date setting.
}

Expand image Requirements

Version 3

Applies To: Date Object (JScript 5.6)

Expand image See Also

Reference

getHours Method (JScript 5.6)
getUTCHours Method (JScript 5.6)
setUTCHours Method (JScript 5.6)


setMilliseconds Method (JScript 5.6)

JScript
setMilliseconds Method (JScript 5.6)
See Also Example
CollapseAll image DropDown image

Sets the milliseconds value in the Date object using local time.

dateObj.setMilliseconds(numMilli)

Expand image Arguments

dateObj

Required. Any Date object.

numMilli

Required. A numeric value equal to the millisecond value.

Expand image Remarks

To set the milliseconds value using Universal Coordinated Time (UTC), use the setUTCMilliseconds method.

If the value of numMilli is greater than 999 or is a negative number, the stored number of seconds (and minutes, hours, and so forth if necessary) is incremented an appropriate amount.

Expand image Example

The following example illustrates the use of the setMilliseconds method.

CopyCode image Copy Code
function SetMSecDemo(nmsec){
   var d, s;                    //Declare variables.
   var sep = ":";               //Initialize separator.
   d = new Date();              //Create Date object.
   d.setMilliseconds(nmsec);    //Set milliseconds.
   s = "Current setting is ";
   s += d.toLocaleString() + sep + d.getMilliseconds();
   return(s);                   //Return new date setting.
}

Expand image Requirements

Version 3

Applies To: Date Object (JScript 5.6)

Expand image See Also

Reference

getMilliseconds Method (JScript 5.6)
getUTCMilliseconds Method (JScript 5.6)
setUTCMilliseconds Method (JScript 5.6)


setMinutes Method (JScript 5.6)

JScript
setMinutes Method (JScript 5.6)
See Also Example
CollapseAll image DropDown image

Sets the minutes value in the Date object using local time.

dateObj.setMinutes(numMinutes[, numSeconds[, numMilli]])

Expand image Arguments

dateObj

Required. Any Date object.

numMinutes

Required. A numeric value equal to the minutes value.

numSeconds

Optional. A numeric value equal to the seconds value. Must be supplied if the numMilli argument is used.

numMilli

Optional. A numeric value equal to the milliseconds value.

Expand image Remarks

All set methods taking optional arguments use the value returned from corresponding get methods, if you do not specify an optional argument. For example, if the numSeconds argument is optional, but not specified, JScript uses the value returned from the getSeconds method.

To set the minutes value using Universal Coordinated Time (UTC), use the setUTCMinutes method.

If the value of an argument is greater than its range or is a negative number, other stored values are modified accordingly. For example, if the stored date is "Jan 5, 1996 00:00:00" and setMinutes(90) is called, the date is changed to "Jan 5, 1996 01:30:00." Negative numbers have a similar behavior.

Expand image Example

The following example illustrates the use of the setMinutes method.

CopyCode image Copy Code
function SetMinutesDemo(nmin, nsec){
   var d, s;                     //Declare variables.
   d = new Date();               //Create Date object.
   d.setMinutes(nmin, nsec);     //Set minutes.
   s = "Current setting is " + d.toLocaleString()
   return(s);                    //Return new setting.
}

Expand image Requirements

Version 1

Applies To: Date Object (JScript 5.6)

Expand image See Also

Reference

getMinutes Method (JScript 5.6)
getUTCMinutes Method (JScript 5.6)
setUTCMinutes Method (JScript 5.6)


setMonth Method (JScript 5.6)

JScript
setMonth Method (JScript 5.6)
See Also Example
CollapseAll image DropDown image

Sets the month value in the Date object using local time.

dateObj.setMonth(numMonth[, dateVal])

Expand image Arguments

dateObj

Required. Any Date object.

numMonth

Required. A numeric value equal to the month.

dateVal

Optional. A numeric value representing the date. If not supplied, the value from a call to the getDate method is used.

Expand image Remarks

To set the month value using Universal Coordinated Time (UTC), use the setUTCMonth method.

If the value of numMonth is greater than 11 (January is month 0) or is a negative number, the stored year is modified accordingly. For example, if the stored date is "Jan 5, 1996" and setMonth(14) is called, the date is changed to "Mar 5, 1997."

Expand image Example

The following example illustrates the use of the setMonth method.

CopyCode image Copy Code
function SetMonthDemo(newmonth){
   var d, s;               //Declare variables.
   d = new Date();         //Create Date object.
   d.setMonth(newmonth);   //Set month.
   s = "Current setting is ";
   s += d.toLocaleString();
   return(s);              //Return new setting.
}

Expand image Requirements

Version 1

Applies To: Date Object (JScript 5.6)

Expand image See Also

Reference

getMonth Method (JScript 5.6)
getUTCMonth Method (JScript 5.6)
setUTCMonth Method (JScript 5.6)


setSeconds Method (JScript 5.6)

JScript
setSeconds Method (JScript 5.6)
See Also Example
CollapseAll image DropDown image

Sets the seconds value in the Date object using local time.

dateObj.setSeconds(numSeconds[, numMilli])

Expand image Arguments

dateObj

Required. Any Date object.

numSeconds

Required. A numeric value equal to the seconds value.

numMilli

Optional. A numeric value equal to the milliseconds value.

Expand image Remarks

All set methods taking optional arguments use the value returned from corresponding get methods, if you do not specify an optional argument. For example, if the numMilli argument is optional, but not specified, JScript uses the value returned from the getMilliseconds method.

To set the seconds value using Universal Coordinated Time (UTC), use the setUTCSeconds method.

If the value of an argument is greater than its range or is a negative number, other stored values are modified accordingly. For example, if the stored date is "Jan 5, 1996 00:00:00" and setSeconds(150) is called, the date is changed to "Jan 5, 1996 00:02:30."

Expand image Example

The following example illustrates the use of the setSeconds method.

CopyCode image Copy Code
function SetSecondsDemo(nsec, nmsec){
   var d, s;                   //Declare variables.
   var sep = ":";
   d = new Date();             //Create Date object.
   d.setSeconds(nsec, nmsec);  //Set seconds and milliseconds.
   s = "Current setting is ";
   s += d.toLocaleString() + sep + d.getMilliseconds();
   return(s);                  //Return new setting.
}

Expand image Requirements

Version 1

Applies To: Date Object (JScript 5.6)

Expand image See Also

Reference

getSeconds Method (JScript 5.6)
getUTCSeconds Method (JScript 5.6)
setUTCSeconds Method (JScript 5.6)


setTime Method (JScript 5.6)

JScript
setTime Method (JScript 5.6)
See Also Example
CollapseAll image DropDown image

Sets the date and time value in the Date object.

dateObj.setTime(milliseconds)

Expand image Arguments

dateObj

Required. Any Date object.

milliseconds

Required. A numeric value representing the number of elapsed milliseconds since midnight, January 1, 1970 GMT.

Expand image Remarks

If milliseconds is negative, it indicates a date before 1970. The range of available dates is approximately 285,616 years from either side of 1970.

Setting the date and time with the setTime method is independent of the time zone.

Expand image Example

The following example illustrates the use of the setTime method.

CopyCode image Copy Code
function SetTimeTest(newtime){
   var d, s;                  //Declare variables.
   d = new Date();            //Create Date object.
   d.setTime(newtime);        //Set time.
   s = "Current setting is ";
   s += d.toUTCString();
   return(s);                 //Return new setting.
}

Expand image Requirements

Version 1

Applies To: Date Object (JScript 5.6)

Expand image See Also

Reference

getTime Method (JScript 5.6)


setUTCDate Method (JScript 5.6)

JScript
setUTCDate Method (JScript 5.6)
See Also Example
CollapseAll image DropDown image

Sets the numeric date in the Date object using Universal Coordinated Time (UTC).

dateObj.setUTCDate(numDate)

Expand image Arguments

dateObj

Required. Any Date object.

numDate

Required. A numeric value equal to the numeric date.

Expand image Remarks

To set the date using local time, use the setDate method.

If the value of numDate is greater than the number of days in the month stored in the Date object or is a negative number, the date is set to a date equal to numDate minus the number of days in the stored month. For example, if the stored date is January 5, 1996, and setUTCDate(32) is called, the date changes to February 1, 1996. Negative numbers have a similar behavior.

Expand image Example

The following example illustrates the use of the setUTCDate method.

CopyCode image Copy Code
function SetUTCDateDemo(newdate){
   var d, s;                   //Declare variables.
   d = new Date();             //Create Date object.
   d.setUTCDate(newdate);      //Set UTC date.
   s = "Current setting is ";
   s += d.toUTCString();
   return(s);                  //Return new setting.
}

Expand image Requirements

Version 3

Applies To: Date Object (JScript 5.6)

Expand image See Also

Reference

getDate Method (JScript 5.6)
getUTCDate Method (JScript 5.6)
setDate Method (JScript 5.6)


setUTCFullYear Method (JScript 5.6)

JScript
setUTCFullYear Method (JScript 5.6)
See Also Example
CollapseAll image DropDown image

Sets the year value in the Date object using Universal Coordinated Time (UTC).

dateObj.setUTCFullYear(numYear[, numMonth[, numDate]])

Expand image Arguments

dateObj

Required. Any Date object.

numYear

Required. A numeric value equal to the year.

numMonth

Optional. A numeric value equal to the month. Must be supplied if numDate is supplied.

numDate

Optional. A numeric value equal to the date.

Expand image Remarks

All set methods taking optional arguments use the value returned from corresponding get methods, if you do not specify an optional argument. For example, if the numMonth argument is optional, but not specified, JScript uses the value returned from the getUTCMonth method.

In addition, if the value of an argument is greater that its range or is a negative number, other stored values are modified accordingly.

To set the year using local time, use the setFullYear method.

The range of years supported in the Date object is approximately 285,616 years from either side of 1970.

Expand image Example

The following example illustrates the use of the setUTCFullYear method.

CopyCode image Copy Code
function SetUTCFullYearDemo(newyear){
   var d, s;                   //Declare variables.
   d = new Date();             //Create Date object.
   d.setUTCFullYear(newyear);  //Set UTC full year.
   s = "Current setting is ";
   s += d.toUTCString();
   return(s);                  //Return new setting.
}

Expand image Requirements

Version 3

Applies To: Date Object (JScript 5.6)

Expand image See Also

Reference

getFullYear Method (JScript 5.6)
getUTCFullYear Method (JScript 5.6)
setFullYear Method (JScript 5.6)


setUTCHours Method (JScript 5.6)

JScript
setUTCHours Method (JScript 5.6)
See Also Example
CollapseAll image DropDown image

Sets the hours value in the Date object using Universal Coordinated Time (UTC).

dateObj.setUTCHours(numHours[, numMin[, numSec[, numMilli]]])

Expand image Arguments

dateObj

Required. Any Date object.

numHours

Required. A numeric value equal to the hours value.

numMin

Optional. A numeric value equal to the minutes value. Must be supplied if either numSec or numMilli are used.

numSec

Optional. A numeric value equal to the seconds value. Must be supplied if numMilli argument is used.

numMilli

Optional. A numeric value equal to the milliseconds value.

Expand image Remarks

All set methods taking optional arguments use the value returned from corresponding get methods, if you do not specify an optional argument. For example, if the numMin argument is optional, but not specified, JScript uses the value returned from the getUTCMinutes method.

To set the hours value using local time, use the setHours method.

If the value of an argument is greater than its range, or is a negative number, other stored values are modified accordingly. For example, if the stored date is "Jan 5, 1996 00:00:00.00", and setUTCHours(30) is called, the date is changed to "Jan 6, 1996 06:00:00.00."

Expand image Example

The following example illustrates the use of the setUTCHours method.

CopyCode image Copy Code
function SetUTCHoursDemo(nhr, nmin, nsec){
   var d, s;                        //Declare variables.
   d = new Date();                  //Create Date object.
   d.setUTCHours(nhr, nmin, nsec);  //Set UTC hours, minutes, seconds.
   s = "Current setting is " + d.toUTCString()
   return(s);                       //Return new setting.
}

Expand image Requirements

Version 3

Applies To: Date Object (JScript 5.6)

Expand image See Also

Reference

getHours Method (JScript 5.6)
getUTCHours Method (JScript 5.6)
setHours Method (JScript 5.6)


setUTCMilliseconds Method (JScript 5.6)

JScript
setUTCMilliseconds Method (JScript 5.6)
See Also Example
CollapseAll image DropDown image

Sets the milliseconds value in the Date object using Universal Coordinated Time (UTC).

dateObj.setUTCMilliseconds(numMilli)

Expand image Arguments

dateObj

Required. Any Date object.

numMilli

Required. A numeric value equal to the millisecond value.

Expand image Remarks

To set the milliseconds using local time, use the setMilliseconds method.

If the value of numMilli is greater than 999, or is a negative number, the stored number of seconds (and minutes, hours, and so forth, if necessary) is incremented an appropriate amount.

Expand image Example

The following example illustrates the use of the setUTCMilliseconds method.

CopyCode image Copy Code
function SetUTCMSecDemo(nmsec){
   var d, s;                           //Declare variables.
   var sep = ":";                      //Initialize separator.
   d = new Date();                     //Create Date object.
   d.setUTCMilliseconds(nmsec);        //Set UTC milliseconds.
   s = "Current setting is ";
   s += d.toUTCString() + sep + d.getUTCMilliseconds();
   return(s);                          //Return new setting.
}

Expand image Requirements

Version 3

Applies To: Date Object (JScript 5.6)

Expand image See Also

Reference

getMilliseconds Method (JScript 5.6)
getUTCMilliseconds Method (JScript 5.6)
setMilliseconds Method (JScript 5.6)


setUTCMinutes Method (JScript 5.6)

JScript
setUTCMinutes Method (JScript 5.6)
See Also Example
CollapseAll image DropDown image

Sets the minutes value in the Date object using Universal Coordinated Time (UTC).

dateObj.setUTCMinutes(numMinutes[, numSeconds[, numMilli]])

Expand image Arguments

dateObj

Required. Any Date object.

numMinutes

Required. A numeric value equal to the minutes value.

numSeconds

Optional. A numeric value equal to the seconds value. Must be supplied if numMilli is used.

numMilli

Optional. A numeric value equal to the milliseconds value.

Expand image Remarks

All set methods taking optional arguments use the value returned from corresponding get methods, if you do not specify an optional argument. For example, if the numSeconds argument is optional, but not specified, JScript uses the value returned from the getUTCSeconds method.

To modify the minutes value using local time, use the setMinutes method.

If the value of an argument is greater than its range, or is a negative number, other stored values are modified accordingly. For example, if the stored date is "Jan 5, 1996 00:00:00.00", and setUTCMinutes(70) is called, the date is changed to "Jan 5, 1996 01:10:00.00."

Expand image Example

The following example illustrates the use of the setUTCMinutes method:

CopyCode image Copy Code
function SetUTCMinutesDemo(nmin, nsec){
   var d, s;                    //Declare variables.
   d = new Date();              //Create Date object.
   d.setUTCMinutes(nmin,nsec);  //Set UTC minutes.
   s = "Current setting is " + d.toUTCString()
   return(s);                   //Return new setting.
}

Expand image Requirements

Version 3

Applies To: Date Object (JScript 5.6)

Expand image See Also

Reference

getMinutes Method (JScript 5.6)
getUTCMinutes Method (JScript 5.6)
setMinutes Method (JScript 5.6)


setUTCMonth Method (JScript 5.6)

JScript
setUTCMonth Method (JScript 5.6)
See Also Example
CollapseAll image DropDown image

Sets the month value in the Date object using Universal Coordinated Time (UTC).

dateObj.setUTCMonth(numMonth[, dateVal])

Expand image Arguments

dateObj

Required. Any Date object.

numMonth

Required. A numeric value equal to the month.

dateVal

Optional. A numeric value representing the date. If not supplied, the value from a call to the getUTCDate method is used.

Expand image Remarks

To set the month value using local time, use the setMonth method.

If the value of numMonth is greater than 11 (January is month 0), or is a negative number, the stored year is incremented or decremented appropriately. For example, if the stored date is "Jan 5, 1996 00:00:00.00", and setUTCMonth(14) is called, the date is changed to "Mar 5, 1997 00:00:00.00."

Expand image Example

The following example illustrates the use of the setUTCMonth method.

CopyCode image Copy Code
function SetUTCMonthDemo(newmonth){
   var d, s;                       //Declare variables.
   d = new Date();                 //Create Date object.
   d.setUTCMonth(newmonth);        //Set UTC month.
   s = "Current setting is ";
   s += d.toUTCString();
   return(s);                      //Return new setting.
}

Expand image Requirements

Version 3

Applies To: Date Object (JScript 5.6)

Expand image See Also

Reference

getMonth Method (JScript 5.6)
getUTCMonth Method (JScript 5.6)
setMonth Method (JScript 5.6)


setUTCSeconds Method (JScript 5.6)

JScript
setUTCSeconds Method (JScript 5.6)
See Also Example
CollapseAll image DropDown image

Sets the seconds value in the Date object using Universal Coordinated Time (UTC).

dateObj.setUTCSeconds(numSeconds[, numMilli])

Expand image Arguments

dateObj

Required. Any Date object.

numSeconds

Required. A numeric value equal to the seconds value.

numMilli

Optional. A numeric value equal to the milliseconds value.

Expand image Remarks

All set methods taking optional arguments use the value returned from corresponding get methods, if you do not specify an optional argument. For example, if the numMilli argument is optional, but not specified, JScript uses the value returned from the getUTCMilliseconds method.

To set the seconds value using local time, use the setSeconds method.

If the value of an argument is greater than its range or is a negative number, other stored values are modified accordingly. For example, if the stored date is "Jan 5, 1996 00:00:00.00" and setSeconds(150) is called, the date is changed to "Jan 5, 1996 00:02:30.00."

Expand image Example

The following example illustrates the use of the setSeconds method.

CopyCode image Copy Code
function SetUTCSecondsDemo(nsec, nmsec){
   var d, s;                       //Declare variables.
   d = new Date();                 //Create Date object.
   d.setUTCSeconds(nsec, nmsec);   //Set UTC seconds and milliseconds.
   s = "Current UTC milliseconds setting is ";
   s += d.getUTCMilliseconds();    //Get new setting.
   return(s);                      //Return new setting.
}

Expand image Requirements

Version 3

Applies To: Date Object (JScript 5.6)

Expand image See Also

Reference

getSeconds Method (JScript 5.6)
getUTCSeconds Method (JScript 5.6)
setSeconds Method (JScript 5.6)


setYear Method (JScript 5.6)

JScript
setYear Method (JScript 5.6)
See Also
CollapseAll image DropDown image

Sets the year value in the Date object.

dateObj.setYear(numYear)

Expand image Arguments

dateObj

Required. Any Date object.

numYear

Required. A numeric value equal to the year minus 1900.

Expand image Remarks

This method is obsolete, and is maintained for backwards compatibility only. Use the setFullYear method instead.

To set the year of a Date object to 1997, call setYear(97). To set the year to 2010, call setYear(2010). Finally, to set the year to a year in the range 0-99, use the setFullYear method.

Note Note

For JScript version 1.0, setYear uses a value that is the result of the addition of 1900 to the year value provided by numYear, regardless of the value of the year. For example, to set the year to 1899 numYear is -1 and to set the year 2000 numYear is 100.

Expand image Requirements

Version 1

Applies To: Date Object (JScript 5.6)

Expand image See Also

Reference

getFullYear Method (JScript 5.6)
getUTCFullYear Method (JScript 5.6)
getYear Method (JScript 5.6)
setFullYear Method (JScript 5.6)
setUTCFullYear Method (JScript 5.6)


shift Method (JScript 5.6)

JScript
shift Method (JScript 5.6)
See Also
CollapseAll image DropDown image

Removes the first element from an array and returns it.

arrayObj.shift( )

Expand image Remarks

The required arrayObj reference is an Array object.

The shift method removes the first element from an array and returns it.

Expand image Requirements

Version 5.5

Applies To: Array Object (JScript 5.6)

Expand image See Also

Reference

unshift Method (JScript 5.6)


sin Method (JScript 5.6)

JScript
sin Method (JScript 5.6)
See Also
CollapseAll image DropDown image

Returns the sine of a number.

Math.sin(number)

Expand image Remarks

The number argument is a numeric expression for which the sine is needed.

The return value is the sine of the numeric argument.

Expand image Requirements

Version 1

Applies To: Math Object (JScript 5.6)

Expand image See Also

Reference

acos Method (JScript 5.6)
asin Method (JScript 5.6)
atan Method (JScript 5.6)
cos Method (JScript 5.6)
tan Method (JScript 5.6)


slice Method (Array) (JScript 5.6)

JScript
slice Method (Array) (JScript 5.6)
See Also Example
CollapseAll image DropDown image

Returns a section of an array.

arrayObj.slice(start, [end])

Expand image Arguments

arrayObj

Required. An Array object.

start

Required. The index to the beginning of the specified portion of arrayObj.

end

Optional. The index to the end of the specified portion of arrayObj.

Expand image Remarks

The slice method returns an Array object containing the specified portion of arrayObj.

The slice method copies up to, but not including, the element indicated by end. If start is negative, it is treated as length + start where length is the length of the array. If end is negative, it is treated as length + end where length is the length of the array. If end is omitted, extraction continues to the end of arrayObj. If end occurs before start, no elements are copied to the new array.

Expand image Example

In the following example, all but the last element of myArray is copied into newArray:

CopyCode image Copy Code
newArray = myArray.slice(0, -1)

Expand image Requirements

Version 3

Applies To: Array Object (JScript 5.6)

Expand image See Also

Reference

slice Method (String) (JScript 5.6)
String Object (JScript 5.6)


slice Method (String) (JScript 5.6)

JScript
slice Method (String) (JScript 5.6)
See Also Example
CollapseAll image DropDown image

Returns a section of a string.

stringObj.slice(start, [end])

Expand image Arguments

stringObj

Required. A String object or literal.

start

Required. The index to the beginning of the specified portion of stringObj.

end

Optional. The index to the end of the specified portion of stringObj.

Expand image Remarks

The slice method returns a String object containing the specified portion of stringObj.

The slice method copies up to, but not including, the element indicated by end. If start is negative, it is treated as length + start where length is the length of the string. If end is negative, it is treated as length + end where length is the length of the string. If end is omitted, extraction continues to the end of stringObj. If end occurs before start, no characters are copied to the new string.

Expand image Example

In the following example, the two uses of the slice method return the same result. In the second example, negative one (-1) points to the last character in str1 as the ending point.

CopyCode image Copy Code
str1.slice(0)
str2.slice(0,-1)

Expand image Requirements

Version 3

Applies To: String Object (JScript 5.6)

Expand image See Also

Reference

Array Object (JScript 5.6)
slice Method (Array) (JScript 5.6)


small Method (JScript 5.6)

JScript
small Method (JScript 5.6)
See Also
CollapseAll image DropDown image

Places HTML <SMALL> tags around text in a String object.

strVariable.small( )
"String Literal".small( )

Expand image Remarks

The following example illustrates the use of the small method:

CopyCode image Copy Code
var strVariable = "This is a string";
strVariable = strVariable.small( );

The value of strVariable after the last statement is:

CopyCode image Copy Code
<SMALL>This is a string</SMALL>

No checking is done to see if the tag has already been applied to the string.

Expand image Requirements

Version 1

Applies To: String Object (JScript 5.6)

Expand image See Also

Reference

big Method (JScript 5.6)


sort Method (JScript 5.6)

JScript
sort Method (JScript 5.6)
See Also Example
CollapseAll image DropDown image

Returns an Array object with the elements sorted.

arrayobj.sort(sortFunction)

Expand image Arguments

arrayObj

Required. Any Array object.

sortFunction

Optional. The name of the function used to determine the order of the elements. If omitted, the elements are sorted in ascending, ASCII character order.

Expand image Remarks

The sort method sorts the Array object in place; no new Array object is created during execution.

If you supply a function in the sortFunction argument, it must return one of the following values:

  • A negative value if the first argument passed is less than the second argument.

  • Zero if the two arguments are equivalent.

  • A positive value if the first argument is greater than the second argument.

Expand image Example

The following example illustrates the use of the sort method.

CopyCode image Copy Code
function SortDemo(){
   var a, l;                       //Declare variables.
   a = new Array("X" ,"y" ,"d", "Z", "v","m","r");
   l = a.sort();                   //Sort the array.
   return(l);                      //Return sorted array.
}

Expand image Requirements

Version 2

Applies To: Array Object (JScript 5.6)

Expand image See Also

Reference

small Method (JScript 5.6)


splice Method (JScript 5.6)

JScript
splice Method (JScript 5.6)
See Also
CollapseAll image DropDown image

Removes elements from an array and, if necessary, inserts new elements in their place, returning the deleted elements.

arrayObj.splice(start, deleteCount, [item1[, item2[, . . . [,itemN]]]])

Expand image Arguments

arrayObj

Required. An Array object.

start

Required. The zero-based location in the array from which to start removing elements.

deleteCount

Required. The number of elements to remove.

item1, item2,. . ., itemN

Optional. Elements to insert into the array in place of the deleted elements.

Expand image Remarks

The splice method modifies arrayObj by removing the specified number of elements from position start and inserting new elements. The deleted elements are returned as a new array object.

Expand image Requirements

Version 5.5

Applies To: Array Object (JScript 5.6)

Expand image See Also

Reference

slice Method (Array) (JScript 5.6)


split Method (JScript 5.6)

JScript
split Method (JScript 5.6)
See Also Example
CollapseAll image DropDown image

Returns the array of strings that results when a string is separated into substrings.

stringObj.split([separator[, limit]])

Expand image Arguments

stringObj

Required. The String object or literal to be split. This object is not modified by the split method.

separator

Optional. A string or an instance of a Regular Expression object identifying one or more characters to use in separating the string. If omitted, a single-element array containing the entire string is returned.

limit

Optional. A value used to limit the number of elements returned in the array.

Expand image Remarks

The result of the split method is an array of strings split at each point where separator occurs in stringObj. The separator is not returned as part of any array element.

Expand image Example

The following example illustrates the use of the split method.
CopyCode image Copy Code
function SplitDemo(){
   var s, ss;
   var s = "The rain in Spain falls mainly in the plain.";
   // Split at each space character.
   ss = s.split(" ");
   return(ss);
}

Expand image Requirements

Version 3

Applies To: String Object (JScript 5.6)

Expand image See Also

Reference

concat Method (String) (JScript 5.6)
RegExp Object (JScript 5.6)
Regular Expression Object (JScript 5.6)
Regular Expression Syntax (Scripting)


sqrt Method (JScript 5.6)

JScript
sqrt Method (JScript 5.6)
See Also
CollapseAll image DropDown image

Returns the square root of a number.

Math.sqrt(number)

Expand image Remarks

The required number argument is a numeric expression.

If number is negative, the return value is NaN.

Expand image Requirements

Version 1

Applies To: Math Object (JScript 5.6)

Expand image See Also

Reference

SQRT1_2 Property (JScript 5.6)
SQRT2 Property (JScript 5.6)


strike Method (JScript 5.6)

JScript
strike Method (JScript 5.6)
See Also
CollapseAll image DropDown image

Places HTML <STRIKE> tags around text in a String object.

strVariable.strike( )
"String Literal".strike( )

Expand image Remarks

The following example demonstrates how the strike method works:

CopyCode image Copy Code
var strVariable = "This is a string object";
strVariable = strVariable.strike( );

The value of strVariable after the last statement is:

CopyCode image Copy Code
<STRIKE>This is a string object</STRIKE>

No checking is done to see if the tag has already been applied to the string.

Expand image Requirements

Version 1

Applies To: String Object (JScript 5.6)

Expand image See Also

Reference

split Method (JScript 5.6)


sub Method (JScript 5.6)

JScript
sub Method (JScript 5.6)
See Also
CollapseAll image DropDown image

Places HTML <SUB> tags around text in a String object.

strVariable.sub( )
"String Literal".sub( )

Expand image Remarks

The following example demonstrates how the sub method works:

CopyCode image Copy Code
var strVariable = "This is a string object";
strVariable = strVariable.sub( );

The value of strVariable after the last statement is:

CopyCode image Copy Code
<SUB>This is a string object</SUB>

No checking is done to see if the tag has already been applied to the string.

Expand image Requirements

Version 1

Applies To: String Object (JScript 5.6)

Expand image See Also

Reference

sup Method (JScript 5.6)


substr Method (JScript 5.6)

JScript
substr Method (JScript 5.6)
See Also Example
CollapseAll image DropDown image

Returns a substring beginning at a specified location and having a specified length.

stringvar.substr(start [, length ])

Expand image Arguments

stringvar

Required. A string literal or String object from which the substring is extracted.

start

Required. The starting position of the desired substring. The index of the first character in the string is zero.

length

Optional. The number of characters to include in the returned substring.

Expand image Remarks

If length is zero or negative, an empty string is returned. If not specified, the substring continues to the end of stringvar.

Expand image Example

The following example illustrates the use of the substr method.
CopyCode image Copy Code
function SubstrDemo(){
   var s, ss;                //Declare variables.
   var s = "The rain in Spain falls mainly in the plain.";
   ss = s.substr(12, 5);  //Get substring.
   return(ss);               // Returns "Spain".
}

Expand image Requirements

Version 3

Applies To: String Object (JScript 5.6)

Expand image See Also

Reference

substring Method (JScript 5.6)


substring Method (JScript 5.6)

JScript
substring Method (JScript 5.6)
See Also Example
CollapseAll image DropDown image

Returns the substring at the specified location within a String object.

strVariable.substring(start, end)
"String Literal".substring(start, end)

Expand image Arguments

start

The zero-based index integer indicating the beginning of the substring.

end

The zero-based index integer indicating the end of the substring.

Expand image Remarks

The substring method returns a string containing the substring from start up to, but not including, end.

The substring method uses the lower value of start and end as the beginning point of the substring. For example, strvar.substring(0, 3) and strvar.substring(3, 0) return the same substring.

If either start or end is NaN or negative, it is replaced with zero.

The length of the substring is equal to the absolute value of the difference between start and end. For example, the length of the substring returned in strvar.substring(0, 3) and strvar.substring(3, 0) is three.

Expand image Example

The following example illustrates the use of the substring method.
CopyCode image Copy Code
function SubstringDemo(){
   var ss;                         //Declare variables.
   var s = "The rain in Spain falls mainly in the plain..";
   ss = s.substring(12, 17);   //Get substring.
   return(ss);                     //Return substring.
}

Expand image Requirements

Version 1

Applies To: String Object (JScript 5.6)

Expand image See Also

Reference

substr Method (JScript 5.6)


sup Method (JScript 5.6)

JScript
sup Method (JScript 5.6)
See Also
CollapseAll image DropDown image

Places HTML <SUP> tags around text in a String object.

strVariable.sup( )
"String Literal".sup( )

Expand image Remarks

The following example demonstrates how the sup method works.

CopyCode image Copy Code
var strVariable = "This is a string object";
strVariable = strVariable.sup( );

The value of strVariable after the last statement is:

CopyCode image Copy Code
<SUP>This is a string object</SUP>

No checking is done to see if the tag has already been applied to the string.

Expand image Requirements

Version 1

Applies To: String Object (JScript 5.6)

Expand image See Also

Reference

sub Method (JScript 5.6)


tan Method (JScript 5.6)

JScript
tan Method (JScript 5.6)
See Also
CollapseAll image DropDown image

Returns the tangent of a number.

Math.tan(number)

Expand image Remarks

The required number argument is a numeric expression for which the tangent is sought.

The return value is the tangent of number.

Expand image Requirements

Version 1

Applies To: Math Object (JScript 5.6)

Expand image See Also

Reference

acos Method (JScript 5.6)
asin Method (JScript 5.6)
atan Method (JScript 5.6)
atan2 Method (JScript 5.6)
cos Method (JScript 5.6)
sin Method (JScript 5.6)


test Method (JScript 5.6)

JScript
test Method (JScript 5.6)
See Also Example
CollapseAll image DropDown image

Returns a Boolean value that indicates whether or not a pattern exists in a searched string.

rgExp.test(str)

Expand image Arguments

rgExp

Required. An instance of a Regular Expression object containing the regular expression pattern and applicable flags.

str

Required. The string on which to perform the search.

Expand image Remarks

The test method checks to see if a pattern exists within a string and returns true if so, and false otherwise.

The properties of the global RegExp object are not modified by the test method.

Expand image Example

The following example illustrates the use of the test method. To use this example, pass the function a regular expression pattern and a string. The function will test for the occurrence of the regular expression pattern in the string and return a string indicating the results of that search:
CopyCode image Copy Code
function TestDemo(re, s){
   var s1;                         //Declare variable.
   // Test string for existence of regular expression.
   if (re.test(s))                 //Test for existence.
      s1 = " contains ";           //s contains pattern.
   else
      s1 = " does not contain ";   //s does not contain pattern.
   return("'" + s + "'" + s1 + "'"+ re.source + "'"); //Return string.
}

Expand image Requirements

Version 3

Applies To: Regular Expression Object (JScript 5.6)

Expand image See Also

Reference

RegExp Object (JScript 5.6)
Regular Expression Object (JScript 5.6)
Regular Expression Syntax (Scripting)


toArray Method (JScript 5.6)

JScript
toArray Method (JScript 5.6)
See Also Example
CollapseAll image DropDown image

Returns a standard JScript array converted from a VBArray.

safeArray.toArray( )

Expand image Remarks

The required safeArray reference is a VBArray object.

The conversion translates the multidimensional VBArray into a single dimensional JScript array. Each successive dimension is appended to the end of the previous one. For example, a VBArray with three dimensions and three elements in each dimension is converted into a JScript array as follows:

Suppose the VBArray contains: (1, 2, 3), (4, 5, 6), (7, 8, 9). After translation, the JScript array contains: 1, 2, 3, 4, 5, 6, 7, 8, 9.

There is currently no way to convert a JScript array into a VBArray.

Expand image Example

The following example consists of three parts. The first part is VBScript code to create a Visual Basic safe array. The second part is JScript code that converts the Visual Basic safe array to a JScript array. Both of these parts go into the <HEAD> section of an HTML page. The third part is the JScript code that goes in the <BODY> section to run the other two parts.

CopyCode image Copy Code
<HEAD>
<SCRIPT LANGUAGE="VBScript">
<!--
Function CreateVBArray()
   Dim i, j, k
   Dim a(2, 2)
   k = 1
   For i = 0 To 2
      For j = 0 To 2
         a(j, i) = k
         document.writeln(k)
         k = k + 1
      Next
      document.writeln("<BR>")
   Next
   CreateVBArray = a
End Function
-->
</SCRIPT>

<SCRIPT LANGUAGE="JScript">
<!--
function VBArrayTest(vbarray)
{
   var a = new VBArray(vbarray);
   var b = a.toArray();
   var i;
   for (i = 0; i < 9; i++)
   {
      document.writeln(b[i]);
   }
}
-->
</SCRIPT>
</HEAD>

<BODY>
<SCRIPT LANGUAGE="JScript">
<!--
   VBArrayTest(CreateVBArray());
-->
</SCRIPT>
</BODY>

Expand image Requirements

Version 3

Applies To: VBArray Object (JScript 5.6)

Expand image See Also

Reference

dimensions Method (JScript 5.6)
getItem Method (JScript 5.6)
lbound Method (JScript 5.6)
ubound Method (JScript 5.6)


toDateString Method (JScript 5.6)

JScript
toDateString Method (JScript 5.6)
See Also
CollapseAll image DropDown image

Returns a date as a string value.

objDate.toDateString( )

Expand image Remarks

The required objDate reference is a Date object.

The toDateString method returns a string value containing the date, in the current time zone, in a convenient, easily read format.

Expand image Requirements

Version 5.5

Applies To: Date Object (JScript 5.6)

Expand image See Also

Reference

toTimeString Method (JScript 5.6)
toLocaleDateString Method (JScript 5.6)


toExponential Method (JScript 5.6)

JScript
toExponential Method (JScript 5.6)
See Also
CollapseAll image DropDown image

Returns a string containing a number represented in exponential notation.

numObj.toExponential([fractionDigits])

Expand image Arguments

numObj

Required. A Number object.

fractionDigits

Optional. Number of digits after the decimal point. Must be in the range 0 – 20, inclusive.

Expand image Remarks

The toExponential method returns a string representation of a number in exponential notation. The string contains one digit before the significand's decimal point, and may contain fractionDigits digits after it.

If fractionDigits is not supplied, the toExponential method returns as many digits necessary to uniquely specify the number.

Expand image Requirements

Version 5.5

Applies To: Number Object (JScript 5.6)

Expand image See Also

Reference

toFixed Method (JScript 5.6)
toPrecision Method (JScript 5.6)


toFixed Method (JScript 5.6)

JScript
toFixed Method (JScript 5.6)
See Also
CollapseAll image DropDown image

Returns a string representing a number in fixed-point notation.

numObj.toFixed([fractionDigits])

Expand image Arguments

numObj

Required A Number object.

fractionDigits

Optional. Number of digits after the decimal point. Must be in the range 0 – 20, inclusive.

Expand image Remarks

The toFixed method returns a string representation of a number in fixed-point notation. The string contains one digit before the significand's decimal point, and must contain fractionDigits digits after it.

If fractionDigits is not supplied or undefined, the toFixed method assumes the value is zero.

Expand image Requirements

Version 5.5

Applies To: Number Object (JScript 5.6)

Expand image See Also

Reference

toExponential Method (JScript 5.6)
toPrecision Method (JScript 5.6)


toGMTString Method (JScript 5.6)

JScript
toGMTString Method (JScript 5.6)
See Also
CollapseAll image DropDown image

Returns a date converted to a string using Greenwich Mean Time(GMT).

dateObj.toGMTString()

Expand image Remarks

The required dateObj reference is any Date object.

The toGMTString method is obsolete, and is provided for backwards compatibility only. It is recommended that you use the toUTCString method instead.

The toGMTString method returns a String object that contains the date formatted using GMT convention. The format of the return value is as follows: "05 Jan 1996 00:00:00 GMT."

Expand image Requirements

Version 1

Applies To: Date Object (JScript 5.6)

Expand image See Also

Reference

toUTCString Method (JScript 5.6)


toLocaleDateString Method (JScript 5.6)

JScript
toLocaleDateString Method (JScript 5.6)
See Also
CollapseAll image DropDown image

Returns a date as a string value appropriate to the host environment's current locale.

objDate.toLocaleDateString( )

Expand image Remarks

The required objDate reference is a Date object.

The toLocaleDateString method returns a string value that contains a date, in the current time zone, in an easily read format. The date is in the default format of the host environment's current locale. The return value of this method cannot be relied upon in scripting, as it will vary from computer to computer. The toLocalDateString method should only be used to format display – never as part of a computation.

Expand image Requirements

Version 5.5

Applies To: Date Object (JScript 5.6)

Expand image See Also

Reference

toDateString Method (JScript 5.6)
toLocaleTimeString Method (JScript 5.6)


toLocaleLowerCase Method (JScript 5.6)

JScript
toLocaleLowerCase Method (JScript 5.6)
See Also
CollapseAll image DropDown image

Returns a string where all alphabetic characters have been converted to lowercase, taking into account the host environment's current locale.

stringVar.tolocaleLowerCase( )

Expand image Remarks

The required stringVar reference is a String object, value, or literal.

The toLocaleLowerCase method converts the characters in a string, taking into account the host environment's current locale. In most cases, the results are the same as you would obtain with the toLowerCase method. Results differ if the rules for a language conflict with the regular Unicode case mappings.

Expand image Requirements

Version 5.5

Applies To: String Object (JScript 5.6)

Expand image See Also

Reference

toLocaleUpperCase Method (JScript 5.6)
toLowerCase Method (JScript 5.6)


toLocaleString Method (JScript 5.6)

JScript
toLocaleString Method (JScript 5.6)
See Also Example
CollapseAll image DropDown image

Returns a date converted to a string using the current locale.

dateObj.toLocaleString()

Expand image Remarks

The required dateObj is any Date object.

The toLocaleString method returns a String object that contains the date written in the current locale's long default format.

  • For dates between 1601 and 1999 A.D., the date is formatted according to the user's Control Panel Regional Settings.

  • For dates outside this range, the default format of the toString method is used.

For example, in the United States, toLocaleString returns "01/05/96 00:00:00" for January 5. In Europe, it returns "05/01/96 00:00:00" for the same date, as European convention puts the day before the month.

Note Note

toLocaleString should only be used to display results to a user; it should never be used as the basis for computation within a script as the returned result is machine-specific.

Expand image Example

The following example illustrates the use of the toLocaleString method.
CopyCode image Copy Code
function toLocaleStrDemo(){
   var d, s;                      //Declare variables.
   d = new Date();                //Create Date object.
   s = "Current setting is ";
   s += d.toLocaleString();       //Convert to current locale.
   return(s);                     //Return converted date
}

Expand image Requirements

Version 1

Applies To: Array Object (JScript 5.6)| Date Object (JScript 5.6)| Number Object (JScript 5.6)| Object Object (JScript 5.6)

Expand image See Also

Reference

toLocaleDateString Method (JScript 5.6)


toLocaleTimeString Method (JScript 5.6)

JScript
toLocaleTimeString Method (JScript 5.6)
See Also
CollapseAll image DropDown image

Returns a time as a string value appropriate to the host environment's current locale.

objDate.toLocaleTimeString( )

Expand image Remarks

The required objDate reference is a Date object.

The toLocaleTimeString method returns a string value that contains a time, in the current time zone, in an easily read format. The time is in the default format of the host environment's current locale. The return value of this method cannot be relied upon in scripting, as it will vary from computer to computer. The toLocalTimeString method should only be used to format display – never as part of a computation.

Expand image Requirements

Version 5.5

Applies To: Date Object (JScript 5.6)

Expand image See Also

Reference

toTimeString Method (JScript 5.6)
toLocaleDateString Method (JScript 5.6)


toLocaleUpperCase Method (JScript 5.6)

JScript
toLocaleUpperCase Method (JScript 5.6)
See Also
CollapseAll image DropDown image

Returns a string where all alphabetic characters have been converted to uppercase, taking into account the host environment's current locale.

stringVar.tolocaleUpperCase( )

Expand image Remarks

The required stringVar reference is a String object, value, or literal.

The toLocaleUpperCase method converts the characters in a string, taking into account the host environment's current locale. In most cases, the results are the same as you would obtain with the toUpperCase method. Results differ if the rules for a language conflict with the regular Unicode case mappings.

Expand image Requirements

Version 5.5

Applies To: String Object (JScript 5.6)

Expand image See Also

Reference

toLocaleLowerCase Method (JScript 5.6)
toUpperCase Method (JScript 5.6)


toLowerCase Method (JScript 5.6)

JScript
toLowerCase Method (JScript 5.6)
See Also
CollapseAll image DropDown image

Returns a string where all alphabetic characters have been converted to lowercase.

strVariable.toLowerCase( )
"String Literal".toLowerCase( )

Expand image Remarks

The toLowerCase method has no effect on nonalphabetic characters.

The following example demonstrates the effects of the toLowerCase method:

CopyCode image Copy Code
var strVariable = "This is a STRING object";
strVariable = strVariable.toLowerCase( );

The value of strVariable after the last statement is:

CopyCode image Copy Code
this is a string object

Expand image Requirements

Version 1

Applies To: String Object (JScript 5.6)

Expand image See Also

Reference

toUpperCase Method (JScript 5.6)


toPrecision Method (JScript 5.6)

JScript
toPrecision Method (JScript 5.6)
See Also
CollapseAll image DropDown image

Returns a string containing a number represented either in exponential or fixed-point notation with a specified number of digits.

numObj.toPrecision ([precision])

Expand image Arguments

numObj

Required. A Number object.

precision

Optional. Number of significant digits. Must be in the range 1 – 21, inclusive.

Expand image Remarks

For numbers in exponential notation, precision - 1 digits are returned after the decimal point. For numbers in fixed notation, precision significant digits are returned.

If precision is not supplied or is undefined, the toString method is called instead.

Expand image Requirements

Version 5.5

Applies To: Number Object (JScript 5.6)

Expand image See Also

Reference

toFixed Method (JScript 5.6)
toExponential Method (JScript 5.6)


toString Method (JScript 5.6)

JScript
toString Method (JScript 5.6)
See Also Example
CollapseAll image DropDown image

Returns a string representation of an object.

objectname.toString([radix])

Expand image Arguments

objectname

Required. An object for which a string representation is sought.

radix

Optional. Specifies a radix for converting numeric values to strings. This value is only used for numbers.

Expand image Remarks

The toString method is a member of all built-in JScript objects. How it behaves depends on the object type:

Object Behavior

Array

Elements of an Array are converted to strings. The resulting strings are concatenated, separated by commas.

Boolean

If the Boolean value is true, returns "true". Otherwise, returns "false".

Date

Returns the textual representation of the date.

Error

Returns a string containing the associated error message.

Function

Returns a string of the following form, where functionname is the name of the function whose toString method was called:

CopyCode image Copy Code
function functionname( ) { [native code] }

Number

Returns the textual representation of the number.

String

Returns the value of the String object.

Default

Returns "[object objectname]", where objectname is the name of the object type.

Expand image Example

The following example illustrates the use of the toString method with a radix argument. The return value of function shown below is a Radix conversion table.
CopyCode image Copy Code
function CreateRadixTable (){
   var s, s1, s2, s3, x;                    //Declare variables.
   s = "Hex    Dec   Bin \n";               //Create table heading.
   for (x = 0; x < 16; x++)                 //Establish size of table
   {                                        // in terms of number of
      switch(x)                             // values shown.
      {                                     //Set intercolumn spacing.
         case 0 :
            s1 = "      ";
            s2 = "    ";
            s3 = "   ";
            break;
         case 1 :
            s1 = "      ";
            s2 = "    ";
            s3 = "   ";
            break;
         case 2 :
            s3 = "  ";
            break;
         case 3 :
            s3 = "  ";
            break;
         case 4 :
            s3 = " ";
            break;
         case 5 :
            s3 = " ";
            break;
         case 6 :
            s3 = " ";
            break;
         case 7 :
            s3 = " ";
            break;
         case 8 :
            s3 = "" ;
            break;
         case 9 :
            s3 = "";
            break;
         default:
            s1 = "     ";
            s2 = "";
            s3 = "    ";
      }                                     //Convert to hex, decimal & binary.
      s += " " + x.toString(16) + s1 + x.toString(10)
      s +=  s2 + s3 + x.toString(2)+ "\n";

   }
   return(s);                               //Return entire radix table.
}

Expand image Requirements

Version 2

Applies To: Array Object (JScript 5.6)| Boolean Object (JScript 5.6)| Date Object (JScript 5.6)| Error Object (JScript 5.6)| Function Object (JScript 5.6)| Number Object (JScript 5.6)| Object Object (JScript 5.6)| String Object (JScript 5.6)

Expand image See Also

Reference

function Statement (JScript 5.6)


toTimeString Method (JScript 5.6)

JScript
toTimeString Method (JScript 5.6)
See Also
CollapseAll image DropDown image

Returns a time as a string value.

objDate.toTimeString( )

Expand image Remarks

The required objDate reference is a Date object.

The toTimeString method returns a string value containing the time, in the current time zone, in a convenient, easily read format.

Expand image Requirements

Version 5.5

Applies To: Date Object (JScript 5.6)

Expand image See Also

Reference

toDateString Method (JScript 5.6)
toLocaleTimeString Method (JScript 5.6)


toUpperCase Method (JScript 5.6)

JScript
toUpperCase Method (JScript 5.6)
See Also Example
CollapseAll image DropDown image

Returns a string where all alphabetic characters have been converted to uppercase.

strVariable.toUpperCase( )
"String Literal".toUpperCase( )

Expand image Remarks

The toUpperCase method has no effect on non-alphabetic characters.

Expand image Example

The following example demonstrates the effects of the toUpperCase method:

CopyCode image Copy Code
var strVariable = "This is a STRING object";
strVariable = strVariable.toUpperCase( );

The value of strVariable after the last statement is:

CopyCode image Copy Code
THIS IS A STRING OBJECT

Expand image Requirements

Version 1

Applies To: String Object (JScript 5.6)

Expand image See Also

Reference

toLowerCase Method (JScript 5.6)


toUTCString Method (JScript 5.6)

JScript
toUTCString Method (JScript 5.6)
See Also Example
CollapseAll image DropDown image

Returns a date converted to a string using Universal Coordinated Time (UTC).

dateObj.toUTCString()

Expand image Remarks

The required dateObj reference is any Date object.

The toUTCString method returns a String object that contains the date formatted using UTC convention in a convenient, easily read form.

Expand image Example

The following example illustrates the use of the toUTCString method.

CopyCode image Copy Code
function toUTCStrDemo(){
   var d, s;                   //Declare variables.
   d = new Date();             //Create Date object.
   s = "Current setting is ";
   s += d.toUTCString();       //Convert to UTC string.
   return(s);                  //Return UTC string.
}

Expand image Requirements

Version 3

Applies To: Date Object (JScript 5.6)

Expand image See Also

Reference

toGMTString Method (JScript 5.6)


ubound Method (JScript 5.6)

JScript
ubound Method (JScript 5.6)
See Also Example
CollapseAll image DropDown image

Returns the highest index value used in the specified dimension of the VBArray.

safeArray.ubound(dimension)

Expand image Arguments

safeArray

Required. A VBArray object.

dimension

Optional. The dimension of the VBArray for which the higher bound index is wanted. If omitted, ubound behaves as if a 1 was passed.

Expand image Remarks

If the VBArray is empty, the ubound method returns undefined. If dim is greater than the number of dimensions in the VBArray, or is negative, the method generates a "Subscript out of range" error.

Expand image Example

The following example consists of three parts. The first part is VBScript code to create a Visual Basic safe array. The second part is JScript code that determines the number of dimensions in the safe array and the upper bound of each dimension. Both of these parts go into the <HEAD> section of an HTML page. The third part is the JScript code that goes in the <BODY> section to run the other two parts.

CopyCode image Copy Code
<HEAD>
<SCRIPT LANGUAGE="VBScript">
<!--
Function CreateVBArray()
   Dim i, j, k
   Dim a(2, 2)
   k = 1
   For i = 0 To 2
      For j = 0 To 2
         a(j, i) = k
         k = k + 1
      Next
   Next
   CreateVBArray = a
End Function
-->
</SCRIPT>

<SCRIPT LANGUAGE="JScript">
<!--
function VBArrayTest(vba)
{
   var i, s;
   var a = new VBArray(vba);
   for (i = 1; i <= a.dimensions(); i++)
   {
      s = "The upper bound of dimension ";
      s += i + " is ";
      s += a.ubound(i)+ ".<BR>";
      return(s);
   }
}
-->
</SCRIPT>
</HEAD>

<BODY>
<SCRIPT language="jscript">
   document.write(VBArrayTest(CreateVBArray()));
</SCRIPT>
</BODY>

Expand image Requirements

Version 3

Applies To: VBArray Object (JScript 5.6)

Expand image See Also

Reference

dimensions Method (JScript 5.6)
getItem Method (JScript 5.6)
lbound Method (JScript 5.6)
toArray Method (JScript 5.6)


unescape Method (JScript 5.6)

JScript
unescape Method (JScript 5.6)
See Also
CollapseAll image DropDown image

Decodes String objects encoded with the escape method.

unescape(charString)

Expand image Remarks

The required charString argument is a String object or literal to be decoded.

The unescape method returns a string value that contains the contents of charstring. All characters encoded with the %xx hexadecimal form are replaced by their ASCII character set equivalents.

Characters encoded in %u xxxx format (Unicode characters) are replaced with the Unicode character with hexadecimal encoding xxxx.

Note Note

The unescape method should not be used to decode Uniform Resource Identifiers (URI). Use decodeURI and decodeURIComponent methods instead.

Expand image Requirements

Version 1

Applies To: Global Object (JScript 5.6)

Expand image See Also

Reference

decodeURI Method (JScript 5.6)
decodeURIComponent Method (JScript 5.6)
escape Method (JScript 5.6)
String Object (JScript 5.6)


unshift Method (JScript 5.6)

JScript
unshift Method (JScript 5.6)
See Also
CollapseAll image DropDown image

Returns an array with specified elements inserted at the beginning.

arrayObj.unshift([item1[, item2 [, . . . [, itemN]]]])

Expand image Arguments

arrayObj

Required. An Array object.

item1, item2,. . ., itemN

Optional. Elements to insert at the start of the Array.

Expand image Remarks

The unshift method inserts elements into the start of an array, so they appear in the same order in which they appear in the argument list.

Expand image Requirements

Version 5.5

Applies To: Array Object (JScript 5.6)

Expand image See Also

Reference

shift Method (JScript 5.6)


UTC Method (JScript 5.6)

JScript
UTC Method (JScript 5.6)
See Also Example
CollapseAll image DropDown image

Returns the number of milliseconds between midnight, January 1, 1970 Universal Coordinated Time (UTC) (or GMT) and the supplied date.

Date.UTC(year, month, day[, hours[, minutes[, seconds[,ms]]]])

Expand image Arguments

year

Required. The full year designation is required for cross-century date accuracy. If year is between 0 and 99 is used, then year is assumed to be 1900 + year.

month

Required. The month as an integer between 0 and 11 (January to December).

day

Required. The date as an integer between 1 and 31.

hours

Optional. Must be supplied if minutes is supplied. An integer from 0 to 23 (midnight to 11pm) that specifies the hour.

minutes

Optional. Must be supplied if seconds is supplied. An integer from 0 to 59 that specifies the minutes.

seconds

Optional. Must be supplied if milliseconds is supplied. An integer from 0 to 59 that specifies the seconds.

ms

Optional. An integer from 0 to 999 that specifies the milliseconds.

Expand image Remarks

The UTC method returns the number of milliseconds between midnight, January 1, 1970 UTC and the supplied date. This return value can be used in the setTime method and in the Date object constructor. If the value of an argument is greater than its range, or is a negative number, other stored values are modified accordingly. For example, if you specify 150 seconds, JScript redefines that number as two minutes and 30 seconds.

The difference between the UTC method and the Date object constructor that accepts a date is that the UTC method assumes UTC, and the Date object constructor assumes local time.

The UTC method is a static method. Therefore, a Date object does not have to be created before it can be used.

Note Note

If year is between 0 and 99, use 1900 + year for the year.

Expand image Example

The following example illustrates the use of the UTC method.
CopyCode image Copy Code
function DaysBetweenDateAndNow(yr, mo, dy){
   var d, r, t1, t2, t3;            //Declare variables.
   var MinMilli = 1000 * 60         //Initialize variables.
   var HrMilli = MinMilli * 60
   var DyMilli = HrMilli * 24
   t1 = Date.UTC(yr, mo - 1, dy)    //Get milliseconds since 1/1/1970.
   d = new Date();                  //Create Date object.
   t2 = d.getTime();                //Get current time.
   if (t2 >= t1)
      t3 = t2 - t1;
   else
      t3 = t1 - t2;
   r = Math.round(t3 / DyMilli);
   return(r);                       //Return difference.
}

Expand image Requirements

Version 1

Applies To: Date Object (JScript 5.6)

Expand image See Also

Reference

setTime Method (JScript 5.6)


valueOf Method (JScript 5.6)

JScript
valueOf Method (JScript 5.6)
See Also
CollapseAll image DropDown image

Returns the primitive value of the specified object.

object.valueOf( )

Expand image Remarks

The required object reference is any intrinsic JScript object.

The valueOf method is defined differently for each intrinsic JScript object.

Object | Return Value
Array | Returns the array instance.
Boolean | The Boolean value.
Date | The stored time value in milliseconds since midnight, January 1, 1970 UTC.
Function | The function itself.
Number | The numeric value.
Object | The object itself. This is the default.
String | The string value.

The Math and Error objects do not have a valueOf method.

Expand image Requirements

Version 2

Applies To: Array Object (JScript 5.6)| Boolean Object (JScript 5.6)| Date Object (JScript 5.6)| Function Object (JScript 5.6)| Number Object (JScript 5.6)| Object Object (JScript 5.6)| String Object (JScript 5.6)

Expand image See Also

Reference

toString Method (JScript 5.6)


write Method (JScript 5.6)

JScript
write Method (JScript 5.6)
See Also Example
CollapseAll image DropDown image

Sends strings to the script debugger.

Debug.write([str1 [, str2 [, ... [, strN]]]])

Expand image Arguments

str1, str2, ... , strN

Optional. Strings to send to the script debugger.

Expand image Remarks

The write method sends strings to the Immediate window of the Microsoft Script Debugger at run time. If the script is not being debugged, the write method has no effect.

The write method is almost identical to the writeln method. The only difference is that the writeln method sends a newline character after the strings are sent.

Expand image Example

This example uses the write method to display the value of the variable in the Immediate window of the Microsoft Script Debugger.

Note Note

To run this example, you must have a script debugger installed and the script must run in debug mode. For more information, search MSDN (http://msdn.microsoft.com) for the title "Introducing Microsoft Script Debugger".
CopyCode image Copy Code
var counter = 42;
Debug.write("The value of counter is " + counter);

Expand image Requirements

Version 3

Applies To: Debug Object (JScript 5.6)

Expand image See Also

Reference

writeln Method


writeln Method

JScript
writeln Method
See Also Example
CollapseAll image DropDown image

Sends strings to the script debugger, followed by a newline character.

Debug.writeln([str1 [, str2 [, ... [, strN]]]])

Expand image Arguments

str1, str2, ... , strN

Optional. Strings to send to the script debugger.

Expand image Remarks

The writeln method sends strings, followed by a newline character, to the Immediate window of the Microsoft Script Debugger at run time. If the script is not being debugged, the writeln method has no effect.

The writeln method is almost identical to the write method. The only difference is that the write method does not send a newline character after sending the strings.

Expand image Example

This example uses the writeln method to display the value of the variable in the Immediate window of the Microsoft Script Debugger.

Note Note

To run this example, you must have a script debugger installed and the script must run in debug mode. For more information, search MSDN (http://msdn.microsoft.com) for the title "Introducing Microsoft Script Debugger".
CopyCode image Copy Code
var counter = 42;
Debug.writeln("The value of counter is " + counter);

Expand image Requirements

Version 3

Applies To: Debug Object (JScript 5.6)

Expand image See Also

Reference

write Method (JScript 5.6)


JScript Objects (JScript 5.6)

JScript
JScript Objects (JScript 5.6)
See Also
CollapseAll image DropDown image

The following table lists JScript Objects.

Expand image Objects

Description | Language Element
Enables and returns a reference to an Automation object. | ActiveXObject Object
Provides support for creation of arrays of any data type. | Array Object
An object representing the arguments to the currently executing function, and the functions that called it. | arguments Object
Creates a new Boolean value. | Boolean Object
Enables basic storage and retrieval of dates and times. | Date Object
An intrinsic object that can send output to a script debugger. | Debug Object
Enables enumeration of items in a collection. | Enumerator Object
An object that contains information about errors that occur while JScript code is running. | Error Object
Creates a new function. | Function Object
An intrinsic object whose purpose is to collect global methods into one object. | Global Object
An intrinsic object that provides basic mathematics functionality and constants. | Math Object
An object representation of the number data type and placeholder for numeric constants. | Number Object
Provides functionality common to all JScript objects. | Object Object
Stores information on regular expression pattern searches. | RegExp Object
Contains a regular expression pattern. | Regular Expression Object
Allows manipulation and formatting of text strings and determination and location of substrings within strings. | String Object
Provides access to Visual Basic safe arrays. | VBArray Object

Expand image See Also

Reference

JScript Methods


ActiveXObject Object (JScript 5.6)

JScript
ActiveXObject Object (JScript 5.6)
See Also
CollapseAll image DropDown image

Enables and returns a reference to an Automation object.

newObj = new ActiveXObject(servername.typename[, location])

Expand image Arguments

newObj

Required. The variable name to which the ActiveXObject is assigned.

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.

Expand image 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 new ActiveXObject to an object variable:

CopyCode image Copy Code
var ExcelSheet;
ExcelApp = new ActiveXObject("Excel.Application");
ExcelSheet = new ActiveXObject("Excel.Sheet");

This code starts the application creating the object (in this case, a Microsoft Excel worksheet). Once an object is created, you refer to it in code using the object variable you defined. In the following example, you 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.

CopyCode image Copy Code
// 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:\\TEST.XLS");
// Close Excel with the Quit method on the Application object.
ExcelSheet.Application.Quit();

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 ActiveXObject. 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":

CopyCode image Copy Code
function GetAppVersion() {
   var XLApp = new ActiveXObject("Excel.Application", "MyServer");
   return(XLApp.Version);
}

An error occurs if the specified remote server does not exist or cannot be found.

Expand image Requirements

Version 1

Expand image See Also

Reference

GetObject Function (JScript 5.6)


Array Object (JScript 5.6)

JScript
Array Object (JScript 5.6)
See Also
CollapseAll image DropDown image

Provides support for creation of arrays of any data type.

arrayObj = new Array()
arrayObj = new Array([size])
arrayObj = new Array([element0[, element1[, ...[, elementN]]]])

Expand image Arguments

arrayObj

Required. The variable name to which the Array object is assigned.

size

Optional. The size of the array. As arrays are zero-based, created elements will have indexes from zero to size -1.

element0,...,elementN

Optional. The elements to place in the array. This creates an array with n + 1 elements, and a length of n + 1. Using this syntax, you must supply more than one element.

Expand image Remarks

After an array is created, the individual elements of the array can be accessed using [ ] notation, for example:

CopyCode image Copy Code
var my_array = new Array();
for (i = 0; i < 10; i++)
   {
   my_array[i] = i;
   }
x = my_array[4];

Since arrays in Microsoft JScript are zero-based, the last statement in the preceding example accesses the fifth element of the array. That element contains the value 4.

If only one argument is passed to the Array constructor, and the argument is a number, it must be an unsigned 32-bit integer (< approximately four billion). That value then becomes the size of the array. If the value is a number, but is less than zero or is not an integer, a run-time error occurs.

If a single value is passed to the Array constructor, and it is not a number, the length property is set to 1, and the value of the only element becomes the single, passed-in argument.

Notice that JScript arrays are sparse arrays, that is, although you can allocate an array with many elements, only the elements that actually contain data exist. This reduces the amount of memory used by the array.

Expand image Properties

constructor Property | length Property | prototype Property

Expand image Methods

concat Method | join Method | pop Method | push Method | reverse Method | shift Method | slice Method | sort Method | splice Method | toLocaleString Method | toString Method | unshift Method | valueOf Method

Expand image Requirements

Version 2

Expand image See Also

Reference

new Operator (JScript 5.6)


arguments Object (JScript 5.6)

JScript
arguments Object (JScript 5.6)
See Also Example
CollapseAll image DropDown image

An object representing the arguments to the currently executing function, and the functions that called it.

[function.]arguments[n]

Expand image Arguments

function

Optional. The name of the currently executing Function object.

n

Required. The zero-based index to argument values passed to the Function object.

Expand image Remarks

You cannot explicitly create an arguments object. The arguments object only becomes available when a function begins execution. The arguments object of the function is not an array, but the individual arguments are accessed the same way array elements are accessed. The index n is actually a reference to one of the 0n properties of the arguments object.

Expand image Example

The following example illustrates the use of the arguments object.
CopyCode image Copy Code
function ArgTest(a, b){
   var i, s = "The ArgTest function expected ";
   var numargs = arguments.length;     //Get number of arguments passed.
   var expargs = ArgTest.length;       //Get number of arguments expected.
   if (expargs < 2)
      s += expargs + " argument. ";
   else
      s += expargs + " arguments. ";
   if (numargs < 2)
      s += numargs + " was passed.";
   else
      s += numargs + " were passed.";
   s += "\n\n"
   for (i =0 ; i < numargs; i++){      //Get argument contents.
   s += "  Arg " + i + " = " + arguments[i] + "\n";
   }
   return(s);                          //Return list of arguments.
}

Expand image Requirements

Version 1

Expand image See Also

Reference

0...n Properties (JScript 5.6)
callee Property (JScript 5.6)
caller Property (JScript 5.6)
length Property (arguments) (JScript 5.6)


Boolean Object (JScript 5.6)

JScript
Boolean Object (JScript 5.6)
See Also
CollapseAll image DropDown image

Creates a new Boolean value.

boolObj = new Boolean([boolValue])

Expand image Arguments

boolObj

Required. The variable name to which the Boolean object is assigned.

boolValue

Optional. The initial Boolean value for the new object. If Boolvalue is omitted, or is false, 0, null, NaN, or an empty string, the initial value of the Boolean object is false. Otherwise, the initial value is true.

Expand image Remarks

The Boolean object is a wrapper for the Boolean data type. JScript implicitly uses the Boolean object whenever a Boolean data type is converted to a Boolean object.

You rarely call the Boolean object explicitly.

Expand image Properties

constructor Property | prototype Property

Expand image Methods

toString Method | valueOf Method

Expand image Requirements

Version 2

Expand image See Also

Reference

new Operator (JScript 5.6)
var Statement (JScript 5.6)


Debug Object (JScript 5.6)

JScript
Debug Object (JScript 5.6)
See Also Example
CollapseAll image DropDown image

An intrinsic global object that can send output to a script debugger, such as the Microsoft Script Debugger.

Debug.method

Expand image Remarks

The Debug object cannot be created directly, but it is always available for use.

The write and writeln methods of the Debug object display strings in the Immediate window of the Microsoft Script Debugger at run time. If the script is not being debugged, the methods have no effect.

Expand image Example

This example uses the write method to display the value of the variable in the Immediate window of the Microsoft Script Debugger.

Note Note

To run this example, you must have a script debugger installed and the script must run in debug mode. For more information, search MSDN (http://msdn.microsoft.com) for the title "Introducing Microsoft Script Debugger".
CopyCode image Copy Code
var counter = 42;
Debug.write("The value of counter is " + counter);

Expand image Properties

The Debug object has no properties.

Expand image Methods

write Method (JScript 5.6) | writeln Method

Expand image Requirements

Version 3

Expand image See Also

Reference

debugger Statement (JScript 5.6)


Date Object (JScript 5.6)

JScript
Date Object (JScript 5.6)
See Also Example
CollapseAll image DropDown image

Enables basic storage and retrieval of dates and times.

dateObj = new Date()
dateObj = new Date(dateVal)
dateObj = new Date(year, month, date[, hours[, minutes[, seconds[,ms]]]])

Expand image Arguments

dateObj

Required. The variable name to which the Date object is assigned.

dateVal

Required. If a numeric value, dateVal represents the number of milliseconds in Universal Coordinated Time between the specified date and midnight January 1, 1970. If a string, dateVal is parsed according to the rules in the parse method. The dateVal argument can also be a VT_DATE value as returned from some ActiveX® objects.

year

Required. The full year, for example, 1976 (and not 76).

month

Required. The month as an integer between 0 and 11 (January to December).

date

Required. The date as an integer between 1 and 31.

hours

Optional. Must be supplied if minutes is supplied. An integer from 0 to 23 (midnight to 11pm) that specifies the hour.

minutes

Optional. Must be supplied if seconds is supplied. An integer from 0 to 59 that specifies the minutes.

seconds

Optional. Must be supplied if milliseconds is supplied. An integer from 0 to 59 that specifies the seconds.

ms

Optional. An integer from 0 to 999 that specifies the milliseconds.

Expand image Remarks

A Date object contains a number representing a particular instant in time to within a millisecond. If the value of an argument is greater than its range or is a negative number, other stored values are modified accordingly. For example, if you specify 150 seconds, JScript redefines that number as two minutes and 30 seconds.

If the number is NaN, the object does not represent a specific instant of time. If you pass no parameters to the Date object, it is initialized to the current time (UTC). A value must be given to the object before you can use it.

The range of dates that can be represented in a Date object is approximately 285,616 years on either side of January 1, 1970.

The Date object has two static methods that are called without creating a Date object. They are parse and UTC.

Expand image Example

The following example illustrates the use of the Date object.
CopyCode image Copy Code
function DateDemo(){
   var d, s = "Today's date is: ";           //Declare variables.
   d = new Date();                           //Create Date object.
   s += (d.getMonth() + 1) + "/";            //Get month
   s += d.getDate() + "/";                   //Get day
   s += d.getYear();                         //Get year.
   return(s);                                //Return date.
}

Expand image Properties

constructor Property | prototype Property

Expand image Methods

getDate Method | getDay Method | getFullYear Method | getHours Method | getMilliseconds Method | getMinutes Method | getMonth Method | getSeconds Method | getTime Method | getTimezoneOffset Method | getUTCDate Method | getUTCDay Method | getUTCFullYear Method | getUTCHours Method | getUTCMilliseconds Method | getUTCMinutes Method | getUTCMonth Method | getUTCSeconds Method | getVarDate Method | getYear Method | parse Method | setDate Method | setFullYear Method | setHours Method | setMilliseconds Method | setMinutes Method | setMonth Method | setSeconds Method | setTime Method | setUTCDate Method | setUTCFullYear Method | setUTCHours Method | setUTCMilliseconds Method | setUTCMinutes Method | setUTCMonth Method | setUTCSeconds Method | setYear Method | toDateString Method | toGMTString Method | toLocaleDateString Method | toLocaleString Method | toLocaleTimeString Method | toString Method | toTimeString Method | toUTCString Method | UTC Method | valueOf Method

Expand image Requirements

Version 1

Expand image See Also

Reference

new Operator (JScript 5.6)
var Statement (JScript 5.6)


Enumerator Object (JScript 5.6)

JScript
Enumerator Object (JScript 5.6)
See Also Example
CollapseAll image DropDown image

Enables enumeration of items in a collection.

enumObj = new Enumerator([collection])

Expand image Arguments

enumObj

Required. The variable name to which the Enumerator object is assigned.

collection

Optional. Any Collection object.

Expand image Remarks

Collections differ from arrays in that the members of a collection are not directly accessible. Instead of using indexes, as you would with arrays, you can only move the current item pointer to the first or next element of a collection.

The Enumerator object provides a way to access any member of a collection and behaves similarly to the For...Each statement in VBScript.

Expand image Example

The following code shows the usage of the Enumerator object:

CopyCode image Copy Code
function ShowDriveList(){
   var fso, s, n, e, x;                     //Declare variables.
   fso = new ActiveXObject("Scripting.FileSystemObject");
   e = new Enumerator(fso.Drives);          //Create Enumerator on Drives.
   s = "";
   for (;!e.atEnd();e.moveNext())           //Enumerate drives collection.
      {
         x = e.item();
         s = s + x.DriveLetter;
         s += " - ";
         if (x.DriveType == 3)              //See if network drive.
            n = x.ShareName;                //Get share name
         else if (x.IsReady)                //See if drive is ready.
            n = x.VolumeName;               //Get volume name.
         else
            n = "[Drive not ready]";
         s +=  n + "<br>";
      }
   return(s);                               //Return active drive list.
}

Expand image Properties

The Enumerator object has no properties.

Expand image Methods

atEnd Method | item Method | moveFirst Method | moveNext Method

Expand image Requirements

Version 3

Expand image See Also

Reference

Boolean Object (JScript 5.6)


Error Object (JScript 5.6)

JScript
Error Object (JScript 5.6)
See Also Example
CollapseAll image DropDown image

Contains information about errors.

errorObj = new Error()
errorObj = new Error([number])
errorObj = new Error([number[, description]])

Expand image Arguments

errorObj

Required. The variable name to which the Error object is assigned.

number

Optional. Numeric value assigned to an error. Zero if omitted.

description

Optional. Brief string that describes an error. Empty string if omitted.

Expand image Remarks

Whenever a run-time error occurs, an instance of the Error object is created to describe the error. This instance has two intrinsic properties that contain the description of the error (description property) and the error number (number property).

An error number is a 32-bit value. The upper 16-bit word is the facility code, while the lower word is the actual error code.

Error objects can also be explicitly created, using the syntax shown above, or thrown using the throw statement. In both cases, you can add any properties you choose to expand the capability of the Error object.

Typically, the local variable that is created in a try...catch statement refers to the implicitly created Error object. As a result, you can use the error number and description in any way you choose.

Expand image Example

The following example illustrates the use of the implicitly created Error object.
CopyCode image Copy Code
try
   x = y   // Cause an error.
catch(e){   // Create local variable e.
   response.write(e)   // Prints "[object Error]".
   response.write(e.number & 0xFFFF)   // Prints 5009.
   response.write(e.description)   // Prints "'y' is undefined".
}

Expand image Methods

The Error object has no methods.

Expand image Properties

description Property | message Property | name Property | number Property

Expand image Requirements

Version 5

Expand image See Also

Reference

new Operator (JScript 5.6)
throw Statement (JScript 5.6)
try...catch...finally Statement (JScript 5.6)
var Statement (JScript 5.6)


Function Object (JScript 5.6)

JScript
Function Object (JScript 5.6)
See Also
CollapseAll image DropDown image

Creates a new function.

function functionName([argname1 [, ...[, argnameN]]])
{
      body
}
functionName = new Function( [argname1, [... argnameN,]] body );

Expand image Arguments

functionName

Required. The name of the newly created function

argname1...argnameN

Optional. A list of arguments the function accepts.

body

Optional. A string that contains the block of JScript code to be executed when the function is called.

Expand image Remarks

The function is a basic data type in JScript. Syntax 1 creates a function value that JScript converts into a Function object when necessary. JScript converts Function objects created by Syntax 2 into function values at the time the function is called.

Syntax 1 is the standard way to create new functions in JScript. Syntax 2 is an alternative form used to create function objects explicitly.

For example, to create a function that adds the two arguments passed to it, you can do it in either of two ways:

Expand image Example 1

CopyCode image Copy Code
        function add(x, y)
{
   return(x + y);            //Perform addition and return results.
}

Expand image Example 2

CopyCode image Copy Code
var add = new Function("x", "y", "return(x+y)");

In either case, you call the function with a line of code similar to the following:

CopyCode image Copy Code
add(2, 3);
Note Note

When calling a function, ensure that you always include the parentheses and any required arguments. Calling a function without parentheses causes the text of the function to be returned instead of the results of the function.

Expand image Properties

0...n Properties |arguments Property | callee Property | caller Property | constructor Property | length Property (Function) | prototype Property

Expand image Methods

apply Method | call Method | toString Method | valueOf Method

Expand image Requirements

Version 2

Expand image See Also

Reference

function Statement (JScript 5.6)
new Operator (JScript 5.6)
var Statement (JScript 5.6)


Global Object (JScript 5.6)

JScript
Global Object (JScript 5.6)
See Also
CollapseAll image DropDown image

An intrinsic object whose purpose is to collect global methods into one object.

The Global object has no syntax. You call its methods directly.

Expand image Remarks

The Global object is never used directly, and cannot be created using the new operator. It is created when the scripting engine is initialized, thus making its methods and properties available immediately.

Expand image Properties

Infinity Property | NaN Property | undefined Property

Expand image Methods

decodeURI Method | decodeURIComponent Method | encodeURI Method | encodeURIComponent Method | escape Method | eval Method | isFinite Method | isNaN Method | parseFloat Method | parseInt Method | unescape Method

Expand image Requirements

Version 5

Expand image See Also

Reference

Object Object (JScript 5.6)


Math Object (JScript 5.6)

JScript
Math Object (JScript 5.6)
See Also
CollapseAll image DropDown image

An intrinsic object that provides basic mathematics functionality and constants.

Math.[{property | method}]

Expand image Arguments

property

Required. Name of one of the properties of the Math. object.

method

Required. Name of one of the methods of the Math. object.

Expand image Remarks

The Math object cannot be created using the new operator, and gives an error if you attempt to do so. The scripting engine creates it when the engine is loaded. All of its methods and properties are available to your script at all times.

Expand image Properties

E Property | LN2 Property | LN10 Property | LOG2E Property | LOG10E Property | PI Property | SQRT1_2 Property | SQRT2 Property

Expand image Methods

abs Method | acos Method | asin Method | atan Method | atan2 Method | ceil Method | cos Method | exp Method | floor Method | log Method | max Method | min Method | pow Method | random Method | round Method | sin Method | sqrt Method | tan Method

Expand image Requirements

Version 1

Expand image See Also

Reference

Number Object (JScript 5.6)


Number Object (JScript 5.6)

JScript
Number Object (JScript 5.6)
See Also
CollapseAll image DropDown image

An object representation of the number data type and placeholder for numeric constants.

numObj = new Number(value)

Expand image Arguments

numobj

Required. The variable name to which the Number object is assigned.

value

Required. The numeric value of the Number object being created.

Expand image Remarks

JScript creates Number objects as required from numerical values. It is rarely necessary to create Number objects explicitly.

The primary purposes for the Number object are to collect its properties into one object, and to allow numbers to be converted into strings via the toString method.

Expand image Properties

MAX_VALUE Property | MIN_VALUE Property | NaN Property | NEGATIVE_INFINITY Property | POSITIVE_INFINITY Property | constructor Property | prototype Property

Expand image Methods

toExponential Method | toFixed Method | toLocaleString Method | toPrecision Method | toString Method | valueOf Method

Expand image Requirements

Version 1

Expand image See Also

Reference

Math Object (JScript 5.6)
new Operator (JScript 5.6)


Object Object (JScript 5.6)

JScript
Object Object (JScript 5.6)
See Also
CollapseAll image DropDown image

Provides functionality common to all JScript objects.

obj = new Object([value])

Expand image Arguments

obj

Required. The variable name to which the Object object is assigned.

value

Optional. Any one of the JScript primitive data types (Number, Boolean, or String. If value is an object, the object is returned unmodified. If value is null, undefined, or not supplied, an object with no content is created.

Expand image Remarks

The Object object is contained in all other JScript objects; all of its methods and properties are available in all other objects. The methods can be redefined in user-defined objects, and are called by JScript at appropriate times. The toString method is an example of a frequently redefined Object method.

In this language reference, the description of each Object method includes both default and object-specific implementation information for the intrinsic JScript objects.

Expand image Properties

prototype Property | constructor Property | propertyIsEnumerable Property

Expand image Methods

isPrototypeOf Method | hasOwnProperty Method | toLocaleString Method | toString Method | valueOf Method

Expand image Requirements

Version 3

Expand image See Also

Reference

Function Object (JScript 5.6)
Global Object (JScript 5.6)


RegExp Object (JScript 5.6)

JScript
RegExp Object (JScript 5.6)
See Also Example
CollapseAll image DropDown image

An intrinsic global object that stores information about the results of regular expression pattern matches.

RegExp.property

Expand image Remarks

The required property argument can be any one of the RegExp object properties.

The RegExp object cannot be created directly, but is always available for use. Until a successful regular expression search has been completed, the initial values of the various properties of the RegExp object are as follows:

Property | Shorthand | Initial Value
index |  | -1
input | $_ | Empty string.
lastIndex |  | -1
lastMatch | $& | Empty string.
lastParen | $+ | Empty string.
leftContext | $` | Empty string.
rightContext | $' | Empty string.
$1 - $9 | $1 - $9 | Empty string.

Its properties have undefined as their value until a successful regular expression search has been completed.

The global RegExp object should not be confused with the Regular Expression object. Even though they sound like the same thing, they are separate and distinct. The properties of the global RegExp object contain continually updated information about each match as it occurs, while the properties of the Regular Expression object contain only information about the matches that occur with that instance of the Regular Expression.

Expand image Example

The following example illustrates the use of the global RegExp object.
CopyCode image Copy Code
function matchDemo(){
   var s;
   var re = new RegExp("d(b+)(d)","ig");
   var str = "cdbBdbsbdbdz";
   var arr = re.exec(str);
   s = "$1 contains: " + RegExp.$1 + "\n";
   s += "$2 contains: " + RegExp.$2 + "\n";
   s += "$3 contains: " + RegExp.$3;
   return(s);
}

Expand image Properties

$1...$9 Properties | index Property | input Property | lastIndex Property | lastMatch Property | lastParen Property | leftContext Property | rightContext Property

Expand image Methods

The RegExp object has no methods.

Expand image Requirements

Version 3

Expand image See Also

Reference

Regular Expression Object (JScript 5.6)
Regular Expression Syntax (Scripting)
String Object (JScript 5.6)


Regular Expression Object (JScript 5.6)

JScript
Regular Expression Object (JScript 5.6)
See Also Example
CollapseAll image DropDown image

An object that contains a regular expression pattern along with flags that identify how to apply the pattern.

re = /pattern/[flags]
re = new RegExp("pattern"[,"flags"])

Expand image Arguments

re

Required. The variable name to which the regular expression pattern is assigned.

pattern

Required. The regular expression pattern to use. If you use Syntax 1, delimit the pattern by "/" characters. If you use Syntax 2, enclose the pattern in quotation marks.

flags

Optional. Enclose flag in quotation marks if you use Syntax 2. Available flags, which may be combined, are:

  • g (global search for all occurrences of pattern)

  • i (ignore case)

  • m (multiline search)

Expand image Remarks

The Regular Expression object should not be confused with the global RegExp object. Even though they sound the same, they are separate and distinct. The properties of the Regular Expression object contain only information about one particular Regular Expression instance, while the properties of the global RegExp object contain continually updated information about each match as it occurs.

Regular Expression objects store patterns used when searching strings for character combinations. After the Regular Expression object is created, it is either passed to a string method, or a string is passed to one of the regular expression methods. Information about the most recent search performed is stored in the global RegExp object.

Use Syntax 1 when you know the search string ahead of time. Use Syntax 2 when the search string is changing frequently, or is unknown, such as strings taken from user input.

The pattern argument is compiled into an internal format before use. For Syntax 1, pattern is compiled as the script is loaded. For Syntax 2, pattern is compiled just before use, or when the compile method is called.

Expand image Example

The following example illustrates the use of the Regular Expression object by creating an object (re) containing a regular expression pattern with its associated flags. In this case, the resulting Regular Expression object is then used by the match method:
CopyCode image Copy Code
function MatchDemo(){
   var r, re;                     //Declare variables.
   var s = "The rain in Spain falls mainly in the plain";
   re = new RegExp("Spain","i");  //Create regular expression object.
   r = s.match(re);               //Find a match within string s.
   return(r);                     //Return results of match.
}

Expand image Properties

global Property | ignoreCase Property | multiline Property | source Property

Expand image Methods

compile Method | exec Method | test Method

Expand image Requirements

Version 3

Expand image See Also

Reference

RegExp Object (JScript 5.6)
Regular Expression Syntax (Scripting)
String Object (JScript 5.6)


String Object (JScript 5.6)

JScript
String Object (JScript 5.6)
See Also
CollapseAll image DropDown image

Allows manipulation and formatting of text strings and determination and location of substrings within strings.

newString = new String(["stringLiteral"])

Expand image Arguments

newString

Required. The variable name to which the String object is assigned.

stringLiteral

Optional. Any group of Unicode characters.

Expand image Remarks

String objects can be created implicitly using string literals. String objects created in this fashion (referred to as standard strings) are treated differently than String objects created using the new operator. All string literals share a common, global string object. If a property is added to a string literal, it is available to all standard string objects:

CopyCode image Copy Code
var alpha, beta;
alpha = "This is a string";
beta = "This is also a string";

alpha.test = 10;

In the previous example, test is now defined for beta and all future string literals. In the following example, however, added properties are treated differently:

CopyCode image Copy Code
var gamma, delta;
gamma = new String("This is a string");
delta = new String("This is also a string");

gamma.test = 10;

In this case, test is not defined for delta. Each String object declared as a new String object has its own set of members. This is the only case where String objects and string literals are handled differently.

Expand image Properties

constructor Property | length Property | prototype Property

Expand image Methods

anchor Method | big Method | blink Method | bold Method | charAt Method | charCodeAt Method | concat Method | fixed Method | fontcolor Method | fontsize Method | fromCharCode Method | indexOf Method | italics Method | lastIndexOf Method | link Method | localeCompare Method | match Method | replace Method | search Method | slice Method | small Method | split Method | strike Method | sub Method | substr Method | substring Method | sup Method | toLocaleLowerCase Method | toLocaleUpperCase Method | toLowerCase Method | toUpperCase Method | toString Method | valueOf Method

Expand image Requirements

Version 1

Expand image See Also

Reference

new Operator (JScript 5.6)


VBArray Object (JScript 5.6)

JScript
VBArray Object (JScript 5.6)
See Also Example
CollapseAll image DropDown image

Provides access to Visual Basic safe arrays.

varName = new VBArray(safeArray)

Expand image Arguments

varName

Required. The variable name to which the VBArray is assigned.

safeArray

Required. A VBArray value.

Expand image Remarks

VBArrays are read-only, and cannot be created directly. The safeArray argument must have obtained a VBArray value before being passed to the VBArray constructor. This can only be done by retrieving the value from an existing ActiveX or other object.

VBArrays can have multiple dimensions. The indices of each dimension can be different. The dimensions method retrieves the number of dimensions in the array; the lbound and ubound methods retrieve the range of indices used by each dimension.

Expand image Example

The following example consists of three parts. The first part is VBScript code to create a Visual Basic safe array. The second part is JScript code that converts the Visual Basic safe array to a JScript array. Both of these parts go into the <HEAD> section of an HTML page. The third part is the JScript code that goes in the <BODY> section to run the other two parts.

CopyCode image Copy Code
<HEAD>
<SCRIPT LANGUAGE="VBScript">
<!--
Function CreateVBArray()
   Dim i, j, k
   Dim a(2, 2)
   k = 1
   For i = 0 To 2
      For j = 0 To 2
         a(j, i) = k
         document.writeln(k)
         k = k + 1
      Next
      document.writeln("vbCRLF")
   Next
   CreateVBArray = a
End Function
-->
</SCRIPT>

<SCRIPT LANGUAGE="JScript">
<!--
function VBArrayTest(vbarray){
   var a = new VBArray(vbarray);
   var b = a.toArray();
   var i;
   for (i = 0; i < 9; i++)
   {
      document.writeln(b[i]);
   }
}
-->
</SCRIPT>
</HEAD>

<BODY>
<SCRIPT LANGUAGE="JScript">
<!--
   VBArrayTest(CreateVBArray());
-->
</SCRIPT>
</BODY>

Expand image Properties

The VBArray object has no properties.

Expand image Methods

dimensions Method | getItem Method | lbound Method | toArray Method | ubound Method

Expand image Requirements

Version 3

Expand image See Also

Reference

Array Object (JScript 5.6)


JScript Operators (JScript 5.6)

JScript
JScript Operators (JScript 5.6)
See Also
CollapseAll image DropDown image

The following table lists JScript operators.

Expand image Operators

Description | Language Element
Adds the value of an expression to the value of a variable and assigns the result to the variable. | Addition Assignment Operator (+=)
Sums two numbers or concatenates two strings. | Addition Operator (+)
Assigns a value to a variable. | Assignment Operator (=)
Performs a bitwise AND on the value of a variable and the value of an expression and assigns the result to the variable. | Bitwise AND Assignment Operator (&=)
Performs a bitwise AND on two expressions. | Bitwise AND Operator (&)
Shifts the bits of an expression to the left. | Bitwise Left Shift Operator (<<)
Performs a bitwise NOT (negation) on an expression. | Bitwise NOT Operator (~)
Performs a bitwise OR on the value of a variable and the value of an expression and assigns the result to the variable. | Bitwise OR Assignment Operator (|=)
Performs a bitwise OR on two expressions. | Bitwise OR Operator (|)
Shifts the bits of an expression to the right, maintaining sign. | Bitwise Right Shift Operator (>>)
Performs a bitwise exclusive OR on a variable and an expression and assigns the result to the variable. | Bitwise XOR Assignment Operator (^=)
Performs a bitwise exclusive OR on two expressions. | Bitwise XOR Operator (^)
Causes two expressions to be executed sequentially. | Comma Operator (,)
Returns a Boolean value indicating the result of the comparison. | Comparison Operators
List of compound assignment operators. | Compound Assignment Operators
Executes one of two expressions depending on a condition. | Conditional (ternary) Operator (?:)
Decrements a variable by one. | Decrement Operator (--)
Deletes a property from an object, or removes an element from an array. | delete Operator
Divides the value of a variable by the value of an expression and assigns the result to the variable. | Division Assignment Operator (/=)
Divides two numbers and returns a numeric result. | Division Operator (/)
Tests for the existence of a property in an object. | in Operator
Compares two expressions to determine if they are equal. | Equality Operator (==)
Compares two expressions to determine if one is greater than the other. | Greater than Operator (>)
Compares two expressions to determine if one is greater than or equal to the other. | Greater than or equal to Operator (>=)
Compares two expressions to determine if they are equal in value and of the same data type. | Identity Operator (===)
Increments a variable by one. | Increment Operator (++)
Compares two expressions to determine if they are unequal. | Inequality Operator (!=)
Returns a Boolean value that indicates whether or not an object is an instance of a particular class. | instanceof Operator
Left shifts the value of a variable by the number of bits specified in the value of an expression and assigns the result to the variable. | Left Shift Assignment Operator (<<=)
Compares two expressions to determine if one is less than the other. | Less than Operator (<)
Compares two expressions to determine if one is less than or equal to the other. | Less than or equal to Operator (<=)
Performs a logical conjunction on two expressions. | Logical AND Operator (&&)
Performs logical negation on an expression. | Logical NOT Operator (!)
Performs a logical disjunction on two expressions. | Logical OR Operator (||)
Divides the value of a variable by the value of an expression, and assigns the remainder to the variable. | Modulus Assignment Operator (%=)
Divides two numbers and returns the remainder. | Modulus Operator (%)
Multiplies the value of a variable by the value of an expression and assigns the result to the variable. | Multiplication Assignment Operator (*=)
Multiplies two numbers. | Multiplication Operator (*)
Creates a new object. | new Operator
Compares two expressions to determine that they are not equal in value or of the same data type. | Nonidentity Operator (!==)
Right shifts the value of a variable by the number of bits specified in the value of an expression, maintaining the sign, and assigns the result to the variable. | Right Shift Assignment Operator (>>=)
Subtracts the value of an expression from the value of a variable and assigns the result to the variable. | Subtraction Assignment Operator (-=)
Performs subtraction of two expressions. | Subtraction Operator (-)
Returns a string that identifies the data type of an expression. | typeof Operator
Indicates the negative value of a numeric expression. | Unary Negation Operator (-)
Right shifts the value of a variable by the number of bits specified in the value of an expression, without maintaining sign, and assigns the result to the variable. | Unsigned Right Shift Assignment Operator (>>>=)
Performs an unsigned right shift of the bits in an expression. | Unsigned Right Shift Operator (>>>)
Prevents an expression from returning a value. | void Operator

Expand image See Also

Concepts

Operator Precedence (JScript 5.6)


Addition Assignment Operator (+=) (JScript 5.6)

JScript
Addition Assignment Operator (+=) (JScript 5.6)
See Also
CollapseAll image DropDown image

Adds the value of an expression to the value of a variable and assigns the result to the variable.

result += expression

Expand image Arguments

result

Any variable.

expression

Any expression.

Expand image Remarks

Using this operator is exactly the same as specifying:

CopyCode image Copy Code
result = result + expression

The underlying subtype of the expressions determines the behavior of the += operator.

If | Then
Both expressions are numeric or Boolean | Add
Both expressions are strings | Concatenate
One expression is numeric and the other is a string | Concatenate

Expand image Requirements

Version 1

Expand image See Also

Reference

Addition Operator (+) (JScript 5.6)

Concepts

Operator Precedence (JScript 5.6)
Operator Summary (JScript 5.6)


Addition Operator (+) (JScript 5.6)

JScript
Addition Operator (+) (JScript 5.6)
See Also
CollapseAll image DropDown image

Adds the value of one numeric expression to another or concatenates two strings.

result = expression1 + expression2

Expand image Arguments

result

Any variable.

expression1

Any expression.

expression2

Any expression.

Expand image Remarks

The underlying subtype of the expressions determines the behavior of the + operator.

If | Then
Both expressions are numeric or Boolean | Add
Both expressions are strings | Concatenate
One expression is numeric and the other is a string | Concatenate

Expand image Requirements

Version 1

Expand image See Also

Reference

Addition Assignment Operator (+=) (JScript 5.6)

Concepts

Operator Precedence (JScript 5.6)
Operator Summary (JScript 5.6)


Assignment Operator (=) (JScript 5.6)

JScript
Assignment Operator (=) (JScript 5.6)
See Also
CollapseAll image DropDown image

Assigns a value to a variable.

result = expression

Expand image Arguments

result

Any variable.

expression

Any numeric expression.

Expand image Remarks

As the = operator behaves like other operators, expressions using it have a value in addition to assigning that value into variable. This means that you can chain assignment operators as follows:

CopyCode image Copy Code
j = k = l = 0;

j, k, and l equal zero after the example statement is executed.

Expand image Requirements

Version 1

Expand image See Also

Concepts

Operator Precedence (JScript 5.6)
Operator Summary (JScript 5.6)


Bitwise AND Assignment Operator (&=) (JScript 5.6)

JScript
Bitwise AND Assignment Operator (&=) (JScript 5.6)
See Also
CollapseAll image DropDown image

Performs a bitwise AND on the value of a variable and the value of an expression and assigns the result to the variable.

result &= expression

Expand image Arguments

result

Any variable.

expression

Any expression.

Expand image Remarks

Using this operator is exactly the same as specifying:

CopyCode image Copy Code
result = result & expression

The &= operator looks at the binary representation of the values of result and expression and does a bitwise AND operation on them. The output of this operation behaves like this:

CopyCode image Copy Code
0101    (result)
1100    (expression)
----
0100    (output)

Any time both of the expressions have a 1 in a digit, the result has a 1 in that digit. Otherwise, the result has a 0 in that digit.

Expand image Requirements

Version 1

Expand image See Also

Reference

Bitwise AND Operator (&) (JScript 5.6)

Concepts

Operator Precedence (JScript 5.6)
Operator Summary (JScript 5.6)


Bitwise AND Operator (&) (JScript 5.6)

JScript
Bitwise AND Operator (&) (JScript 5.6)
See Also
CollapseAll image DropDown image

Performs a bitwise AND on two expressions.

result = expression1 & expression2

Expand image Arguments

result

Any variable.

expression1

Any expression.

expression2

Any expression.

Expand image Remarks

The & operator looks at the binary representation of the values of two expressions and does a bitwise AND operation on them. The result of this operation behaves as follows:

CopyCode image Copy Code
0101   (expression1)
1100   (expression2)
----
0100   (result)

Any time both of the expressions have a 1 in a digit, the result has a 1 in that digit. Otherwise, the result has a 0 in that digit.

Expand image Requirements

Version 1

Expand image See Also

Reference

Bitwise AND Assignment Operator (&=) (JScript 5.6)

Concepts

Operator Precedence (JScript 5.6)
Operator Summary (JScript 5.6)


Bitwise Left Shift Operator (<<) (JScript 5.6)

JScript
Bitwise Left Shift Operator (<<) (JScript 5.6)
See Also
CollapseAll image DropDown image

Left shifts the bits of an expression.

result = expression1 << expression2

Expand image Arguments

result

Any variable.

expression1

Any expression.

expression2

Any expression.

Expand image Remarks

The << operator shifts the bits of expression1 left by the number of bits specified in expression2. For example:

CopyCode image Copy Code
var temp
temp = 14 << 2

The variable temp has a value of 56 because 14 (00001110 in binary) shifted left two bits equals 56 (00111000 in binary).

Expand image Requirements

Version 1

Expand image See Also

Reference

Left Shift Assignment Operator (<<=) (JScript 5.6)
Bitwise Right Shift Operator (>>) (JScript 5.6)
Unsigned Right Shift Operator (>>>) (JScript 5.6)

Concepts

Operator Precedence (JScript 5.6)
Operator Summary (JScript 5.6)


Bitwise NOT Operator (~) (JScript 5.6)

JScript
Bitwise NOT Operator (~) (JScript 5.6)
See Also
CollapseAll image DropDown image

Performs a bitwise NOT (negation) on an expression.

result = ~ expression

Expand image Arguments

result

Any variable.

expression

Any expression.

Expand image Remarks

All unary operators, such as the ~ operator, evaluate expressions as follows:

  • If applied to undefined or null expressions, a run-time error is raised.

  • Objects are converted to strings.

  • Strings are converted to numbers if possible. If not, a run-time error is raised.

  • Boolean values are treated as numbers (0 if false, 1 if true).

The operator is applied to the resulting number.

The ~ operator looks at the binary representation of the values of the expression and does a bitwise negation operation on it. The result of this operation behaves as follows:

CopyCode image Copy Code
0101   (expression)
----
1010   (result)

Any digit that is a 1 in the expression becomes a 0 in the result. Any digit that is a 0 in the expression becomes a 1 in the result.

Expand image Requirements

Version 1

Expand image See Also

Reference

Logical NOT Operator (!) (JScript 5.6)

Concepts

Operator Precedence (JScript 5.6)
Operator Summary (JScript 5.6)


Bitwise OR Assignment Operator (|=) (JScript 5.6)

JScript
Bitwise OR Assignment Operator (|=) (JScript 5.6)
See Also
CollapseAll image DropDown image

Performs a bitwise OR on the value of a variable and the value of an expression and assigns the result to the variable.

result |= expression

Expand image Arguments

result

Any variable.

expression

Any expression.

Expand image Remarks

Using this operator is exactly the same as specifying:

CopyCode image Copy Code
result = result | expression

The |= operator looks at the binary representation of the values of result and expression and does a bitwise OR operation on them. The result of this operation behaves like this:

CopyCode image Copy Code
0101    (result)
1100    (expression)
----
1101    (output)

Any time either of the expressions has a 1 in a digit, the result has a 1 in that digit. Otherwise, the result has a 0 in that digit.

Expand image Requirements

Version 1

Expand image See Also

Reference

Bitwise OR Operator (|) (JScript 5.6)

Concepts

Operator Precedence (JScript 5.6)
Operator Summary (JScript 5.6)


Bitwise OR Operator (|) (JScript 5.6)

JScript
Bitwise OR Operator (|) (JScript 5.6)
See Also
CollapseAll image DropDown image

Performs a bitwise OR on two expressions.

result = expression1 | expression2

Expand image Arguments

result

Any variable.

expression1

Any expression.

expression2

Any expression.

Expand image Remarks

The | operator looks at the binary representation of the values of two expressions and does a bitwise OR operation on them. The result of this operation behaves as follows:

CopyCode image Copy Code
0101   (expression1)
1100   (expression2)
----
1101   (result)

Any time either of the expressions has a 1 in a digit, the result will have a 1 in that digit. Otherwise, the result will have a 0 in that digit.

Expand image Requirements

Version 1

Expand image See Also

Reference

Bitwise OR Assignment Operator (|=) (JScript 5.6)

Concepts

Operator Precedence (JScript 5.6)
Operator Summary (JScript 5.6)


Bitwise Right Shift Operator (>>) (JScript 5.6)

JScript
Bitwise Right Shift Operator (>>) (JScript 5.6)
See Also
CollapseAll image DropDown image

Right shifts the bits of an expression, maintaining sign.

result = expression1 >> expression2

Expand image Arguments

result

Any variable.

expression1

Any expression.

expression2

Any expression.

Expand image Remarks

The >> operator shifts the bits of expression1 right by the number of bits specified in expression2. The sign bit of expression1 is used to fill the digits from the left. Digits shifted off the right are discarded. For example, after the following code is evaluated, temp has a value of -4: 14 (11110010 in binary) shifted right two bits equals -4 (11111100 in binary).

CopyCode image Copy Code
var temp
temp = -14 >> 2

Expand image Requirements

Version 1

Expand image See Also

Reference

Bitwise Left Shift Operator (<<) (JScript 5.6)
Right Shift Assignment Operator (>>=) (JScript 5.6)
Unsigned Right Shift Operator (>>>) (JScript 5.6)

Concepts

Operator Precedence (JScript 5.6)
Operator Summary (JScript 5.6)


Bitwise XOR Assignment Operator (^=) (JScript 5.6)

JScript
Bitwise XOR Assignment Operator (^=) (JScript 5.6)
See Also
CollapseAll image DropDown image

Performs a bitwise exclusive OR on a variable and an expression and assigns the result to the variable.

result ^= expression

Expand image Arguments

result

Any variable.

expression

Any expression.

Expand image Remarks

Using the ^= operator is exactly the same as specifying:

CopyCode image Copy Code
result = result ^ expression

The ^= operator looks at the binary representation of the values of two expressions and does a bitwise exclusive OR operation on them. The result of this operation behaves as follows:

CopyCode image Copy Code
0101    (result)
1100    (expression)
----
1001    (result)

When one, and only one, of the expressions has a 1 in a digit, the result has a 1 in that digit. Otherwise, the result has a 0 in that digit.

Expand image Requirements

Version 1

Expand image See Also

Reference

Bitwise XOR Operator (^) (JScript 5.6)

Concepts

Operator Precedence (JScript 5.6)
Operator Summary (JScript 5.6)


Bitwise XOR Operator (^) (JScript 5.6)

JScript
Bitwise XOR Operator (^) (JScript 5.6)
See Also
CollapseAll image DropDown image

Performs a bitwise exclusive OR on two expressions.

result = expression1 ^ expression2

Expand image Arguments

result

Any variable.

expression1

Any expression.

expression2

Any expression.

Expand image Remarks

The ^ operator looks at the binary representation of the values of two expressions and does a bitwise exclusive OR operation on them. The result of this operation behaves as follows:

CopyCode image Copy Code
0101   (expression1)
1100   (expression2)
----
1001   (result)

When one, and only one, of the expressions has a 1 in a digit, the result has a 1 in that digit. Otherwise, the result has a 0 in that digit.

Expand image Requirements

Version 1

Expand image See Also

Reference

Bitwise XOR Assignment Operator (^=) (JScript 5.6)

Concepts

Operator Precedence (JScript 5.6)
Operator Summary (JScript 5.6)


Comma Operator (,) (JScript 5.6)

JScript
Comma Operator (,) (JScript 5.6)
See Also
CollapseAll image DropDown image

Causes two expressions to be executed sequentially.

expression1, expression2

Expand image Arguments

expression1

Any expression.

expression2

Any expression.

Expand image Remarks

The , operator causes the expressions on either side of it to be executed in left-to-right order, and obtains the value of the expression on the right. The most common use for the , operator is in the increment expression of a for loop. For example:

CopyCode image Copy Code
for (i = 0; i < 10; i++, j++)
{
   k = i + j;
}

The for statement only allows a single expression to be executed at the end of every pass through a loop. The , operator is used to allow multiple expressions to be treated as a single expression, thereby getting around the restriction.

Expand image Requirements

Version 1

Expand image See Also

Reference

for Statement (JScript 5.6)

Concepts

Operator Precedence (JScript 5.6)
Operator Summary (JScript 5.6)


Comparison Operators (JScript 5.6)

JScript
Comparison Operators (JScript 5.6)
See Also
CollapseAll image DropDown image

Returns a Boolean value indicating the result of the comparison.

expression1 comparisonoperator expression2

Expand image Arguments

expression1

Any expression.

comparisonoperator

Any comparison operator.

expression2

Any expression.

Expand image Remarks

When comparing strings, JScript uses the Unicode character value of the string expression.

The following describes how the different groups of operators behave depending on the types and values of expression1 and expression2:

Relational (<, >, <=, >=)

  • Attempt to convert both expression1 and expression2 into numbers.

  • If both expressions are strings, do a lexicographical string comparison.

  • If either expression is NaN, return false.

  • Negative zero equals Positive zero.

  • Negative Infinity is less than everything including itself.

  • Positive Infinity is greater than everything including itself.

Equality (==, !=)

  • If the types of the two expressions are different, attempt to convert them to string, number, or Boolean.

  • NaN is not equal to anything including itself.

  • Negative zero equals positive zero.

  • null equals both null and undefined.

  • Values are considered equal if they are identical strings, numerically equivalent numbers, the same object, identical Boolean values, or (if different types) they can be coerced into one of these situations.

  • Every other comparison is considered unequal.

Identity (===, !==)

These operators behave identically to the equality operators except no type conversion is done, and the types must be the same to be considered equal.

Expand image Requirements

Version 1

Expand image See Also

Concepts

Operator Precedence (JScript 5.6)
Operator Summary (JScript 5.6)


Compound Assignment Operators

JScript
Compound Assignment Operators
See Also
CollapseAll image DropDown image

The following table lists JScript assignment operators.

Expand image Assignment Operators

Operator | Symbol
Addition | +=
Bitwise AND | &=
Bitwise Or | |=
Bitwise XOR | ^=
Division | /=
Left Shift | <<=
Modulus | %=
Multiplication | *=
Right Shift | >>=
Subtraction | -=
Unsigned Right Shift | >>>=

Expand image Requirements

Version Information

Expand image See Also

Reference

Assignment Operator (=) (JScript 5.6)


Conditional (Ternary) Operator (?:) (JScript 5.6)

JScript
Conditional (Ternary) Operator (?:) (JScript 5.6)
See Also
CollapseAll image DropDown image

Returns one of two expressions depending on a condition.

test ? expression1 : expression2

Expand image Arguments

test

Any Boolean expression.

expression1

An expression returned if test is true. May be a comma expression.

expression2

An expression returned if test is false. May be a comma expression.

Expand image Remarks

The ?: operator can be used as a shortcut for an if...else statement. It is typically used as part of a larger expression where an if...else statement would be awkward. For example:

CopyCode image Copy Code
var now = new Date();
var greeting = "Good" + ((now.getHours() > 17) ? " evening." : " day.");

The example creates a string containing "Good evening." if it is after 6pm. The equivalent code using an if...else statement would look as follows:

CopyCode image Copy Code
var now = new Date();
var greeting = "Good";
if (now.getHours() > 17)
   greeting += " evening.";
else
   greeting += " day.";

Expand image Requirements

Version 1

Expand image See Also

Reference

if...else Statement (JScript 5.6)

Concepts

Operator Precedence (JScript 5.6)
Operator Summary (JScript 5.6)


delete Operator (JScript 5.6)

JScript
delete Operator (JScript 5.6)
See Also
CollapseAll image DropDown image

Deletes a property from an object, or removes an element from an array.

delete expression

Expand image Remarks

The expression argument is a valid JScript expression that usually results in a property name or array element.

If the result of expression is an object, the property specified in expression exists, and the object will not allow it to be deleted, false is returned.

In all other cases, true is returned.

Expand image Requirements

Version 3

Expand image See Also

Concepts

Operator Precedence (JScript 5.6)
Operator Summary (JScript 5.6)


Division Assignment Operator (/=) (JScript 5.6)

JScript
Division Assignment Operator (/=) (JScript 5.6)
See Also
CollapseAll image DropDown image

Divides the value of a variable by the value of an expression and assigns the result to the variable.

result /= expression

Expand image Arguments

result

Any numeric variable.

expression

Any numeric expression.

Expand image Remarks

Using the /= operator is exactly the same as specifying:

CopyCode image Copy Code
result = result / expression

Expand image Requirements

Version 1

Expand image See Also

Reference

Division Operator (/) (JScript 5.6)

Concepts

Operator Precedence (JScript 5.6)
Operator Summary (JScript 5.6)


Division Operator (/) (JScript 5.6)

JScript
Division Operator (/) (JScript 5.6)
See Also
CollapseAll image DropDown image

Divides the value of two expressions.

result = number1 / number2

Expand image Arguments

result

Any numeric variable.

number1

Any numeric expression.

number2

Any numeric expression.

Expand image Requirements

Version 1

Expand image See Also

Reference

Division Assignment Operator (/=) (JScript 5.6)

Concepts

Operator Precedence (JScript 5.6)
Operator Summary (JScript 5.6)


in Operator (JScript 5.6)

JScript
in Operator (JScript 5.6)
See Also
CollapseAll image DropDown image

Tests for the existence of a property in an object.

result = property in object

Expand image Arguments

result

Required. Any variable.

property

Required. An expression that evaluates to a string expression.

object

Required. Any object.

Expand image Remarks

The in operator checks if an object has a property named property. It also checks the object's prototype to see if the property is part of the prototype chain.

Expand image Requirements

Version 1

Expand image See Also

Concepts

Operator Precedence (JScript 5.6)
Operator Summary (JScript 5.6)


Increment (++) and Decrement (--) Operators (JScript 5.6)

JScript
Increment (++) and Decrement (--) Operators (JScript 5.6)
See Also
CollapseAll image DropDown image

Increments or decrements the value of a variable by one.

result = ++variable
result = --variable
result = variable++
result = variable--
++variable
--variable
variable++
variable--

Expand image Arguments

result

Any variable.

variable

Any variable.

Expand image Remarks

The increment and decrement operators are used as a shortcut to modify the value stored in a variable. The value of an expression containing one of these operators depends on whether the operator comes before or after the variable:

CopyCode image Copy Code
var j, k;
k = 2;
j = ++k;

j is assigned the value 3, as the increment occurs before the expression is evaluated.

Contrast the following example:

CopyCode image Copy Code
var j, k;
k = 2;
j = k++;

Here, j is assigned the value 2, as the increment occurs after the expression is evaluated.

Expand image Requirements

Version 1

Expand image See Also

Concepts

Operator Precedence (JScript 5.6)
Operator Summary (JScript 5.6)


instanceof Operator (JScript 5.6)

JScript
instanceof Operator (JScript 5.6)
See Also Example
CollapseAll image DropDown image

Returns a Boolean value that indicates whether or not an object is an instance of a particular class.

result = object instanceof class

Expand image Arguments

result

Required. Any variable.

object

Required. Any object expression.

class

Required. Any defined object class.

Expand image Remarks

The instanceof operator returns true if object is an instance of class. It returns false if object is not an instance of the specified class, or if object is null.

Expand image Example

The following example illustrates the use of the instanceof operator.
CopyCode image Copy Code
function objTest(obj){
   var i, t, s = "";   // Create variables.
   t = new Array();   // Create an array.
   t["Date"] = Date;   // Populate the array.
   t["Object"] = Object;
   t["Array"] = Array;
      for (i in t)
      {
         if (obj instanceof t[i])   // Check class of obj.
         {
            s += "obj is an instance of " + i + "\n";
         }
         else
         {
            s += "obj is not an instance of " + i + "\n";
         }
   }
   return(s);   // Return string.
}

var obj = new Date();
response.write(objTest(obj));

Expand image Requirements

Version 5

Expand image See Also

Concepts

Operator Precedence (JScript 5.6)
Operator Summary (JScript 5.6)


Left Shift Assignment Operator (<<=) (JScript 5.6)

JScript
Left Shift Assignment Operator (<<=) (JScript 5.6)
See Also
CollapseAll image DropDown image

Left shifts the value of a variable by the number of bits specified in the value of an expression and assigns the result to the variable.

result <<= expression

Expand image Arguments

result

Any variable.

expression

Any expression.

Expand image Remarks

Using the <<= operator is exactly the same as specifying:

CopyCode image Copy Code
result = result << expression

The <<= operator shifts the bits of result left by the number of bits specified in expression. For example:

CopyCode image Copy Code
var temp
temp = 14
temp <<= 2

The variable temp has a value of 56 because 14 (00001110 in binary) shifted left two bits equals 56 (00111000 in binary). Bits are filled in with zeroes when shifting.

Expand image Requirements

Version 1

Expand image See Also

Reference

Bitwise Left Shift Operator (<<) (JScript 5.6)
Bitwise Right Shift Operator (>>) (JScript 5.6)
Unsigned Right Shift Operator (>>>) (JScript 5.6)

Concepts

Operator Precedence (JScript 5.6)
Operator Summary (JScript 5.6)


Logical AND Operator (&&) (JScript 5.6)

JScript
Logical AND Operator (&&) (JScript 5.6)
See Also
CollapseAll image DropDown image

Performs a logical conjunction on two expressions.

result = expression1 && expression2

Expand image Arguments

result

Any variable.

expression1

Any expression.

expression2

Any expression.

Expand image Remarks

If, and only if, both expressions evaluate to True, result is True. If either expression evaluates to False, result is False.

JScript uses the following rules for converting non-Boolean values to Boolean values:

  • All objects are considered true.

  • Strings are considered false if, and only if, they are empty.

  • null and undefined are considered false.

  • Numbers are false if, and only if, they are zero.

Expand image Requirements

Version 1

Expand image See Also

Concepts

Operator Precedence (JScript 5.6)
Operator Summary (JScript 5.6)


Logical NOT Operator (!) (JScript 5.6)

JScript
Logical NOT Operator (!) (JScript 5.6)
See Also
CollapseAll image DropDown image

Performs logical negation on an expression.

result = !expression

Expand image Arguments

result

Any variable.

expression

Any expression.

Expand image Remarks

The following table illustrates how result is determined.

If expression is | Then result is
True | False
False | True

All unary operators, such as the ! operator, evaluate expressions as follows:

  • If applied to undefined or null expressions, a run-time error is raised.

  • Objects are converted to strings.

  • Strings are converted to numbers if possible. If not, a run-time error is raised.

  • Boolean values are treated as numbers (0 if false, 1 if true).

The operator is applied to the resulting number.

For the ! operator, if expression is nonzero, result is zero. If expression is zero, result is 1.

Expand image Requirements

Version 1

Expand image See Also

Reference

Bitwise NOT Operator (~) (JScript 5.6)

Concepts

Operator Precedence (JScript 5.6)
Operator Summary (JScript 5.6)


Logical OR Operator (||) (JScript 5.6)

JScript
Logical OR Operator (||) (JScript 5.6)
See Also
CollapseAll image DropDown image

Performs a logical disjunction on two expressions.

result = expression1 || expression2

Expand image Arguments

result

Any variable.

expression1

Any expression.

expression2

Any expression.

Expand image Remarks

If either or both expressions evaluate to True, result is True. The following table illustrates how result is determined:

If expression1 is | And expression2 is | The result is
True | True | True
True | False | True
False | True | True
False | False | False

JScript uses the following rules for converting non-Boolean values to Boolean values:

  • All objects are considered true.

  • Strings are considered false if and only if they are empty.

  • null and undefined are considered false.

  • Numbers are false if, and only if, they are 0.

Expand image Requirements

Version 1

Expand image See Also

Concepts

Operator Precedence (JScript 5.6)
Operator Summary (JScript 5.6)


Modulus Assignment Operator (%=) (JScript 5.6)

JScript
Modulus Assignment Operator (%=) (JScript 5.6)
See Also
CollapseAll image DropDown image

Divides the value of a variable by the value of an expression, and assigns the remainder to the variable.

result %= expression

Expand image Arguments

result

Any variable.

expression

Any numeric expression.

Expand image Remarks

Using the %= operator is exactly the same as specifying:

CopyCode image Copy Code
result = result % expression

Expand image Requirements

Version 1

Expand image See Also

Reference

Modulus Operator (%) (JScript 5.6)

Concepts

Operator Precedence (JScript 5.6)
Operator Summary (JScript 5.6)


Modulus Operator (%) (JScript 5.6)

JScript
Modulus Operator (%) (JScript 5.6)
See Also
CollapseAll image DropDown image

Divides the value of one expression by the value of another, and returns the remainder.

result = number1 % number2

Expand image Arguments

result

Any variable.

number1

Any numeric expression.

number2

Any numeric expression.

Expand image Remarks

The modulus, or remainder, operator divides number1 by number2 and returns only the remainder as result. The sign of result is the same as the sign of number1. The value of result is between 0 and the absolute value of number2.

For example, in the following expression, A (which is result) equals 5.6.

CopyCode image Copy Code
A = 19 % 6.7

Expand image Requirements

Version 1

Expand image See Also

Reference

Modulus Assignment Operator (%=) (JScript 5.6)

Concepts

Operator Precedence (JScript 5.6)
Operator Summary (JScript 5.6)


Multiplication Assignment Operator (*=) (JScript 5.6)

JScript
Multiplication Assignment Operator (*=) (JScript 5.6)
See Also
CollapseAll image DropDown image

Multiplies the value of a variable by the value of an expression and assigns the result to the variable.

result *= expression

Expand image Arguments

result

Any variable.

expression

Any expression.

Expand image Remarks

Using the *= operator is exactly the same as specifying:

CopyCode image Copy Code
result = result * expression

Expand image Requirements

Version 1

Expand image See Also

Reference

Multiplication Operator (*) (JScript 5.6)

Concepts

Operator Precedence (JScript 5.6)
Operator Summary (JScript 5.6)


Multiplication Operator (*) (JScript 5.6)

JScript
Multiplication Operator (*) (JScript 5.6)
See Also
CollapseAll image DropDown image

Multiplies the value of two expressions.

result = number1*number2

Expand image Arguments

result

Any variable.

number1

Any expression.

number2

Any expression.

Expand image Requirements

Version 1

Expand image See Also

Reference

Multiplication Assignment Operator (*=) (JScript 5.6)

Concepts

Operator Precedence (JScript 5.6)
Operator Summary (JScript 5.6)


new Operator (JScript 5.6)

JScript
new Operator (JScript 5.6)
See Also
CollapseAll image DropDown image

Creates a new object.

new constructor[(arguments)]

Expand image Arguments

constructor

Required. Object's constructor. The parentheses can be omitted if the construc

tor takes no arguments.

arguments

Optional. Any arguments to be passed to the new object's constructor.

Expand image Remarks

The new operator performs the following tasks:

  • It creates an object with no members.

  • It calls the constructor for that object, passing a pointer to the newly created object as the this pointer.

  • The constructor then initializes the object according to the arguments passed to the constructor.

These are examples of valid uses of the new operator.

CopyCode image Copy Code
my_object = new Object;
my_array = new Array();
my_date = new Date("Jan 5 1996");

Expand image Requirements

Version 1

Expand image See Also

Reference

function Statement (JScript 5.6)


Right Shift Assignment Operator (>>=) (JScript 5.6)

JScript
Right Shift Assignment Operator (>>=) (JScript 5.6)
See Also
CollapseAll image DropDown image

Right shifts the value of a variable by the number of bits specified in the value of an expression, maintaining the sign, and assigns the result to the variable.

result >>= expression

Expand image Arguments

result

Any variable.

expression

Any expression.

Expand image Remarks

Using the >>= operator is exactly the same as specifying:

CopyCode image Copy Code
result = result >> expression

The >>= operator shifts the bits of result right by the number of bits specified in expression. The sign bit of result is used to fill the digits from the left. Digits shifted off the right are discarded. For example, after the following code is evaluated, temp has a value of -4: 14 (11110010 in binary) shifted right two bits equals -4 (11111100 in binary).

CopyCode image Copy Code
var temp
temp = -14
temp >>= 2

Expand image Requirements

Version 1

Expand image See Also

Reference

Bitwise Left Shift Operator (<<) (JScript 5.6)
Bitwise Right Shift Operator (>>) (JScript 5.6)
Unsigned Right Shift Operator (>>>) (JScript 5.6)

Concepts

Operator Precedence (JScript 5.6)
Operator Summary (JScript 5.6)


Subtraction Assignment Operator (-=) (JScript 5.6)

JScript
Subtraction Assignment Operator (-=) (JScript 5.6)
See Also
CollapseAll image DropDown image

Subtracts the value of an expression from the value of a variable and assigns the result to the variable.

result -= expression

Expand image Arguments

result

Any numeric variable.

expression

Any numeric expression.

Expand image Remarks

Using the -= operator is exactly the same as doing the following:

CopyCode image Copy Code
result = result – expression

Expand image Requirements

Version 1

Expand image See Also

Reference

Subtraction Operator (-) (JScript 5.6)

Concepts

Operator Precedence (JScript 5.6)
Operator Summary (JScript 5.6)


Subtraction Operator (-) (JScript 5.6)

JScript
Subtraction Operator (-) (JScript 5.6)
See Also
CollapseAll image DropDown image

Subtracts the value of one expression from another or provides unary negation of a single expression.

result = number1 - number2
-number

Expand image Arguments

result

Any numeric variable.

number

Any numeric expression.

number1

Any numeric expression.

number2

Any numeric expression.

Expand image 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.

For Syntax 2, as for all unary operators, expressions are evaluated as follows:

  • If applied to undefined or null expressions, a run-time error is raised.

  • Objects are converted to strings.

  • Strings are converted to numbers if possible. If not, a run-time error is raised.

  • Boolean values are treated as numbers (0 if false, 1 if true).

The operator is applied to the resulting number. In Syntax 2, if the resulting number is nonzero, result is equal to the resulting number with its sign reversed. If the resulting number is zero, result is zero.

Expand image Requirements

Version 1

Expand image See Also

Reference

Subtraction Assignment Operator (-=) (JScript 5.6)

Concepts

Operator Precedence (JScript 5.6)
Operator Summary (JScript 5.6)


typeof Operator (JScript 5.6)

JScript
typeof Operator (JScript 5.6)
See Also
CollapseAll image DropDown image

Returns a string that identifies the data type of an expression.

typeof[(]expression[)] ;

Expand image Remarks

The expression argument is any expression for which type information is sought.

The typeof operator returns type information as a string. There are six possible values that typeof returns: "number," "string," "boolean," "object," "function," and "undefined."

The parentheses are optional in the typeof syntax.

Expand image Requirements

Version 1

Expand image See Also

Concepts

Operator Precedence (JScript 5.6)
Operator Summary (JScript 5.6)


Unsigned Right Shift Assignment Operator (>>>=) (JScript 5.6)

JScript
Unsigned Right Shift Assignment Operator (>>>=) (JScript 5.6)
See Also
CollapseAll image DropDown image

Right shifts the value of a variable by the number of bits specified in the value of an expression, without maintaining sign, and assigns the result to the variable.

result >>>= expression

Expand image Arguments

result

Any variable.

expression

Any expression.

Expand image Remarks

Using the >>>= operator is exactly the same as doing the following:

CopyCode image Copy Code
result = result >>> expression

The >>>= operator shifts the bits of result right by the number of bits specified in expression. Zeroes are filled in from the left. Digits shifted off the right are discarded. For example:

CopyCode image Copy Code
var temp
temp = -14
temp >>>= 2

The variable temp has a value of 1073741820 as -14 (11111111 11111111 11111111 11110010 in binary) shifted right two bits equals 1073741820 (00111111 11111111 11111111 11111100 in binary).

Expand image Requirements

Version 1

Expand image See Also

Reference

Unsigned Right Shift Operator (>>>) (JScript 5.6)
Bitwise Left Shift Operator (<<) (JScript 5.6)
Bitwise Right Shift Operator (>>) (JScript 5.6)

Concepts

Operator Precedence (JScript 5.6)
Operator Summary (JScript 5.6)


Unsigned Right Shift Operator (>>>) (JScript 5.6)

JScript
Unsigned Right Shift Operator (>>>) (JScript 5.6)
See Also
CollapseAll image DropDown image

Right shifts the bits of an expression, without maintaining sign.

result = expression1 >>> expression2

Expand image Arguments

result

Any variable.

expression1

Any expression.

expression2

Any expression.

Expand image Remarks

The >>> operator shifts the bits of expression1 right by the number of bits specified in expression2. Zeroes are filled in from the left. Digits shifted off the right are discarded. For example:

CopyCode image Copy Code
var temp
temp = -14 >>> 2

The variable temp has a value of 1073741820 as -14 (11111111 11111111 11111111 11110010 in binary) shifted right two bits equals 1073741820 (00111111 11111111 11111111 11111100 in binary).

Expand image Requirements

Version 1

Expand image See Also

Reference

Unsigned Right Shift Assignment Operator (>>>=) (JScript 5.6)
Bitwise Left Shift Operator (<<) (JScript 5.6)
Bitwise Right Shift Operator (>>) (JScript 5.6)

Concepts

Operator Precedence (JScript 5.6)
Operator Summary (JScript 5.6)


void Operator (JScript 5.6)

JScript
void Operator (JScript 5.6)
See Also
CollapseAll image DropDown image

Prevents an expression from returning a value.

void expression

Expand image Remarks

The expression argument is any valid JScript expression.

The void operator evaluates its expression, and returns undefined. It is most useful in situations where you want an expression evaluated but do not want the results visible to the remainder of the script.

Expand image Requirements

Version 2

Expand image See Also

Concepts

Operator Precedence (JScript 5.6)
Operator Summary (JScript 5.6)


JScript Properties

JScript
JScript Properties
See Also
CollapseAll image DropDown image

The following table lists JScript properties.

Expand image Properties

Description | Language Element
Returns the value of individual arguments from an arguments object. | 0...n Properties
Returns the nine most-recently memorized portions found during pattern matching. | $1...$9 Properties
Returns an array containing each argument passed to the currently executing function. | arguments Property
Returns the Function object being executed. | callee Property
Returns a reference to the function that invoked the current function. | caller Property
Specifies the function that creates an object. | constructor Property
Returns or sets the descriptive string associated with a specific error. | description Property
Returns Euler's constant, the base of natural logarithms. | E Property
Returns a Boolean value indicating the state of the global flag (g) used with a regular expression. | global Property
Returns a Boolean value indicating the state of the ignoreCase flag (i) used with a regular expression. | ignoreCase Property
Returns the character position where the first successful match begins in a searched string. | index Property
Returns an initial value of Number.POSITIVE_INFINITY. | Infinity Property
Returns the string against which a search was performed. | input Property
Returns the character position where the last successful match begins in a searched string. | lastIndex Property
Returns the last matched characters from any regular expression search. | lastMatch Property
Returns the last parenthesized submatch from any regular expression search, if any. | lastParen Property
Returns the characters from the beginning of a searched string up to the position before the beginning of the last match. | leftContext Property
Returns the actual number of arguments passed to a function by the caller. | length Property (arguments)
Returns an integer value one higher than the highest element defined in an array. | length Property (Array)
Returns the number of arguments defined for a function. | length Property (Function)
Returns the length of a String object. | length Property (String)
Returns the natural logarithm of 2. | LN2 Property
Returns the natural logarithm of 10. | LN10 Property
Returns the base-2 logarithm of e, Euler's constant. | LOG2E Property
Returns the base-10 logarithm of e, Euler's constant. | LOG10E Property
Returns the largest number that can be represented in JScript. | MAX_VALUE Property
Returns an error message string. | message Property
Returns the number closest to zero that can be represented in JScript. | MIN_VALUE Property
Returns a Boolean value indicating the state of the multiline flag (m) used with a regular expression. | multiline Property
Returns the name of an error. | name Property
Returns the special value NaN indicating that an expression is not a number. | NaN Property (Global)
Returns the special value (NaN) indicating that an expression is not a number. | NaN Property (Number)
Returns a value more negative than the largest negative number (-Number.MAX_VALUE) that can be represented in JScript. | NEGATIVE_INFINITY Property
Returns or sets the numeric value associated with a specific error. | number Property
Returns the ratio of the circumference of a circle to its diameter, approximately 3.141592653589793. | PI Property
Returns a value larger than the largest number (Number.MAX_VALUE) that can be represented in JScript. | POSITIVE_INFINITY Property
Returns a Boolean value indicating whether a specified property is part of an object and if it is enumerable. | propertyIsEnumerable Property
Returns a reference to the prototype for a class of objects. | prototype Property
Returns the characters from the position following the last match to the end of the searched string. | rightContext Property
Returns a copy of the text of the regular expression pattern. | source Property
Returns the square root of 0.5, or one divided by the square root of 2. | SQRT1_2 Property
Returns the square root of 2. | SQRT2 Property
Returns an initial value of undefined. | undefined Property

Expand image See Also

Reference

JScript Methods


0...n Properties (JScript 5.6)

JScript
0...n Properties (JScript 5.6)
See Also Example
CollapseAll image DropDown image

Returns the actual value of individual arguments from an arguments object returned by the arguments property of an executing function.

[function.]arguments[[0|1|2|...|n]]

Expand image Arguments

function

Optional. The name of the currently executing Function object.

0, 1, 2, , n

Required. Non-negative integer in the range of 0 to n where 0 represents the first argument and n represents the final argument. The value of the final argument n is arguments.length-1.

Expand image Remarks

The values returned by the 0 . . . n properties are the actual values passed to the executing function. While not actually an array of arguments, the individual arguments that comprise the arguments object are accessed the same way that array elements are accessed.

Expand image Example

The following example illustrates the use of the 0 . . . n properties of the arguments object. To fully understand the example, pass one or more arguments to the function:
CopyCode image Copy Code
function ArgTest(){
   var s = "";
   s += "The individual arguments are: "
   for (n=0; n< arguments.length; n++){
      s += ArgTest.arguments[n];
      s += " ";
   }
   return(s);
}
print(ArgTest(1, 2, "hello", new Date()));

Expand image Requirements

Version 5.5

Applies To: arguments Object (JScript 5.6)| Function Object (JScript 5.6)

Expand image See Also

Reference

length Property (arguments) (JScript 5.6)
length Property (Function) (JScript 5.6)


$1...$9 Properties (JScript 5.6)

JScript
$1...$9 Properties (JScript 5.6)
See Also
CollapseAll image DropDown image

Returns the nine most-recently memorized portions found during pattern matching. Read-only.

RegExp.$n

Expand image Arguments

RegExp

Always the global RegExp object.

n

Any integer from 1 through 9.

Expand image Remarks

The value of the $1...$9 properties is modified whenever a successful parenthesized match is made. Any number of parenthesized substrings may be specified in a regular expression pattern, but only the nine most recent can be stored.

The following example illustrates the use of the $1...$9 properties:

CopyCode image Copy Code
function matchDemo(){
   var s;
   var re = new RegExp("d(b+)(d)","ig");
   var str = "cdbBdbsbdbdz";
   var arr = re.exec(str);
   s = "$1 contains: " + RegExp.$1 + "\n";
   s += "$2 contains: " + RegExp.$2 + "\n";
   s += "$3 contains: " + RegExp.$3;
   return(s);
}

Expand image Requirements

Version 1

Applies To: RegExp Object (JScript 5.6)

Expand image See Also

Reference

Regular Expression Syntax (Scripting)


arguments Property (JScript 5.6)

JScript
arguments Property (JScript 5.6)
See Also Example
CollapseAll image DropDown image

Returns the arguments object for the currently executing Function object.

function.arguments

Expand image Remarks

The function argument is the name of the currently executing function, and can be omitted.

The arguments property allows a function to handle a variable number of arguments. The length property of the arguments object contains the number of arguments passed to the function. The individual arguments contained in the arguments object can be accessed in the same way array elements are accessed.

Expand image Example

The following example illustrates the use of the arguments property:
CopyCode image Copy Code
function ArgTest(){
   var i, s, numargs = arguments.length;
   s = numargs;
   if (numargs < 2)
      s += " argument was passed to ArgTest. It was ";
   else
      s += " arguments were passed to ArgTest. They were " ;
   for (i = 0; i < numargs; i++)
      {
         s += arguments[i] + " ";
      }
   return(s);
}

Expand image Requirements

Version 2

Applies To: Function Object (JScript 5.6)

Expand image See Also

Reference

arguments Object (JScript 5.6)
function Statement (JScript 5.6)


callee Property (JScript 5.6)

JScript
callee Property (JScript 5.6)
See Also Example
CollapseAll image DropDown image

Returns the Function object being executed, that is, the body text of the specified Function object.

[function.]arguments.callee

Expand image Remarks

The optional function argument is the name of the currently executing Function object.

The callee property is a member of the arguments object that becomes available only when the associated function is executing.

The initial value of the callee property is the Function object being executed. This allows anonymous functions to be recursive.

Expand image Example

CopyCode image Copy Code
function factorial(n){
  if (n <= 0)
  return 1;
  else
    return n * arguments.callee(n - 1)
}
print(factorial(3));

Expand image Requirements

Version 5.5

Applies To: arguments Object (JScript 5.6)| Function Object (JScript 5.6)

Expand image See Also

Reference

caller Property (JScript 5.6)


caller Property (JScript 5.6)

JScript
caller Property (JScript 5.6)
See Also
CollapseAll image DropDown image

Returns a reference to the function that invoked the current function.

functionName.caller

Expand image Remarks

The functionName object is the name of any executing function.

The caller property is only defined for a function while that function is executing. If the function is called from the top level of a JScript program, caller contains null.

If the caller property is used in a string context, the result is the same as functionName.toString, that is, the decompiled text of the function is displayed.

The following example illustrates the use of the caller property:

CopyCode image Copy Code
function CallLevel(){
   if (CallLevel.caller == null)
      return("CallLevel was called from the top level.");
   else
      return("CallLevel was called by another function.");
}

Expand image Requirements

Version 2

Applies To: arguments Object (JScript 5.6)| Function Object (JScript 5.6)

Expand image See Also

Reference

function Statement (JScript 5.6)


constructor Property (JScript 5.6)

JScript
constructor Property (JScript 5.6)
See Also
CollapseAll image DropDown image

Specifies the function that creates an object.

object.constructor

Expand image Remarks

The required object is the name of an object or function.

The constructor property is a member of the prototype of every object that has a prototype. This includes all intrinsic JScript objects except the Global and Math objects. The constructor property contains a reference to the function that constructs instances of that particular object. For example:

CopyCode image Copy Code
x = new String("Hi");
if (x.constructor == String)
   // Do something (the condition will be true).

or

CopyCode image Copy Code
function MyFunc {
   // Body of function.
}

y = new MyFunc;
if (y.constructor == MyFunc)
   // Do something (the condition will be true).

Expand image Requirements

Version 2

Applies To: Array Object (JScript 5.6)| Boolean Object (JScript 5.6)| Date Object (JScript 5.6)| Function Object (JScript 5.6)| Math Object (JScript 5.6)| Number Object (JScript 5.6)| Object Object (JScript 5.6)| String Object (JScript 5.6)

Expand image See Also

Reference

prototype Property (JScript 5.6)


description Property (JScript 5.6)

JScript
description Property (JScript 5.6)
See Also
CollapseAll image DropDown image

Returns or sets the descriptive string associated with a specific error.

object.description [= stringExpression]

Expand image Arguments

object

Required. Any instance of an Error object.

stringExpression

Optional. A string expression containing a description of the error.

Expand image Remarks

The description property contains the error message string associated with a specific error. Use the value contained in this property to alert a user to an error that you can't or don't want to handle.

The following example illustrates the use of the description property:

CopyCode image Copy Code
try
   x = y   // Cause an error.
catch(var e){   // Create local variable e.
   document.write(e)   // Prints "[object Error]".
   document.write((e.number & 0xFFFF))   // Prints 5009.
   document.write(e.description)   // Prints "'y' is undefined".
}

Expand image Requirements

Version 5

Applies To: Error Object (JScript 5.6)

Expand image See Also

Reference

number Property (JScript 5.6)
message Property (JScript 5.6)
name Property (JScript 5.6)


E Property (JScript 5.6)

JScript
E Property (JScript 5.6)
See Also
CollapseAll image DropDown image

Returns the mathematical constant e, the base of natural logarithms. The E property is approximately equal to 2.718.

numVar = Math.E

Expand image Requirements

Version 1

Applies To: Math Object (JScript 5.6)

Expand image See Also

Reference

exp Method (JScript 5.6)


global Property (JScript 5.6)

JScript
global Property (JScript 5.6)
See Also Example
CollapseAll image DropDown image

Returns a Boolean value indicating the state of the global flag (g) used with a regular expression. Default is false. Read-only.

rgExp.global

Expand image Remarks

The required rgExp reference is an instance of a Regular Expression object.

The global property returns true if the global flag is set for a regular expression, and returns false if it is not.

The global flag, when used, indicates that a search should find all occurrences of the pattern within the searched string, not just the first one. This is also known as global matching.

Expand image Example

The following example illustrates the use of the global property. If you pass "g" in to the function shown below, all instances of the word "the" are replaced with the word "a". Note that "The" at the beginning of the string is not replaced. This is because the initial letter is uppercase and, therefore, does not match the lowercase "t" in "the".

This function returns a string with a table that shows the condition of the properties associated with the allowable regular expression flags, g, i, and m. The function also returns the string with all replacements made.

CopyCode image Copy Code
function RegExpPropDemo(flag){
   if (flag.match(/[^gim]/))        //Check flag for validity.
     return("Flag specified is not valid");
   var r, re, s                    //Declare variables.
   var ss = "The man hit the ball with the bat.\n";
   ss += "while the fielder caught the ball with the glove.";
   re = new RegExp("the",flag);    //Specify the pattern to search for.
   r = ss.replace(re, "a");        //Replace "the" with "a".
   s = "Regular Expression property values:\n\n"
   s += "global  ignoreCase  multiline\n"
   if (re.global)                  //Test for global flag.
     s += " True     ";
   else
     s += "False     ";
   if (re.ignoreCase)              //Test ignoreCase flag.
     s += " True  ";
   else
     s += "False  ";
   if (re.multiline)               //Test multiline flag.
     s += "     True     ";
   else
     s += "     False   ";
   s += "\n\nThe resulting string is:\n\n" + r;
   return(s);                      //Returns replacement string
}

Expand image Requirements

Version 5.5

Applies To: Regular Expression Object (JScript 5.6)

Expand image See Also

Reference

ignoreCase Property (JScript 5.6)
multiline Property (JScript 5.6)
Regular Expression Syntax (Scripting)


ignoreCase Property (JScript 5.6)

JScript
ignoreCase Property (JScript 5.6)
See Also Example
CollapseAll image DropDown image

Returns a Boolean value indicating the state of the ignoreCase flag (i) used with a regular expression. Default is false. Read-only.

rgExp.ignoreCase

Expand image Remarks

The required rgExp reference is an instance of the RegExp object.

The ignoreCase property returns true if the ignoreCase flag is set for a regular expression, and returns false if it is not.

The ignoreCase flag, when used, indicates that a search should ignore case sensitivity when matching the pattern within the searched string.

Expand image Example

The following example illustrates the use of the ignoreCase property. If you pass "i" in to the function shown below, all instances of the word "the" are replaced with the word "a", including the initial "The". This is because with the ignoreCase flag set, the search ignores any case sensitivity. So "T" is the same as "t" for the purposes of matching.

This function returns a string with a table that shows the condition of the properties associated with the allowable regular expression flags, g, i, and m. The function also returns the string with all replacements made.
CopyCode image Copy Code
function RegExpPropDemo(flag){
   if (flag.match(/[^gim]/))        //Check flag for validity.
     return("Flag specified is not valid");
   var r, re, s                    //Declare variables.
   var ss = "The man hit the ball with the bat.\n";
   ss += "while the fielder caught the ball with the glove.";
   re = new RegExp("the",flag);    //Specify the pattern to search for.
   r = ss.replace(re, "a");        //Replace "the" with "a".
   s = "Regular Expression property values:\n\n"
   s += "global  ignoreCase  multiline\n"
   if (re.global)                  //Test for global flag.
     s += " True     ";
   else
     s += "False     ";
   if (re.ignoreCase)              //Test ignoreCase flag.
     s += " True  ";
   else
     s += "False  ";
   if (re.multiline)               //Test multiline flag.
     s += "     True     ";
   else
     s += "     False   ";
   s += "\n\nThe resulting string is:\n\n" + r;
   return(s);                      //Returns replacement string
}

Expand image Requirements

Version 5.5

Applies To: Regular Expression Object (JScript 5.6)

Expand image See Also

Reference

global Property (JScript 5.6)
multiline Property (JScript 5.6)
Regular Expression Syntax (Scripting)


index Property (JScript 5.6)

JScript
index Property (JScript 5.6)
See Also Example
CollapseAll image DropDown image

Returns the character position where the first successful match begins in a searched string. Read-only.

RegExp.index

Expand image Remarks

The object associated with this property is always the global RegExp object.

The index property is zero-based. The initial value of the index property is –1. Its value changes whenever a successful match is made.

Expand image Example

The following example illustrates the use of the index property. This function iterates a search string and prints out the index and lastIndex values for each word in the string.
CopyCode image Copy Code
function RegExpTest(){
  var ver = Number(ScriptEngineMajorVersion() + "." + ScriptEngineMinorVersion())
  if (ver >= 5.5){
    var src = "The rain in Spain falls mainly in the plain.";
    var re = /\w+/g;
    var arr;
    while ((arr = re.exec(src)) != null)
       print(arr.index + "-" + arr.lastIndex + "\t" + arr);
  }
  else{
    alert("You need a newer version of JScript for this to work");
  }
}

Expand image Requirements

Version 3

Applies To: RegExp Object (JScript 5.6)

Expand image See Also

Reference

Regular Expression Syntax (Scripting)


Infinity Property (JScript 5.6)

JScript
Infinity Property (JScript 5.6)
See Also
CollapseAll image DropDown image

Returns an initial value of Number.POSITIVE_INFINITY.

Infinity

Expand image Remarks

The Infinity property is a member of the Global object, and is made available when the scripting engine is initialized.

Expand image Requirements

Version 3

Applies To: Global Object (JScript 5.6)

Expand image See Also

Reference

POSITIVE_INFINITY Property (JScript 5.6)
NEGATIVE_INFINITY Property (JScript 5.6)


input Property ($_) (JScript 5.6)

JScript
input Property ($_) (JScript 5.6)
See Also
CollapseAll image DropDown image

Returns the string against which a regular expression search was performed. Read-only.

RegExp.input

Expand image Remarks

The object associated with this property is always the global RegExp object.

The value of input property is modified any time the searched string is changed.

The following example illustrates the use of the input property:

CopyCode image Copy Code
function inputDemo(){
   var s;
   var re = new RegExp("d(b+)(d)","ig");
   var str = "cdbBdbsbdbdz";
   var arr = re.exec(str);
   s = "The string used for the match was " + RegExp.input;
   return(s);
}

Expand image Requirements

Version 3

Applies To: RegExp Object (JScript 5.6)

Expand image See Also

Reference

Regular Expression Syntax (Scripting)


lastIndex Property (JScript 5.6)

JScript
lastIndex Property (JScript 5.6)
See Also Example
CollapseAll image DropDown image

Returns the character position where the next match begins in a searched string.

RegExp.lastIndex

Expand image Remarks

The object associated with this property is always the global RegExp object.

The lastIndex property is zero-based, that is, the index of the first character is zero. Its initial value is –1. Its value is modified whenever a successful match is made.

The lastIndex property is modified by the exec and test methods of the RegExp object, and the match, replace, and split methods of the String object.

The following rules apply to values of lastIndex:

  • If there is no match, lastIndex is set to -1.

  • If lastIndex is greater than the length of the string, test and exec fail and lastIndex is set to -1.

  • If lastIndex is equal to the length of the string, the regular expression matches if the pattern matches the empty string. Otherwise, the match fails and lastIndex is reset to -1.

  • Otherwise, lastIndex is set to the next position following the most recent match.

Expand image Example

The following example illustrates the use of the lastIndex property. This function iterates a search string and prints out the index and lastIndex values for each word in the string.
CopyCode image Copy Code
function RegExpTest(){
  var ver = Number(ScriptEngineMajorVersion() + "." + ScriptEngineMinorVersion())
  if (ver >= 5.5){
    var src = "The rain in Spain falls mainly in the plain.";
    var re = /\w+/g;
    var arr;
    while ((arr = re.exec(src)) != null)
       print(arr.index + "-" + arr.lastIndex + "\t" + arr);
  }
  else{
    alert("You need a newer version of JScript for this to work");
  }
}

Expand image Requirements

Version 3

Applies To: RegExp Object (JScript 5.6)

Expand image See Also

Reference

Regular Expression Syntax (Scripting)


lastMatch Property ($&) (JScript 5.6)

JScript
lastMatch Property ($&) (JScript 5.6)
See Also Example
CollapseAll image DropDown image

Returns the last matched characters from any regular expression search. Read-only.

RegExp.lastMatch

Expand image Remarks

The object associated with this property is always the global RegExp object.

The initial value of the lastMatch property is an empty string. The value of the lastMatch property changes whenever a successful match is made.

Expand image Example

The following example illustrates the use of the lastMatch property:
CopyCode image Copy Code
function matchDemo(){
   var s;                                //Declare variable.
   var re = new RegExp("d(b+)(d)","ig"); //Regular expression pattern.
   var str = "cdbBdbsbdbdz";             //String to be searched.
   var arr = re.exec(str);               //Perform the search.
   s = "$1 returns: " + RegExp.$1 + "\n";
   s += "$2 returns: " + RegExp.$2 + "\n";
   s += "$3 returns: " + RegExp.$3 + "\n";
   s += "input returns : " + RegExp.input + "\n";
   s += "lastMatch returns: " + RegExp.lastMatch + "\n";
   s += "leftContext returns: " + RegExp.leftContext + "\n";
   s += "rightContext returns: " + RegExp.rightContext + "\n";
   s += "lastParen returns: " + RegExp.lastParen + "\n";
   return(s);                            //Return results.
}
document.write(matchDemo());

Expand image Requirements

Version 5.5

Applies To: RegExp Object (JScript 5.6)

Expand image See Also

Reference

$1...$9 Properties (JScript 5.6)
index Property (JScript 5.6)
input Property ($_) (JScript 5.6)
lastIndex Property (JScript 5.6)
lastParen Property ($+) (JScript 5.6)
leftContext Property ($`) (JScript 5.6)
rightContext Property ($') (JScript 5.6)


lastParen Property ($+) (JScript 5.6)

JScript
lastParen Property ($+) (JScript 5.6)
See Also Example
CollapseAll image DropDown image

Returns the last parenthesized submatch from any regular expression search, if any. Read-only.

RegExp.lastParen

Expand image Remarks

The object associated with this property is always the global RegExp object.

The initial value of the lastParen property is an empty string. The value of the lastParen property changes whenever a successful match is made.

Expand image Example

The following example illustrates the use of the lastParen property:
CopyCode image Copy Code
function matchDemo(){
   var s;                                //Declare variable.
   var re = new RegExp("d(b+)(d)","ig"); //Regular expression pattern.
   var str = "cdbBdbsbdbdz";             //String to be searched.
   var arr = re.exec(str);               //Perform the search.
   s = "$1 returns: " + RegExp.$1 + "\n";
   s += "$2 returns: " + RegExp.$2 + "\n";
   s += "$3 returns: " + RegExp.$3 + "\n";
   s += "input returns : " + RegExp.input + "\n";
   s += "lastMatch returns: " + RegExp.lastMatch + "\n";
   s += "leftContext returns: " + RegExp.leftContext + "\n";
   s += "rightContext returns: " + RegExp.rightContext + "\n";
   s += "lastParen returns: " + RegExp.lastParen + "\n";
   return(s);                            //Return results.
}
document.write(matchDemo());

Expand image Requirements

Version 5.5

Applies To: RegExp Object (JScript 5.6)

Expand image See Also

Reference

$1...$9 Properties (JScript 5.6)
index Property (JScript 5.6)
input Property ($_) (JScript 5.6)
lastIndex Property (JScript 5.6)
lastMatch Property ($&) (JScript 5.6)
leftContext Property ($`) (JScript 5.6)
rightContext Property ($') (JScript 5.6)


leftContext Property ($`) (JScript 5.6)

JScript
leftContext Property ($`) (JScript 5.6)
See Also Example
CollapseAll image DropDown image

Returns the characters from the beginning of a searched string up to the position before the beginning of the last match. Read-only.

RegExp.leftContext

Expand image Remarks

The object associated with this property is always the global RegExp object.

The initial value of the leftContext property is an empty string. The value of the leftContext property changes whenever a successful match is made.

Expand image Example

The following example illustrates the use of the leftContext property:
CopyCode image Copy Code
function matchDemo(){
   var s;                                //Declare variable.
   var re = new RegExp("d(b+)(d)","ig"); //Regular expression pattern.
   var str = "cdbBdbsbdbdz";             //String to be searched.
   var arr = re.exec(str);               //Perform the search.
   s = "$1 returns: " + RegExp.$1 + "\n";
   s += "$2 returns: " + RegExp.$2 + "\n";
   s += "$3 returns: " + RegExp.$3 + "\n";
   s += "input returns : " + RegExp.input + "\n";
   s += "lastMatch returns: " + RegExp.lastMatch + "\n";
   s += "leftContext returns: " + RegExp.leftContext + "\n";
   s += "rightContext returns: " + RegExp.rightContext + "\n";
   s += "lastParen returns: " + RegExp.lastParen + "\n";
   return(s);                            //Return results.
}
document.write(matchDemo());

Expand image Requirements

Version 5.5

Applies To: RegExp Object (JScript 5.6)

Expand image See Also

Reference

$1...$9 Properties (JScript 5.6)
index Property (JScript 5.6)
input Property ($_) (JScript 5.6)
lastIndex Property (JScript 5.6)
lastMatch Property ($&) (JScript 5.6)
lastParen Property ($+) (JScript 5.6)
rightContext Property ($') (JScript 5.6)


length Property (arguments) (JScript 5.6)

JScript
length Property (arguments) (JScript 5.6)
See Also Example
CollapseAll image DropDown image

Returns the actual number of arguments passed to a function by the caller.

[function.]arguments.length

Expand image Remarks

The optional function argument is the name of the currently executing Function object.

The length property of the arguments object is initialized by the scripting engine to the actual number of arguments passed to a Function object when execution begins in that function.

Expand image Example

The following example illustrates the use of the length property of the arguments object. To fully understand the example, pass more arguments to the function than the 2 arguments expected:
CopyCode image Copy Code
function ArgTest(a, b){
   var i, s = "The ArgTest function expected ";
   var numargs = arguments.length;
   var expargs = ArgTest.length;
   if (expargs < 2)
      s += expargs + " argument. ";
   else
      s += expargs + " arguments. ";
   if (numargs < 2)
      s += numargs + " was passed.";
   else
      s += numargs + " were passed.";
   return(s);
}

Expand image Requirements

Version 5.5

Applies To: arguments Object (JScript 5.6)| Function Object (JScript 5.6)

Expand image See Also

Reference

arguments Property (JScript 5.6)
length Property (Array) (JScript 5.6)
length Property (String) (JScript 5.6)


length Property (Array) (JScript 5.6)

JScript
length Property (Array) (JScript 5.6)
See Also
CollapseAll image DropDown image

Returns an integer value one higher than the highest element defined in an array.

numVar = arrayObj.length

Expand image Arguments

numVar

Required. Any numeric variable.

arrayObj

Required. Any Array object.

Expand image Remarks

As the elements in an array do not have to be contiguous, the length property is not necessarily the number of elements in the array. For example, in the following array definition, my_array.length contains 7, not 2:

CopyCode image Copy Code
var my_array = new Array( );
my_array[0] = "Test";
my_array[6] = "Another Test";

If a value smaller than its previous value is assigned to the length property, the array is truncated, and any elements with array indexes equal to or greater than the new value of the length property are lost.

If a value larger than its previous value is assigned to the length property, the array is expanded, and any new elements created have the value undefined.

The following example illustrates the use of the length property:

CopyCode image Copy Code
function LengthDemo(){
   var a;
   a = new Array(0,1,2,3,4);
   return(a.length);
}

Expand image Requirements

Version 2

Applies To: Array Object (JScript 5.6)

Expand image See Also

Reference

length Property (Function) (JScript 5.6)
length Property (String) (JScript 5.6)


length Property (Function) (JScript 5.6)

JScript
length Property (Function) (JScript 5.6)
See Also Example
CollapseAll image DropDown image

Returns the number of arguments defined for a function.

functionName.length

Expand image Remarks

The required functionName is the name of the function.

The length property of a function is initialized by the scripting engine to the number of arguments in the function's definition when an instance of the function is created.

What happens when a function is called with a number of arguments different from the value of its length property depends on the function.

Expand image Example

The following example illustrates the use of the length property:
CopyCode image Copy Code
function ArgTest(a, b){
   var i, s = "The ArgTest function expected ";
   var numargs = ArgTest.arguments.length;
   var expargs = ArgTest.length;
   if (expargs < 2)
      s += expargs + " argument. ";
   else
      s += expargs + " arguments. ";
   if (numargs < 2)
      s += numargs + " was passed.";
   else
      s += numargs + " were passed.";
   return(s);
}

Expand image Requirements

Version 2

Applies To: Function Object (JScript 5.6)

Expand image See Also

Reference

arguments Property (JScript 5.6)
length Property (Array) (JScript 5.6)
length Property (String) (JScript 5.6)


length Property (String) (JScript 5.6)

JScript
length Property (String) (JScript 5.6)
See Also
CollapseAll image DropDown image

Returns the length of a String object.

strVariable.length
"String Literal".length

Expand image Remarks

The length property contains an integer that indicates the number of characters in the String object. The last character in the String object has an index of length - 1.

Expand image Requirements

Version 1

Applies To: String Object (JScript 5.6)

Expand image See Also

Reference

length Property (Array) (JScript 5.6)
length Property (Function) (JScript 5.6)


LN2 Property (JScript 5.6)

JScript
LN2 Property (JScript 5.6)
See Also
CollapseAll image DropDown image

Returns the natural logarithm of 2.

numVar = Math.LN2

Expand image Remarks

The LN2 property is approximately equal to 0.693.

Expand image Requirements

Version 1

Applies To: Math Object (JScript 5.6)

Expand image See Also

Reference

LN10 Property (JScript 5.6)


LN10 Property (JScript 5.6)

JScript
LN10 Property (JScript 5.6)
See Also
CollapseAll image DropDown image

Returns the natural logarithm of 10.

numVar = Math.LN10

Expand image Remarks

The LN10 property is approximately equal to 2.302.

Expand image Requirements

Version 1

Applies To: Math Object (JScript 5.6)

Expand image See Also

Reference

LN2 Property (JScript 5.6)


LOG2E Property (JScript 5.6)

JScript
LOG2E Property (JScript 5.6)
See Also
CollapseAll image DropDown image

Returns the base-2 logarithm of e, Euler's constant.

varName = Math.LOG2E

Expand image Remarks

The LOG2E property, a constant, is approximately equal to 1.442.

Expand image Requirements

Version 1

Applies To: Math Object (JScript 5.6)

Expand image See Also

Reference

LN2 Property (JScript 5.6)


LOG10E Property (JScript 5.6)

JScript
LOG10E Property (JScript 5.6)
See Also
CollapseAll image DropDown image

Returns the base-10 logarithm of e, Euler's constant.

varName = Math.LOG10E

Expand image Remarks

The LOG10E property, a constant, is approximately equal to 0.434.

Expand image Requirements

Version 1

Applies To: Math Object (JScript 5.6)

Expand image See Also

Reference

LOG2E Property (JScript 5.6)


MAX_VALUE Property (JScript 5.6)

JScript
MAX_VALUE Property (JScript 5.6)
See Also
CollapseAll image DropDown image

Returns the largest number representable in JScript. Equal to approximately 1.79E+308.

Number.MAX_VALUE

Expand image Remarks

The number argument is the Number object.

The Number object does not have to be created before the MAX_VALUE property can be accessed.

Expand image Requirements

Version 2

Applies To: Number Object (JScript 5.6)

Expand image See Also

Reference

MIN_VALUE Property (JScript 5.6)
NaN Property (JScript 5.6)
NEGATIVE_INFINITY Property (JScript 5.6)
POSITIVE_INFINITY Property (JScript 5.6)
toString Method (JScript 5.6)


message Property (JScript 5.6)

JScript
message Property (JScript 5.6)
See Also Example
CollapseAll image DropDown image

Returns an error message string.

errorObj.message

Expand image Arguments

errorObj

Required. Instance of Error object.

Expand image Remarks

The message property is a string containing an error message displayed to users. It contains the same information as the description property.

Expand image Example

The following example causes a TypeError exception to be thrown, and displays the name of the error and its message.
CopyCode image Copy Code
try {
  // 'null' is not a valid object
  null.doSomething();
}
catch(e){
  print(e.name + ": " + e.message);
  print(e.number + ": " + e.description);
}

Expand image Requirements

Version 5

Applies To: Error Object (JScript 5.6)

Expand image See Also

Reference

description Property (JScript 5.6)
name Property (JScript 5.6)


MIN_VALUE Property (JScript 5.6)

JScript
MIN_VALUE Property (JScript 5.6)
See Also
CollapseAll image DropDown image

Returns the number closest to zero representable in JScript. Equal to approximately 5.00E-324.

Number.MIN_VALUE

Expand image Remarks

The number argument is the Number object.

The Number object does not have to be created before the MIN_VALUE property can be accessed.

Expand image Requirements

Version 2

Applies To: Number Object (JScript 5.6)

Expand image See Also

Reference

MAX_VALUE Property (JScript 5.6)
NaN Property (JScript 5.6)
NEGATIVE_INFINITY Property (JScript 5.6)
POSITIVE_INFINITY Property (JScript 5.6)
toString Method (JScript 5.6)


multiline Property (JScript 5.6)

JScript
multiline Property (JScript 5.6)
See Also Example
CollapseAll image DropDown image

Returns a Boolean value indicating the state of the multiline flag (m) used with a regular expression. Default is false. Read-only.

rgExp.multiline

Expand image Remarks

The required rgExp argument is an instance of the RegExp object

The multiline property returns true if the multiline flag is set for a regular expression, and returns false if it is not. The multiline property is true if the regular expression object was created with the m flag.

If multiline is false, "^" matches the position at the beginning of a string, and "$" matches the position at the end of a string. If multiline is true, "^" matches the position at the beginning of a string as well as the position following a "\n" or "\r", and "$" matches the position at the end of a string and the position preceding "\n" or "\r".

Expand image Example

The following example illustrates the behavior of the multiline property. If you pass "m" in to the function shown below, the word "while" is replaced with the word "and". This is because with the multiline flag is set and the word "while" occurs at the beginning of the line after a newline character. The multiline flag allows the search to be performed on multiline strings.

This function returns a string with a table that shows the condition of the allowable regular expression flags, g, i, and m. The function also returns the string with all replacements made.
CopyCode image Copy Code
function RegExpPropDemo(flag){
   if (flag.match(/[^gim]/))          //Check flag for validity.
     return("Flag specified is not valid");
   var r, re, s                       //Declare variables.
   var ss = "The man hit the ball with the bat.";
   ss += "\nwhile the fielder caught the ball with the glove.";
   re = new RegExp("^while",flag);    //Specify the pattern to search for.
   r = ss.replace(re, "and");         //Replace "the" with "a".
   s = "Regular Expression property values:\n\n"
   s += "global  ignoreCase  multiline\n"
   if (re.global)                     //Test for global flag.
     s += " True     ";
   else
     s += "False     ";
   if (re.ignoreCase)                 //Test ignoreCase flag.
     s += " True  ";
   else
     s += "False  ";
   if (re.multiline)                  //Test multiline flag.
     s += "     True     ";
   else
     s += "     False   ";
   s += "\n\nThe resulting string is:\n\n" + r;
   return(s);                         //Returns replacement string
}

Expand image Requirements

Version 5.5

Applies To: Regular Expression Object (JScript 5.6)

Expand image See Also

Reference

global Property (JScript 5.6)
ignoreCase Property (JScript 5.6)
Regular Expression Syntax (Scripting)


name Property (JScript 5.6)

JScript
name Property (JScript 5.6)
See Also Example
CollapseAll image DropDown image

Returns the name of an error.

errorObj.name

Expand image Arguments

errorObj

Required. Instance of Error object.

Expand image Remarks

The name property returns the name or exception type of an error. When a runtime error occurs, the name property is set to one of the following native exception types:

Exception Type | Meaning
ConversionError | This error occurs whenever there is an attempt to convert an object into something to which it cannot be converted.
RangeError | This error occurs when a function is supplied with an argument that has exceeded its allowable range. For example, this error occurs if you attempt to construct an Array object with a length that is not a valid positive integer.
ReferenceError | This error occurs when an invalid reference has been detected. This error will occur, for example, if an expected reference is null.
RegExpError | This error occurs when a compilation error occurs with a regular expression. Once the regular expression is compiled, however, this error cannot occur. This example will occur, for example, when a regular expression is declared with a pattern that has an invalid syntax, or flags other than i, g, or m, or if it contains the same flag more than once.
SyntaxError | This error occurs when source text is parsed and that source text does not follow correct syntax. This error will occur, for example, if the eval function is called with an argument that is not valid program text.
TypeError | This error occurs whenever the actual type of an operand does not match the expected type. An example of when this error occurs is a function call made on something that is not an object or does not support the call.
URIError | This error occurs when an illegal Uniform Resource Indicator (URI) is detected. For example, this is error occurs when an illegal character is found in a string being encoded or decoded.

Expand image Example

The following example causes a TypeError exception to be thrown, and displays the name of the error and its message.
CopyCode image Copy Code
try {
  // 'null' is not a valid object
  null.doSomething();
}
catch(e){
  print(e.name + ": " + e.message);
  print(e.number + ": " + e.description);
}

Expand image Requirements

Version 5.5

Applies To: Error Object (JScript 5.6)

Expand image See Also

Reference

description Property (JScript 5.6)
message Property (JScript 5.6)
number Property (JScript 5.6)


NaN Property (Global) (JScript 5.6)

JScript
NaN Property (Global) (JScript 5.6)
See Also
CollapseAll image DropDown image

Returns the special value NaN indicating that an expression is not a number.

NaN

Expand image Remarks

The NaN property (not a number) is a member of the Global object, and is made available when the scripting engine is initialized.

Expand image Requirements

Version 3

Applies To: Global Object (JScript 5.6)

Expand image See Also

Reference

isNaN Method (JScript 5.6)


NaN Property (JScript 5.6)

JScript
NaN Property (JScript 5.6)
See Also
CollapseAll image DropDown image

A special value that indicates an arithmetic expression returned a value that was not a number.

Number.NaN

Expand image Remarks

The number argument is the Number object.

The Number object does not have to be created before the NaN property can be accessed.

NaN does not compare equal to any value, including itself. To test if a value is equivalent to NaN, use the isNaN function.

Expand image Requirements

Version 2

Applies To: Number Object (JScript 5.6)

Expand image See Also

Reference

isNaN Method (JScript 5.6)
MAX_VALUE Property (JScript 5.6)
MIN_VALUE Property (JScript 5.6)
NEGATIVE_INFINITY Property (JScript 5.6)
POSITIVE_INFINITY Property (JScript 5.6)
toString Method (JScript 5.6)


NEGATIVE_INFINITY Property (JScript 5.6)

JScript
NEGATIVE_INFINITY Property (JScript 5.6)
See Also
CollapseAll image DropDown image

Returns a value more negative than the largest negative number (-Number.MAX_VALUE) representable in JScript.

Number.NEGATIVE_INFINITY

Expand image Remarks

The number argument is the Number object.

The Number object does not have to be created before the NEGATIVE_INFINITY property can be accessed.

JScript displays NEGATIVE_INFINITY values as -infinity. This value behaves mathematically as infinity.

Expand image Requirements

Version 2

Applies To: Number Object (JScript 5.6)

Expand image See Also

Reference

MAX_VALUE Property (JScript 5.6)
MIN_VALUE Property (JScript 5.6)
NaN Property (JScript 5.6)
POSITIVE_INFINITY Property (JScript 5.6)
toString Method (JScript 5.6)


number Property (JScript 5.6)

JScript
number Property (JScript 5.6)
See Also
CollapseAll image DropDown image

Returns or sets the numeric value associated with a specific error. The Error object's default property is number.

object.number [= errorNumber]

Expand image Arguments

object

Any instance of the Error object.

errorNumber

An integer representing an error.

Expand image Remarks

An error number is a 32-bit value. The upper 16-bit word is the facility code, while the lower word is the actual error code.

The following example illustrates the use of the number property:

CopyCode image Copy Code
try
   x = y   // Cause an error.
catch(var e){   // Create local variable e.
   document.write(e)   // Prints "[object Error]".
   document.write(e.number>>16 & 0x1FFF)   // Prints 10, the facility code.
   document.write(e.number & 0xFFFF)   // Prints 5009, the error code.
   document.write(e.description)   // Prints "'y' is undefined".
}

Expand image Requirements

Version 5

Applies To: Error Object (JScript 5.6)

Expand image See Also

Reference

description Property (JScript 5.6)
message Property (JScript 5.6)
name Property (JScript 5.6)


PI Property (JScript 5.6)

JScript
PI Property (JScript 5.6)
See Also
CollapseAll image DropDown image

Returns the ratio of the circumference of a circle to its diameter, approximately 3.141592653589793.

numVar = Math.PI

Expand image Remarks

The PI property, a constant, is approximately equal to 3.14159.

Expand image Requirements

Version 1

Applies To: Math Object (JScript 5.6)

Expand image See Also

Reference

LN2 Property (JScript 5.6)


POSITIVE_INFINITY Property (JScript 5.6)

JScript
POSITIVE_INFINITY Property (JScript 5.6)
See Also
CollapseAll image DropDown image

Returns a value larger than the largest number (Number.MAX_VALUE) that can be represented in JScript.

Number.POSITIVE_INFINITY

Expand image Remarks

The number argument is the Number object.

The Number object does not have to be created before the POSITIVE_INFINITY property can be accessed.

JScript displays POSITIVE_INFINITY values as infinity. This value behaves mathematically as infinity.

Expand image Requirements

Version 2

Applies To: Number Object (JScript 5.6)

Expand image See Also

Reference

MAX_VALUE Property (JScript 5.6)
MIN_VALUE Property (JScript 5.6)
NaN Property (JScript 5.6)
NEGATIVE_INFINITY Property (JScript 5.6)
toString Method (JScript 5.6)


propertyIsEnumerable Property (JScript 5.6)

JScript
propertyIsEnumerable Property (JScript 5.6)
See Also Example
CollapseAll image DropDown image

Returns a Boolean value indicating whether a specified property is part of an object and if it is enumerable.

object.propertyIsEnumerable(proName)

Expand image Arguments

object

Required. Instance of an object.

proName

Required. String value of a property name.

Expand image Remarks

The propertyIsEnumerable property returns true if proName exists in object and can be enumerated using a ForIn loop. The propertyIsEnumerable property returns false if object does not have a property of the specified name or if the specified property is not enumerable. Typically, predefined properties are not enumerable while user-defined properties are always enumerable.

The propertyIsEnumerable property does not consider objects in the prototype chain.

Expand image Example

CopyCode image Copy Code
function testIsEnumerable(){
  var a = new Array("apple", "banana", "cactus");
  return(a.propertyIsEnumerable(1));
}

Expand image Requirements

Version 5.5

Applies To: Object Object (JScript 5.6)

Expand image See Also

Reference

prototype Property (JScript 5.6)


prototype Property (JScript 5.6)

JScript
prototype Property (JScript 5.6)
See Also
CollapseAll image DropDown image

Returns a reference to the prototype for a class of objects.

objectName.prototype

Expand image Remarks

The objectName argument is the name of an object.

Use the prototype property to provide a base set of functionality to a class of objects. New instances of an object "inherit" the behavior of the prototype assigned to that object.

For example, say you want to add a method to the Array object that returns the value of the largest element of the array. To do this, declare the function, add it to Array.prototype, and then use it.

CopyCode image Copy Code
function array_max( ){
   var i, max = this[0];
   for (i = 1; i < this.length; i++)
   {
   if (max < this[i])
   max = this[i];
   }
   return max;
}
Array.prototype.max = array_max;
var x = new Array(1, 2, 3, 4, 5, 6);
var y = x.max( );

After this code is executed, y contains the largest value in the array x, or 6.

All intrinsic JScript objects have a prototype property that is read-only. Functionality may be added to the prototype, as in the example, but the object may not be assigned a different prototype. However, user-defined objects may be assigned a new prototype.

The method and property lists for each intrinsic object in this language reference indicate which ones are part of the object's prototype, and which are not.

Expand image Requirements

Version 2

Applies To: Array Object (JScript 5.6)| Boolean Object (JScript 5.6)| Date Object (JScript 5.6)| Function Object (JScript 5.6)| Number Object (JScript 5.6)| Object Object (JScript 5.6)| String Object (JScript 5.6)

Expand image See Also

Reference

constructor Property (JScript 5.6)


rightContext Property ($') (JScript 5.6)

JScript
rightContext Property ($') (JScript 5.6)
See Also Example
CollapseAll image DropDown image

Returns the characters from the position following the last match to the end of the searched string. Read-only.

RegExp.rightContext

Expand image Remarks

The object associated with this property is always the global RegExp object.

The initial value of the rightContext property is an empty string. The value of the rightContext property changes whenever a successful match is made.

Expand image Example

The following example illustrates the use of the rightContext property:
CopyCode image Copy Code
function matchDemo(){
   var s;                                //Declare variable.
   var re = new RegExp("d(b+)(d)","ig"); //Regular expression pattern.
   var str = "cdbBdbsbdbdz";             //String to be searched.
   var arr = re.exec(str);               //Perform the search.
   s = "$1 returns: " + RegExp.$1 + "\n";
   s += "$2 returns: " + RegExp.$2 + "\n";
   s += "$3 returns: " + RegExp.$3 + "\n";
   s += "input returns : " + RegExp.input + "\n";
   s += "lastMatch returns: " + RegExp.lastMatch + "\n";
   s += "leftContext returns: " + RegExp.leftContext + "\n";
   s += "rightContext returns: " + RegExp.rightContext + "\n";
   s += "lastParen returns: " + RegExp.lastParen + "\n";
   return(s);                            //Return results.
}
document.write(matchDemo());

Expand image Requirements

Version 5.5

Applies To: RegExp Object (JScript 5.6)

Expand image See Also

Reference

$1...$9 Properties (JScript 5.6)
index Property (JScript 5.6)
input Property ($_) (JScript 5.6)
lastIndex Property (JScript 5.6)
lastMatch Property ($&) (JScript 5.6)
lastParen Property ($+) (JScript 5.6)
leftContext Property ($`) (JScript 5.6)


source Property (JScript 5.6)

JScript
source Property (JScript 5.6)
See Also Example
CollapseAll image DropDown image

Returns a copy of the text of the regular expression pattern. Read-only. The rgExp argument is a Regular expression object. It can be a variable name or a literal.

rgExp.source

Expand image Example

The following example illustrates the use of the source property:
CopyCode image Copy Code
function SourceDemo(re, s){
   var s1;
   // Test string for existence of regular expression.
   if (re.test(s))
      s1 = " contains ";
   else
      s1 = " does not contain ";
   // Get the text of the regular expression itself.
   return(s + s1 + re.source);
}

Expand image Requirements

Version 3

Applies To: Regular Expression Object (JScript 5.6)

Expand image See Also

Reference

Regular Expression Object (JScript 5.6)
Regular Expression Object (JScript 5.6)
Regular Expression Syntax (Scripting)


SQRT1_2 Property (JScript 5.6)

JScript
SQRT1_2 Property (JScript 5.6)
See Also
CollapseAll image DropDown image

Returns the square root of 0.5, or one divided by the square root of 2.

numVar = Math.SQRT1_2

Expand image Remarks

The SQRT1_2 property, a constant, is approximately equal to 0.707.

Expand image Requirements

Version 1

Applies To: Math Object (JScript 5.6)

Expand image See Also

Reference

sqrt Method (JScript 5.6)
SQRT2 Property (JScript 5.6)


SQRT2 Property (JScript 5.6)

JScript
SQRT2 Property (JScript 5.6)
See Also
CollapseAll image DropDown image

Returns the square root of 2.

numVar = Math.SQRT2

Expand image Remarks

The SQRT2 property, a constant, is approximately equal to 1.414.

Expand image Requirements

Version 1

Applies To: Math Object (JScript 5.6)

Expand image See Also

Reference

sqrt Method (JScript 5.6)
SQRT1_2 Property (JScript 5.6)


undefined Property (JScript 5.6)

JScript
undefined Property (JScript 5.6)
See Also Example
CollapseAll image DropDown image

Returns an initial value of undefined.

undefined

Expand image Remarks

The undefined property is a member of the Global object, and becomes available when the scripting engine is initialized. When a variable has been declared but not initialized, its value is undefined.

If a variable has not been declared, you cannot compare it to undefined, but you can compare the type of the variable to the string "undefined"

The undefined property is useful when explicitly testing or setting a variable to undefined.

Expand image Example

CopyCode image Copy Code
var declared;                         //Declare variable.
if (declared == undefined)            //Test variable.
  document.write("declared has not been given a value.");

if (typeof(notDeclared) == "undefined")
  document.write("notDeclared has not been defined.");

Expand image Requirements

Version 5.5

Applies To: Global Object (JScript 5.6)

Expand image See Also

Reference

typeof Operator (JScript 5.6)


JScript Statements (JScript 5.6)

JScript
JScript Statements (JScript 5.6)
CollapseAll image DropDown image

The following table lists JScript statements.

Expand image Statements

Description | Language Element
Terminates the current loop, or if in conjunction with a label, terminates the associated statement. | break Statement
Contains statements to execute when an error occurs in code within the try block. | catch Statement
Activates conditional compilation support. | @cc_on Statement
Causes single-line comments to be ignored by the JScript parser. | // (Single-line Comment Statement)
Causes multiline comments to be ignored by the JScript parser. | /*..*/ (Multiline Comment Statement)
Stops the current iteration of a loop, and starts a new iteration. | continue Statement
Starts the debugger. | debugger Statement
Executes a statement block once, and then repeats execution of the loop until a condition expression evaluates to false. | do...while Statement
Executes a block of statements for as long as a specified condition is true. | for Statement
Executes one or more statements for each element of an object or array. | for...in Statement
Declares a new function. | function Statement
Conditionally executes a group of statements, depending on the value of an expression. | @if Statement
Conditionally executes a group of statements, depending on the value of an expression. | if...else Statement
Provides an identifier for a statement. | Labeled Statement
Exits from the current function and returns a value from that function. | return Statement
Creates variables used with conditional compilation statements. | @set Statement
Enables the execution of one or more statements when a specified expression's value matches a label. | switch Statement
Refers to the current object. | this Statement
Generates an error condition that can be handled by a try...catch statement. | throw Statement
Implements error handling for JScript. | try Statement
Declares a variable. | var Statement
Executes a statement until a specified condition is false. | while Statement
Establishes the default object for a statement. | with Statement


break Statement (JScript 5.6)

JScript
break Statement (JScript 5.6)
See Also Example
CollapseAll image DropDown image

Terminates the current loop, or if in conjunction with a label, terminates the associated statement.

break [label];

Expand image Remarks

The optional label argument specifies the label of the statement you are breaking from.

You typically use the break statement in switch statements and while, for, for...in, or do...while loops. You most commonly use the label argument in switch statements, but it can be used in any statement, whether simple or compound.

Executing the break statement exits from the current loop or statement, and begins script execution with the statement immediately following.

Expand image Example

The following example illustrates the use of the break statement.
CopyCode image Copy Code
function BreakTest(breakpoint){
   var i = 0;
   while (i < 100)
   {
   if (i == breakpoint)
      break;
      i++;
   }
   return(i);
}

Expand image Requirements

Version 1

Expand image See Also

Reference

continue Statement (JScript 5.6)
do...while Statement (JScript 5.6)
for Statement (JScript 5.6)
for...in Statement (JScript 5.6)
Labeled Statement (JScript 5.6)
while Statement (JScript 5.6)


@cc_on Statement (JScript 5.6)

JScript
@cc_on Statement (JScript 5.6)
See Also
CollapseAll image DropDown image

Activates conditional compilation support.

@cc_on

Expand image Remarks

The @cc_on statement activates conditional compilation in the scripting engine.

It is strongly recommended that you use the @cc_on statement in a comment, so that browsers that do not support conditional compilation will accept your script as valid syntax:

CopyCode image Copy Code
/*@cc_on*/
...
(remainder of script)

Alternatively, an @if or @set statement outside of a comment also activates conditional compilation.

Expand image Requirements

Version 3

Expand image See Also

Reference

@if Statement
@set Statement (JScript 5.6)

Concepts

Conditional Compilation (JScript 5.6)
Conditional Compilation Variables (JScript 5.6)


Comment Statements (JScript 5.6)

JScript
Comment Statements (JScript 5.6)
Example
CollapseAll image DropDown image

Causes comments to be ignored by the JScript parser.

Single-line Comment:
// comment
Multiline Comment:
/*
comment
*/ The comment argument is the text of any comment you want to include in your script.

//@CondStatement
/*@
condStatement
@*/

Expand image Remarks

The condStatement argument is conditional compilation code to be used if conditional compilation is activated. If Syntax 3 is used, there can be no space between the "//" and "@" characters.

Use comments to keep parts of a script from being read by the JScript parser. You can use comments to include explanatory remarks in a program.

If Syntax 1 is used, the parser ignores any text between the comment marker and the end of the line. If Syntax 2 is used, it ignores any text between the beginning and end markers.

Syntaxes 3 and 4 are used to support conditional compilation while retaining compatibility with browsers that do not support that feature. These browsers treat those forms of comments as syntaxes 1 and 2 respectively.

Expand image Example

The following example illustrates the most common uses of the comment statement.

CopyCode image Copy Code
function myfunction(arg1, arg2){
   /* This is a multiline comment that
      can span as many lines as necessary. */
   var r;
   // This is a single line comment.
   r = arg1 + arg2; // Sum the two arguments.
   return(r);
}

Expand image Requirements

Version 1


continue Statement (JScript 5.6)

JScript
continue Statement (JScript 5.6)
See Also Example
CollapseAll image DropDown image

Stops the current iteration of a loop, and starts a new iteration.

continue [label];

Expand image Remarks

The optional label argument specifies the statement to which continue applies.

You can use the continue statement only inside a while, do...while, for, or for...in loop. Executing the continue statement stops the current iteration of the loop and continues program flow with the beginning of the loop. This has the following effects on the different types of loops:

  • while and do...while loops test their condition, and if true, execute the loop again.

  • for loops execute their increment expression, and if the test expression is true, execute the loop again.

  • for...in loops proceed to the next field of the specified variable and execute the loop again.

Expand image Example

The following example illustrates the use of the continue statement.

CopyCode image Copy Code
function skip5(){
   var s = "", i=0;
   while (i < 10)
   {
      i++;
      // Skip 5
      if (i==5)
      {
       continue;
      }
   s += i;
   }
   return(s);
}

Expand image Requirements

Version 1

Expand image See Also

Reference

break Statement (JScript 5.6)
do...while Statement (JScript 5.6)
for Statement (JScript 5.6)
for...in Statement (JScript 5.6)
Labeled Statement (JScript 5.6)
while Statement (JScript 5.6)


debugger Statement (JScript 5.6)

JScript
debugger Statement (JScript 5.6)
See Also Example
CollapseAll image DropDown image

Suspends execution.

debugger

Expand image Remarks

You can place debugger statements anywhere in procedures to suspend execution. Using the debugger statement is similar to setting a breakpoint in the code.

The debugger statement suspends execution, but it does not close any files or clear any variables.

Note Note

The debugger statement has no effect unless the script is being debugged.

Expand image Example

This example uses the debugger statement to suspend execution for each iteration through the for loop.

Note Note

To run this example, you must have a script debugger installed and the script must run in debug mode. For more information, search MSDN (http://msdn.microsoft.com) for the title "Introducing Microsoft Script Debugger".
CopyCode image Copy Code
for(i = 1; i<5; i++) {
   // Print i to the Output window.
   Debug.write("loop index is " + i);
   // Wait for user to resume.
   debugger
}

Expand image Requirements

Version 3

Expand image See Also

Reference

JScript Statements (JScript 5.6)

Concepts

Conditional Compilation (JScript 5.6)


do...while Statement (JScript 5.6)

JScript
do...while Statement (JScript 5.6)
See Also Example
CollapseAll image DropDown image

Executes a statement block once, and then repeats execution of the loop until a condition expression evaluates to false.

do
   statement
while (expression) ;

Expand image Arguments

statement

Optional. The statement to be executed if expression is true. Can be a compound statement.

expression

Optional. An expression that can be coerced to Boolean true or false. If expression is true, the loop is executed again. If expression is false, the loop is terminated.

Expand image Remarks

The value of expression is not checked until after the first iteration of the loop, guaranteeing that the loop is executed at least once. Thereafter, it is checked after each succeeding iteration of the loop.

Expand image Example

The following example illustrates the use of the do...while statement to iterate the Drives collection.
CopyCode image Copy Code
function GetDriveList(){
   var fso, s, n, e, x;
   fso = new ActiveXObject("Scripting.FileSystemObject");
   e = new Enumerator(fso.Drives);
   s = "";
   do
   {
      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>";
      e.moveNext();
   }
   while (!e.atEnd());
   return(s);
}

Expand image Requirements

Version 3

Expand image See Also

Reference

break Statement (JScript 5.6)
continue Statement (JScript 5.6)
for Statement (JScript 5.6)
for...in Statement (JScript 5.6)
while Statement (JScript 5.6)
Labeled Statement (JScript 5.6)


for Statement (JScript 5.6)

JScript
for Statement (JScript 5.6)
See Also Example
CollapseAll image DropDown image

Executes a block of statements for as long as a specified condition is true.

for (initialization; test; increment)
      statements

Expand image Arguments

initialization

Required. An expression. This expression is executed only once, before the loop is executed.

test

Required. A Boolean expression. If test is true, statement is executed. If test if false, the loop is terminated.

increment

Required. An expression. The increment expression is executed at the end of every pass through the loop.

statements

Optional. One or more statements to be executed if test is true. Can be a compound statement.

Expand image Remarks

You usually use a for loop when the loop is to be executed a specific number of times.

Expand image Example

The following example demonstrates a for loop.

CopyCode image Copy Code
/* i is set to 0 at start, and is incremented by 1 at the end
of each iteration. Loop terminates when i is not less
than 10 before a loop iteration. */
var myarray = new Array();
for (i = 0; i < 10; i++) {
   myarray[i] = i;
}

Expand image Requirements

Version 1

Expand image See Also

Reference

for...in Statement (JScript 5.6)
while Statement (JScript 5.6)


for...in Statement (JScript 5.6)

JScript
for...in Statement (JScript 5.6)
See Also Example
CollapseAll image DropDown image

Executes one or more statements for each property of an object, or each element of an array.

for (variable in [object | array])
      statements

Expand image Arguments

variable

Required. A variable that can be any property name of object or any element index of an array.

object, array

Optional. An object or array over which to iterate.

statements

Optional. One or more statements to be executed for each property of object or each element of array. Can be a compound statement.

Expand image Remarks

Before each iteration of a loop, variable is assigned the next property name of object or the next element index of array. You can then use it in any of the statements inside the loop to reference the property of object or the element of array.

When iterating over an object, there is no way to determine or control the order in which the members of the object are assigned to variable. Iterating through an array will be performed in element order, that is, 0, 1, 2, ...

Expand image Example

The following example illustrates the use of the for ... in statement with an object used as an associative array.

CopyCode image Copy Code
function ForInDemo(){
   // Create some variables.
   var a, key, s = "";
   // Initialize object.
   a = {"a" : "Athens" , "b" : "Belgrade", "c" : "Cairo"}
   // Iterate the properties.
   for (key in a)   {
      s += a[key] + "&ltBR>";
   }
   return(s);
}
Note Note

Use the Enumerator object to iterate members of a collection.

Expand image Requirements

Version 5

Expand image See Also

Reference

for Statement (JScript 5.6)
while Statement (JScript 5.6)


function Statement (JScript 5.6)

JScript
function Statement (JScript 5.6)
See Also Example
CollapseAll image DropDown image

Declares a new function.

function functionname([arg1 [, arg2 [,...[, argN]]]])
{
      statements
}

Expand image Arguments

functionname

Required. The name of the function.

arg1...argN

Optional. An optional, comma-separated list of arguments the function understands.

statements

Optional. One or more JScript statements.

Expand image Remarks

Use the function statement to declare a function for later use. The code contained in statements is not executed until the function is called from elsewhere in the script.

Expand image Example

The following example illustrates the use of the function statement.
CopyCode image Copy Code
      function myfunction(arg1, arg2){
   var r;
   r = arg1 * arg2;
   return(r);
}
Note Note

When calling a function, ensure that you always include the parentheses and any required arguments. Calling a function without parentheses causes the text of the function to be returned instead of the results of the function.

Expand image Requirements

Version 1

Expand image See Also

Reference

new Operator (JScript 5.6)


@if Statement

JScript
@if Statement
See Also
CollapseAll image DropDown image

Conditionally executes a group of statements, depending on the value of an expression.

@if (
      condition1
)
      text1
[@elif (
      condition2
)
      text2]
[@else
      text3]
@end

Expand image Arguments

condition1, condition2

Optional. An expression that can be coerced into a Boolean expression.

text1

Optional. Text to be parsed if condition1 is true.

text2

Optional. Text to be parsed if condition1 is false and condition2 is true.

text3

Optional. Text to be parsed if both condition1 and condition2 are false.

Expand image Remarks

When you write an @if statement, you do not have to place each clause on a separate line. You can use multiple @elif clauses. However, all @elif clauses must come before an @else clause.

You commonly use the @if statement to determine which text among several options should be used for text output. For example:

CopyCode image Copy Code
alert(@if (@_win32) "using Windows NT or Windows 95" @else "using Windows 3.1" @end)

Expand image Requirements

Version 3

Expand image See Also

Reference

@cc_on Statement (JScript 5.6)
@set Statement (JScript 5.6)

Concepts

Conditional Compilation (JScript 5.6)
Conditional Compilation Variables (JScript 5.6)


if...else Statement (JScript 5.6)

JScript
if...else Statement (JScript 5.6)
See Also Example
CollapseAll image DropDown image

Conditionally executes a group of statements, depending on the value of an expression.

if (condition)
      statement1
[else
      statement2]

Expand image Arguments

condition

Required. A Boolean expression. If condition is null or undefined, condition is treated as false.

statement1

Optional. The statement to be executed if condition is true. Can be a compound statement.

statement2

Optional. The statement to be executed if condition is false. Can be a compound statement.

Expand image Remarks

It is generally good practice to enclose statement1 and statement2 in braces ({}) for clarity and to avoid inadvertent errors.

Expand image Example

In the following example, you may intend that the else be used with the first if statement, but it is used with the second one.

CopyCode image Copy Code
          if (x == 5)
   if (y == 6)
      z = 17;
else
   z = 20;

Changing the code in the following manner eliminates any ambiguities:

CopyCode image Copy Code
          if (x == 5)
   {
   if (y == 6)
      z = 17;
   }
else
   z = 20;

Similarly, if you want to add a statement to statement1, and you don not use braces, you can accidentally create an error:

CopyCode image Copy Code
          if (x == 5)
   z = 7;
   q = 42;
else
   z = 19;

In this case, there is a syntax error, because there is more than one statement between the if and else statements. Braces are required around the statements between if and else.

Expand image Requirements

Version 1

Expand image See Also

Reference

Conditional (Ternary) Operator (?:) (JScript 5.6)


Labeled Statement (JScript 5.6)

JScript
Labeled Statement (JScript 5.6)
See Also Example
CollapseAll image DropDown image

Provides an identifier for a statement.

label :
      statements

Expand image Arguments

label

Required. A unique identifier used when referring to the labeled statement.

statements

Optional. One or more statements associated with label.

Expand image Remarks

Labels are used by the break and continue statements to specify the statement to which the break and continue apply.

Expand image Example

In the following statement the continue statement uses a labeled statement to create an array in which the third column of each row contains and undefined value:

CopyCode image Copy Code
function labelDemo(){
   var a = new Array();
   var i, j, s = "", s1 = "";
   Outer:
      for (i = 0; i < 5; i++)
      {
         Inner:
            for (j = 0; j < 5; j++)
            {
               if (j == 2)
                  continue Inner;
               else
                  a[i,j] = j + 1;
            }
      }
      for (i = 0;i < 5; i++)
      {
         s = ""
         for (j = 0; j < 5; j++)
         {
            s += a[i,j];
         }
         s1 += s + "\n";
      }
      return(s1)
}

Expand image Requirements

Version 3

Expand image See Also

Reference

break Statement (JScript 5.6)
continue Statement (JScript 5.6)


return Statement (JScript 5.6)

JScript
return Statement (JScript 5.6)
See Also Example
CollapseAll image DropDown image

Exits from the current function and returns a value from that function.

return[(][expression][)];

Expand image Remarks

The optional expression argument is the value to be returned from the function. If omitted, the function does not return a value.

You use the return statement to stop execution of a function and return the value of expression. If expression is omitted, or no return statement is executed from within the function, the expression that called the current function is assigned the value undefined.

Expand image Example

The following example illustrates the use of the return statement.

CopyCode image Copy Code
function myfunction(arg1, arg2){
   var r;
   r = arg1 * arg2;
   return(r);
}

Expand image Requirements

Version 1

Expand image See Also

Reference

function Statement (JScript 5.6)


@set Statement (JScript 5.6)

JScript
@set Statement (JScript 5.6)
See Also
CollapseAll image DropDown image

Creates variables used with conditional compilation statements.

@set @varname = term

Expand image Arguments

varname

Required. Valid JScript variable name. Must be preceded by an "@" character at all times.

term

Required. Zero or more unary operators followed by a constant, conditional compilation variable, or parenthesized expression.

Expand image Remarks

Numeric and Boolean variables are supported for conditional compilation. Strings are not. Variables created using @set are generally used in conditional compilation statements, but can be used anywhere in JScript code.

Examples of variable declarations look like this:

CopyCode image Copy Code
        @set @myvar1 = 12

@set @myvar2 = (@myvar1 * 20)

@set @myvar3 = @_jscript_version

The following operators are supported in parenthesized expressions:

  • ! ~

  • * / %

  • + -

  • << >> >>>

  • < <= > >=

  • == != === !==

  • & ^ |

  • && | |

If a variable is used before it has been defined, its value is NaN. NaN can be checked for using the @if statement:

CopyCode image Copy Code
@if (@newVar != @newVar)
   ...

This works because NaN is the only value not equal to itself.

Expand image Requirements

Version 3

Expand image See Also

Reference

@cc_on Statement (JScript 5.6)
@if Statement

Concepts

Conditional Compilation (JScript 5.6)
Conditional Compilation Variables (JScript 5.6)


switch Statement (JScript 5.6)

JScript
switch Statement (JScript 5.6)
See Also Example
CollapseAll image DropDown image

Enables the execution of one or more statements when a specified expression's value matches a label.

switch (expression) {
      case label :
              statementlist
      case label :
              statementlist
   ...
      default :
              statementlist
}

Expand image Arguments

expression

The expression to be evaluated.

label

An identifier to be matched against expression. If label === expression, execution starts with the statementlist immediately after the colon, and continues until it encounters either a break statement, which is optional, or the end of the switch statement.

statementlist

One or more statements to be executed.

Expand image Remarks

Use the default clause to provide a statement to be executed if none of the label values matches expression. It can appear anywhere within the switch code block.

Zero or more label blocks may be specified. If no label matches the value of expression, and a default case is not supplied, no statements are executed.

Execution flows through a switch statement as follows:

  • Evaluate expression and look at label in order until a match is found.

  • If a label value equals expression, execute its accompanying statementlist.

    Continue execution until a break statement is encountered, or the switch statement ends. This means that multiple label blocks are executed if a break statement is not used.

  • If no label equals expression, go to the default case. If there is no default case, go to last step.

  • Continue execution at the statement following the end of the switch code block.

Expand image Example

The following example tests an object for its type.

CopyCode image Copy Code
function MyObject() {
...}

switch (object.constructor){
   case Date:
   ...
   case Number:
   ...
   case String:
   ...
   case MyObject:
   ...
   default:
   ...
}

Expand image Requirements

Version 3

Expand image See Also

Reference

break Statement (JScript 5.6)
if...else Statement (JScript 5.6)


this Statement (JScript 5.6)

JScript
this Statement (JScript 5.6)
See Also Example
CollapseAll image DropDown image

Refers to the current object.

this.property

Expand image Remarks

The required property argument is one of the current object's properties

The this keyword is typically used in object constructors to refer to the current object.

Expand image Example

In the following example, this refers to the newly created Car object, and assigns values to three properties:

CopyCode image Copy Code
function Car(color, make, model){
   this.color = color;
   this.make = make;
   this.model = model;
}

For client versions of JScript, this refers to the window object if used outside of the context of any other object.

Expand image Requirements

Version 1

Expand image See Also

Reference

new Operator (JScript 5.6)


throw Statement (JScript 5.6)

JScript
throw Statement (JScript 5.6)
See Also
CollapseAll image DropDown image

Generates an error condition that can be handled by a try...catch...finally statement.

throw exception

Expand image Remarks

The required exception argument can be any expression.

The following example throws an error based on a passed-in value, then illustrates how that error is handled in a hierarchy of try...catch...finally statements:

CopyCode image Copy Code
function TryCatchDemo(x){
   try {
      try {
      if (x == 0)   // Evalute argument.
         throw "x equals zero";   // Throw an error.
      else
         throw "x does not equal zero";   // Throw a different error.
      }
      catch(e) {   // Handle "x = 0" errors here.
         if (e == "x equals zero")   // Check for an error handled here.
            return(e + " handled locally.");   // Return object error message.
         else   // Can't handle error here.
            throw e;   // Rethrow the error for next
      }   // error handler.
   }
   catch(e) {   // Handle other errors here.
      return(e + " handled higher up.");   // Return error message.
   }
}
document.write(TryCatchDemo(0));
document.write(TryCatchDemo(1));

Expand image Requirements

Version 5

Expand image See Also

Reference

try...catch...finally Statement (JScript 5.6)


try...catch...finally Statement (JScript 5.6)

JScript
try...catch...finally Statement (JScript 5.6)
See Also Example
CollapseAll image DropDown image

Implements error handling for JScript.

try {
      tryStatements}
catch(exception){
      catchStatements}
finally {
      finallyStatements}

Expand image Arguments

tryStatements

Required. Statements where an error can occur.

exception

Required. Any variable name. The initial value of exception is the value of the thrown error.

catchStatements

Optional. Statements to handle errors occurring in the associated tryStatements.

finallyStatements

Optional. Statements that are unconditionally executed after all other error processing has occurred.

Expand image Remarks

The try...catch...finally statement provides a way to handle some or all of the possible errors that may occur in a given block of code, while still running code. If errors occur that the programmer has not handled, JScript simply provides its normal error message to a user, as if there was no error handling.

The tryStatements contain code where an error can occur, while catchStatements contain the code to handle any error that does occur. If an error occurs in the tryStatements, program control is passed to catchStatements for processing. The initial value of exception is the value of the error that occurred in tryStatements. If no error occurs, catchStatements are never executed.

If the error cannot be handled in the catchStatements associated with the tryStatements where the error occurred, use the throw statement to propagate, or rethrow, the error to a higher-level error handler.

After all statements in tryStatements have been executed and any error handling has occurred in catchStatements, the statements in finallyStatements are unconditionally executed.

Notice that the code inside finallyStatements is executed even if a return statement occurs inside the try or catch blocks, or if the catch block re-throws the error. finallyStatments are guaranteed to always run, unless an unhandled error occurs (for example, causing a run-time error inside the catch block).

Expand image Example

The following example shows how JScript exception handling works.

CopyCode image Copy Code
try {
  print("Outer try running..");
  try {
    print("Nested try running...");
    throw "an error";
  }
  catch(e) {
    print("Nested catch caught " + e);
    throw e + " re-thrown";
  }
  finally {
    print("Nested finally is running...");
  }
}
catch(e) {
  print("Outer catch caught " + e);
}
finally {
  print("Outer finally running");
}
// Change this for Windows Script Host to say WScript.Echo(s)
function print(s){
   document.write(s);
}

This produces the following output:

CopyCode image Copy Code
Outer try running..
Nested try running...
Nested catch caught an error
Nested finally is running...
Outer catch caught an error re-thrown
Outer finally running

Expand image Requirements

Version 5

Expand image See Also

Reference

throw Statement (JScript 5.6)


var Statement (JScript 5.6)

JScript
var Statement (JScript 5.6)
See Also Example
CollapseAll image DropDown image

Declares a variable.

var variable1 [ = value1 ] [, variable2 [ = value2], ...]

Expand image Arguments

variable1, variable2

The names of the variables being declared.

value1, value2

The initial value assigned to the variable.

Expand image Remarks

Use the var statement to declare variables. These variables can be assigned values at declaration or later in your script.

Expand image Example

The following example illustrates the use of the var statement.

CopyCode image Copy Code
      var index;
var name = "Thomas Jefferson";
var answer = 42, counter, numpages = 10;

Expand image Requirements

Version 1

Expand image See Also

Reference

function Statement (JScript 5.6)
new Operator (JScript 5.6)


while Statement (JScript 5.6)

JScript
while Statement (JScript 5.6)
See Also Example
CollapseAll image DropDown image

Executes a statement until a specified condition is false.

while (expression)
      statements

Expand image Arguments

expression

Required. A Boolean expression checked before each iteration of the loop. If expression is true, the loop is executed. If expression is false, the loop is terminated.

statements

Optional. One or more statements to be executed if expression is true.

Expand image Remarks

The while statement checks expression before a loop is first executed. If expression is false at this time, the loop is never executed.

Expand image Example

The following example illustrates the use of the while statement.

CopyCode image Copy Code
function BreakTest(breakpoint){
   var i = 0;
   while (i < 100)
   {
   if (i == breakpoint)
      break;
      i++;
   }
   return(i);
}

Expand image Requirements

Version 1

Expand image See Also

Reference

break Statement (JScript 5.6)
continue Statement (JScript 5.6)
do...while Statement (JScript 5.6)
for Statement (JScript 5.6)
for...in Statement (JScript 5.6)


with Statement (JScript 5.6)

JScript
with Statement (JScript 5.6)
See Also
CollapseAll image DropDown image

Establishes the default object for a statement.

with (object)
      statements

Expand image Arguments

object

The new default object.

statements

One or more statements for which object is the default object.

Expand image Remarks

The with statement is commonly used to shorten the amount of code that you have to write in certain situations. In the example that follows, notice the repeated use of Math.

CopyCode image Copy Code
x = Math.cos(3 * Math.PI) + Math.sin(Math.LN10)
y = Math.tan(14 * Math.E)

When you use the with statement, your code becomes shorter and easier to read:

CopyCode image Copy Code
        with (Math){
   x = cos(3 * PI) + sin (LN10)
   y = tan(14 * E)
}

Expand image Requirements

Version 1

Expand image See Also

Reference

this Statement (JScript 5.6)


VBScript

Visual Basic Scripting Edition
VBScript
DropDown image

The following sections explain how to use VBScript and provide details about its language elements.

In This Section

VBScript User's Guide

Provides information about how to use VBScript and includes a guide to regular expressions.

VBScript Language Reference

Explains the elements that comprise the VBScript language.

Related Sections

JScript (Windows Script Technologies)

Includes information about how to use JScript and reference information about the language.


VBScript User's Guide

Visual Basic Scripting Edition
VBScript User's Guide
DropDown image

The VBScript User's Guide includes the following sections which explain the concept of VBScript and how to use it.

In This Section

What Is VBScript?

Defines VBScript and explains how it relates to other scripting languages.

Adding VBScript Code to an HTML Page

Explains how to use the SCRIPT element to add VBScript code to an HTML page.

VBScript Fundamentals

Introduces VBScript features and elements.

VBScript in Internet Explorer

Explains how VBScript works in Internet Explorer and provides examples.

Introduction to Regular Expressions (Scripting)

Describes the concept of regular expressions and how to create them.

Related Sections

VBScript Language Reference

Defines the elements of VBScript and provides syntax for proper use.


What Is VBScript?

Visual Basic Scripting Edition
What Is VBScript?
DropDown image

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.


Adding VBScript Code to an HTML Page

Visual Basic Scripting Edition
Adding VBScript Code to an HTML Page
DropDown image

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:

CopyCode image Copy Code
<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:

CopyCode image Copy Code
<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:

CopyCode image Copy Code
<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.


VBScript Fundamentals

Visual Basic Scripting Edition
VBScript Fundamentals
DropDown image

The following sections explain the basic design of the VBScript language.

In This Section

VBScript Features

Lists VBScript features by category and links to a reference topic for each feature.

VBScript Data Types

Explains the data types available in VBScript and how to use them.

VBScript Variables

Explains the concept of variables in VBScript and illustrates how to use them.

VBScript Constants

Illustrates how to create constants in VBScript.

VBScript Operators

Lists the VBScript operators and links to a reference topic that explains each operator.

Using Conditional Statements

Illustrates how to create and use conditions in VBScript code.

Looping Through Code

Explains how to use the various looping mechanisms in VBScript.

VBScript Procedures

Describes how construct and use the various types of procedures in VBScript.

VBScript Coding Conventions

Explains the conventions that govern the use of language elements in VBScript.

Related Sections

VBScript Language Reference

Defines the elements of VBScript and provides syntax for proper use.


VBScript Features

Visual Basic Scripting Edition
VBScript Features
CollapseAll image DropDown image

The following table is a list of VBScript features.

Expand image Features by Category

Category | Keywords
Array handling | 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 MsgBox
Literals | Empty False Nothing Null True
Math | Atn, Cos, Sin, Tan Exp, Log, Sqr Randomize, Rnd
Miscellaneous | Eval Function Execute Statement RGB Function
Objects | CreateObject Err Object GetObject RegExp
Operators | 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
Options | Option Explicit
Procedures | Call Function, Sub Property Get, Property Let, Property Set
Rounding | Abs Int, Fix, Round Sgn
Script Engine ID | ScriptEngine ScriptEngineBuildVersion ScriptEngineMajorVersion ScriptEngineMinorVersion
Strings | 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
Variants |


VBScript Data Types

Visual Basic Scripting Edition
VBScript Data Types
DropDown image

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 | Description
Empty | Variant is uninitialized. Value is 0 for numeric variables or a zero-length string ("") for string variables.
Null | Variant intentionally contains no valid data.
Boolean | Contains either True or False.
Byte | Contains integer in the range 0 to 255.
Integer | Contains integer in the range -32,768 to 32,767.
Currency | -922,337,203,685,477.5808 to 922,337,203,685,477.5807.
Long | Contains integer in the range -2,147,483,648 to 2,147,483,647.
Single | 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.
Double | 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.
Date (Time) | Contains a number that represents a date between January 1, 100 to December 31, 9999.
String | Contains a variable-length string that can be up to approximately 2 billion characters in length.
Object | Contains an object.
Error | 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.


VBScript Variables

Visual Basic Scripting Edition
VBScript Variables
DropDown image

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:

CopyCode image Copy Code
Dim DegreesFahrenheit

You declare multiple variables by separating each variable name with a comma. For example:

CopyCode image Copy Code
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 procedure-level 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:

CopyCode image Copy Code
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:

CopyCode image Copy Code
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:

CopyCode image Copy Code
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:

CopyCode image Copy Code
 . . .
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:

CopyCode image Copy Code
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:

CopyCode image Copy Code
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.

CopyCode image Copy Code
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.


VBScript Constants

Visual Basic Scripting Edition
VBScript Constants
DropDown image

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:

CopyCode image Copy Code
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:

CopyCode image Copy Code
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.


VBScript Operators

Visual Basic Scripting Edition
VBScript Operators
DropDown image

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 | Symbol
Equality | =
Inequality | <>
Less than | <
Greater than | >
Less than or equal to | <=
Greater than or equal to | >=
Object equivalence | Is

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.


Using Conditional Statements

Visual Basic Scripting Edition
Using Conditional Statements
DropDown image

You can control the flow of your script with conditional statements and looping statements.

Controlling Program Execution

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.

CopyCode image Copy Code
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:

CopyCode image Copy Code
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.

CopyCode image Copy Code
Sub AlertUser(value)
   If value = 0 Then
      AlertLabel.ForeColor = vbRed
      AlertLabel.Font.Bold = True
      AlertLabel.Font.Italic = True
   Else
      AlertLabel.Forecolor = vbBlack
      AlertLabel.Font.Bold = False
      AlertLabel.Font.Italic = False
   End If
End Sub

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:

CopyCode image Copy Code
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.

CopyCode image Copy Code
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.


Looping Through Code

Visual Basic Scripting Edition
Looping Through Code
DropDown image

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.

CopyCode image Copy Code
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.

CopyCode image Copy Code
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.

CopyCode image Copy Code
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.

CopyCode image Copy Code
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.

CopyCode image Copy Code
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.

CopyCode image Copy Code
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.

CopyCode image Copy Code
<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 = "Text"><p>
<Input Type = "Text"><p>
<Input Type = "Text"><p>
<Input Type = "Text"><p>
<Input Type = "Button" NAME="cmdChange" VALUE="Click Here"><p>
</FORM>
</CENTER>
</BODY>
</HTML>


VBScript Procedures

Visual Basic Scripting Edition
VBScript Procedures
DropDown image

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.

CopyCode image Copy Code
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.

CopyCode image Copy Code
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.

CopyCode image Copy Code
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:

CopyCode image Copy Code
Temp = Celsius(fDegrees)

-or-

CopyCode image Copy Code
MsgBox "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.

CopyCode image Copy Code
Call MyProc(firstarg, secondarg)
MyProc firstarg, secondarg

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


VBScript Coding Conventions

Visual Basic Scripting Edition
VBScript Coding Conventions
DropDown image

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:

CopyCode image Copy Code
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:

CopyCode image Copy Code
conYourOwnConstant

Variable Naming Conventions

To enhance readability and consistency, use the following prefixes with descriptive names for variables in your VBScript code.

Subtype | Prefix | Example
Boolean | bln | blnFound
Byte | byt | bytRasterData
Date (Time) | dtm | dtmStart
Double | dbl | dblTolerance
Error | err | errOrderNum
Integer | int | intQuantity
Long | lng | lngDistance
Object | obj | objCurrent
Single | sng | sngAverage
String | str | strFirstName

Variable Scope

Variables should always be defined with the smallest scope possible. VBScript variables can have the following scope.

Scope | Where Variable Is Declared | Visibility
Procedure-level | Event, Function, or Sub procedure. | Visible in the procedure in which it is declared.
Script-level | 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 | Prefix | Example
Procedure-level | None | dblVelocity
Script-level | s | 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 | Prefix | Example
3D Panel | pnl | pnlGroup
Animated button | ani | aniMailBox
Check box | chk | chkReadOnly
Combo box, drop-down list box | cbo | cboEnglish
Command button | cmd | cmdExit
Common dialog | dlg | dlgFileOpen
Frame | fra | fraLanguage
Horizontal scroll bar | hsb | hsbVolume
Image | img | imgIcon
Label | lbl | lblHelpMessage
Line | lin | linVertical
List Box | lst | lstPolicyCodes
Spin | spn | spnPages
Text box | txt | txtLastName
Vertical scroll bar | vsb | vsbRate
Slider | sld | 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 | Comment Contents
Purpose | What the procedure does (not how).
Assumptions | List of any external variable, control, or other element whose state affects this procedure.
Effects | List of the procedure's effect on each external variable, control, or other element.
Inputs | Explanation of each argument that is not obvious. Each argument should be on a separate line with inline comments.
Return Values | 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.

CopyCode image Copy Code
'*********************************************************
' 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


VBScript in Internet Explorer

Visual Basic Scripting Edition
VBScript in Internet Explorer
DropDown image

The following sections explain basic functionality of VBScript within Internet Explorer.

In This Section

A Simple VBScript Page

Illustrates how to use the OnClick event to display a message box.

Using VBScript with Objects

Illustrates how to use objects in VBScript.

VBScript and Forms

Illustrates how to create a validation form.

Related Sections

VBScript Language Reference

Explains the elements that comprise the VBScript language.


A Simple VBScript Page

Visual Basic Scripting Edition
A Simple VBScript Page
DropDown image

The following example illustrates how to add functionality to a Web page by including VBScript code.

A Simple Page

Paste the following code in a new text file, save the file with an .htm extension, and then double-click the file to view it in a browser. If you click the button on the page, you see VBScript in action.

CopyCode image Copy Code
<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:

CopyCode image Copy Code
<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:

CopyCode image Copy Code
<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.


Using VBScript with Objects

Visual Basic Scripting Edition
Using VBScript with Objects
DropDown image

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.

Using Objects

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 an ActiveX control, called Label, to a page. This code is for illustrative purposes — for your script to work, the control or object you are using has to be installed on the client computer.

CopyCode image Copy Code
<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 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:

CopyCode image Copy Code
<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:

CopyCode image Copy Code
<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 information about the properties, methods, events, and class identifiers (CLSID) for several controls on the Microsoft® Web site (http://activex.microsoft.com). You can find more information about the <OBJECT> tag by searching for "OBJECT element" at http://msdn.microsoft.com.

Note Note

Internet Explorer version 3 and earlier required braces ({}) around the classid attribute and did not conform to the W3C specification. Using braces with Internet Explorer version 4 and later generates a "This page uses an outdated version of the <OBJECT> tag" message.


VBScript and Forms

Visual Basic Scripting Edition
VBScript and Forms
DropDown image

The following example illustrates how to add validation functionality to a Web page by including VBScript code.

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.

Paste the following code in a new text file, save the file with an .htm extension, and then double-click the file to view it in a browser. The HTML code is for a text box and a button. If you use Microsoft® Internet Explorer to view the page, you'll see a small text box with a button next to it.

CopyCode image Copy Code
<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 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:

CopyCode image Copy Code
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:

CopyCode image Copy 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.


VBScript Language Reference

Visual Basic Scripting Edition
VBScript Language Reference
DropDown image

The following sections include information about the elements that comprise the VBScript language.

In This Section

Feature Information

Includes links to topics that list the versions that introduced VBScript features and includes links to topics that explain the feature differences between VBScript and VBA.

Constants

Lists the constants in VBScript and links to topics that explain how to use each constant.

Errors

Includes links to run-time and syntax error messages.

Events

Includes links to topics that explain events in VBScript.

Functions

Lists VBScript functions and links to topics that explain how to use each function.

Keywords

Includes links to topics that explain how to use keywords in VBScript.

Methods

Includes links to topics that explain how to use methods in VBScript.

Miscellaneous

Includes links to topics that are outside the normal category of VBScript language elements.

Objects and Collections

Lists VBScript objects and collections and links to topics that explain how to use each object or collection.

Operators

Includes links to topics that explain how to use operators in VBScript.

Properties

Lists VBScript properties and links to topics that explain how to use each property.

Statements

Lists VBScript statements and links to topics that explain how to use each statement.

Related Sections

VBScript Fundamentals

Introduces VBScript features and elements.


Feature Information (VBScript)

Visual Basic Scripting Edition
Feature Information (VBScript)
DropDown image

These sections include links to topics that list the versions that introduced VBScript features and include links to topics that explain the feature differences between VBScript and Visual Basic for Applications (VBA).

In This Section

Version Information

Includes a table that lists the versions that introduced VBScript features.

VBScript Features not in Visual Basic for Applications

Includes a table that lists the VBScript features that are not in VBA.

Visual Basic for Applications Features Not In VBScript

Includes a table that lists VBA features that are not in VBScript.

Related Sections

VBScript Fundamentals

Introduces VBScript features and elements.


VBScript Version Information

Visual Basic Scripting Edition
VBScript Version Information
DropDown image

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.1 | 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 Visual Studio 6.0 |  |  |  | x |  |  |  |
Microsoft Internet Explorer 5.0 |  |  |  |  | x |  |  |
Microsoft Internet Explorer 5.01 |  |  |  |  |  | x |  |
Microsoft Windows 2000 |  |  |  |  |  | x |  |
Microsoft Internet Explorer 5.5 |  |  |  |  |  |  | x |
Microsoft Windows Millennium Edition |  |  |  |  |  |  | x |
Microsoft Internet Explorer 6.0 |  |  |  |  |  |  |  | x
Microsoft Windows XP |  |  |  |  |  |  |  | x

The following table lists VBScript language features and the version when first introduced.

Language Element | 1.0 | 2.0 | 3.0 | 4.0 | 5.0 | 5.5 | 5.6
Abs Function | x |  |  |  |  |  |
Addition Operator (+) (VBScript) | x |  |  |  |  |  |
And Operator | x |  |  |  |  |  |
Array Function |  | x |  |  |  |  |
Asc Function | x |  |  |  |  |  |
Assignment Operator (=) (VBScript) | x |  |  |  |  |  |
Atn Function | x |  |  |  |  |  |
Call Statement | x |  |  |  |  |  |
CBool Function | x |  |  |  |  |  |
CByte Function | x |  |  |  |  |  |
CCur Function | x |  |  |  |  |  |
CDate Function | x |  |  |  |  |  |
CDbl Function | x |  |  |  |  |  |
Chr Function | x |  |  |  |  |  |
CInt Function | x |  |  |  |  |  |
Class Object |  |  |  |  | x |  |
Class Statement (VBScript) |  |  |  |  | x |  |
Clear Method (VBScript) | x |  |  |  |  |  |
CLng Function | x |  |  |  |  |  |
Color Constants |  | x |  |  |  |  |
Comparison Constants |  | x |  |  |  |  |
Comparison Operators (VBScript) | x |  |  |  |  |  |
Concatenation Operator (&) | x |  |  |  |  |  |
Const Statement (VBScript) |  | x |  |  |  |  |
Cos Function | x |  |  |  |  |  |
CreateObject Function |  | x |  |  |  |  |
CSng Function | x |  |  |  |  |  |
CStr Function | x |  |  |  |  |  |
Date and Time Constants |  | x |  |  |  |  |
Date Format Constants |  | x |  |  |  |  |
Date Function | x |  |  |  |  |  |
DateAdd Function |  | x |  |  |  |  |
DateDiff Function |  | x |  |  |  |  |
DatePart Function |  | x |  |  |  |  |
DateSerial Function | x |  |  |  |  |  |
DateValue Function | x |  |  |  |  |  |
Day Function | x |  |  |  |  |  |
Debug Object |  |  | x |  |  |  |
Description Property (VBScript) | x |  |  |  |  |  |
Dim Statement | x |  |  |  |  |  |
Division Operator (/) (VBScript) | x |  |  |  |  |  |
Do...Loop Statement | x |  |  |  |  |  |
Empty Keyword | x |  |  |  |  |  |
Eqv Operator | x |  |  |  |  |  |
Erase Statement | x |  |  |  |  |  |
Err Object (VBScript) | x |  |  |  |  |  |
Escape Function |  |  |  |  | x |  |
Eval Function |  |  |  |  | x |  |
Execute Method |  |  |  |  | x |  |
Execute Statement |  |  |  |  | x |  |
ExecuteGlobal Statement |  |  |  |  | x |  |
Exit Statement | x |  |  |  |  |  |
Exp Function | x |  |  |  |  |  |
Exponentiation Operator (^) | x |  |  |  |  |  |
False (Windows Script Technologies) | x |  |  |  |  |  |
Filter Function |  | x |  |  |  |  |
FirstIndex Property |  |  |  |  | x |  |
Int, Fix Functions | x |  |  |  |  |  |
For...Next Statement | x |  |  |  |  |  |
For Each...Next Statement |  | x |  |  |  |  |
FormatCurrency Function |  | x |  |  |  |  |
FormatDateTime Function |  | x |  |  |  |  |
FormatNumber Function |  | x |  |  |  |  |
FormatPercent Function |  | x |  |  |  |  |
Function Statement (VBScript) | x |  |  |  |  |  |
GetLocale Function |  |  |  |  | x |  |
GetObject Function |  | x |  |  |  |  |
GetRef Function |  |  |  |  | x |  |
Global Property (VBScript) |  |  |  |  | x |  |
Hex Function | x |  |  |  |  |  |
HelpContext Property |  | x |  |  |  |  |
HelpFile Property (VBScript) |  | x |  |  |  |  |
Hour Function | x |  |  |  |  |  |
If...Then...Else Statement | x |  |  |  |  |  |
IgnoreCase Property (VBScript) |  |  |  |  | x |  |
Imp Operator | x |  |  |  |  |  |
Initialize Event |  |  |  |  | x |  |
InputBox Function | x |  |  |  |  |  |
InStr Function | x |  |  |  |  |  |
InStrRev Function |  | x |  |  |  |  |
Int, Fix Functions | x |  |  |  |  |  |
Integer Division Operator (\) | x |  |  |  |  |  |
Is Operator | x |  |  |  |  |  |
IsArray Function | x |  |  |  |  |  |
IsDate Function | x |  |  |  |  |  |
IsEmpty Function | x |  |  |  |  |  |
IsNull Function | x |  |  |  |  |  |
IsNumeric Function | x |  |  |  |  |  |
IsObject Function | x |  |  |  |  |  |
Join Function |  | x |  |  |  |  |
LBound Function | x |  |  |  |  |  |
LCase Function | x |  |  |  |  |  |
Left Function | x |  |  |  |  |  |
Len Function | x |  |  |  |  |  |
Length Property |  |  |  |  | x |  |
LoadPicture Function |  | x |  |  |  |  |
Log Function | x |  |  |  |  |  |
LTrim; RTrim; and Trim Functions | x |  |  |  |  |  |
Match Object |  |  |  |  | x |  |
Matches Collection |  |  |  |  | x |  |
Mid Function | x |  |  |  |  |  |
Minute Function (VBScript) | x |  |  |  |  |  |
Miscellaneous Constants |  | x |  |  |  |  |
Mod Operator | x |  |  |  |  |  |
Month Function | x |  |  |  |  |  |
MonthName Function |  | x |  |  |  |  |
MsgBox Constants |  | x |  |  |  |  |
MsgBox Function | x |  |  |  |  |  |
Multiplication Operator (*) (VBScript) | x |  |  |  |  |  |
Subtraction Operator (-) (VBScript) | x |  |  |  |  |  |
Not Operator | x |  |  |  |  |  |
Now Function | x |  |  |  |  |  |
Nothing Keyword | x |  |  |  |  |  |
Null Keyword | x |  |  |  |  |  |
Number Property (VBScript) | x |  |  |  |  |  |
Oct Function (VBScript) | x |  |  |  |  |  |
On Error Statement | x |  |  |  |  |  |
Option Explicit Statement | x |  |  |  |  |  |
Or Operator | x |  |  |  |  |  |
Pattern Property |  |  |  |  | x |  |
Private Statement |  | x |  |  |  |  |
Property Get Statement |  |  |  |  | x |  |
Property Let Statement |  |  |  |  | x |  |
Property Set Statement |  |  |  |  | x |  |
Public Statement |  | x |  |  |  |  |
Raise Method | x |  |  |  |  |  |
Randomize Statement | x |  |  |  |  |  |
ReDim Statement | x |  |  |  |  |  |
Regular Expression (RegExp) Object |  |  |  |  | x |  |
Rem Statement | x |  |  |  |  |  |
Replace Function |  | x |  |  |  |  |
Replace Method (VBScript) |  |  |  |  | x |  |
RGB Function |  | x |  |  |  |  |
Right Function | x |  |  |  |  |  |
Rnd Function | x |  |  |  |  |  |
Round Function |  | x |  |  |  |  |
LTrim; RTrim; and Trim Functions | x |  |  |  |  |  |
ScriptEngine Function |  | x |  |  |  |  |
ScriptEngineBuildVersion Function |  | x |  |  |  |  |
ScriptEngineMajorVersion Function |  | x |  |  |  |  |
ScriptEngineMinorVersion Function |  | x |  |  |  |  |
Second Function | x |  |  |  |  |  |
Select Case Statement | x |  |  |  |  |  |
Set Statement | x |  |  |  |  |  |
SetLocale Function |  |  |  |  | x |  |
Sgn Function | x |  |  |  |  |  |
Sin Function | x |  |  |  |  |  |
Source Property (VBScript) | x |  |  |  |  |  |
Space Function | x |  |  |  |  |  |
Split Function |  | x |  |  |  |  |
Sqr Function | x |  |  |  |  |  |
Stop Statement |  |  | x |  |  |  |
StrComp Function | x |  |  |  |  |  |
String Constants |  | x |  |  |  |  |
String Function | x |  |  |  |  |  |
StrReverse Function |  | x |  |  |  |  |
Sub Statement | x |  |  |  |  |  |
SubMatches Collection |  |  |  |  |  | x |
Subtraction Operator (-) (VBScript) | x |  |  |  |  |  |
Tan Function | x |  |  |  |  |  |
Terminate Event |  |  |  |  | x |  |
Test Method (VBScript) |  |  |  |  | x |  |
Time Function | x |  |  |  |  |  |
Timer Function |  |  |  |  | x |  |
TimeSerial Function | x |  |  |  |  |  |
TimeValue Function | x |  |  |  |  |  |
LTrim; RTrim; and Trim Functions | x |  |  |  |  |  |
Tristate Constants |  | x |  |  |  |  |
True Keyword | x |  |  |  |  |  |
TypeName Function |  | x |  |  |  |  |
UBound Function | x |  |  |  |  |  |
UCase Function | x |  |  |  |  |  |
Unescape Function |  |  |  |  | x |  |
Value Property (VBScript) |  |  |  |  | x |  |
VarType Constants |  | x |  |  |  |  |
VarType Function | x |  |  |  |  |  |
Constants (VBScript) |  | x |  |  |  |  |
Weekday Function | x |  |  |  |  |  |
WeekdayName Function |  | x |  |  |  |  |
While...Wend Statement | x |  |  |  |  |  |
With Statement (VBScript) |  |  |  |  | x |  |
Write Method |  |  | x |  |  |  |
WriteLine Method |  |  | x |  |  |  |
Xor Operator | x |  |  |  |  |  |
Year Function | x |  |  |  |  |  |


VBScript Features not in Visual Basic for Applications

Visual Basic Scripting Edition
VBScript Features not in Visual Basic for Applications
CollapseAll image DropDown image

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

Expand image Features

Category | Feature/Keyword
Declarations | Class
Miscellaneous | Eval Execute
Objects | RegExp
Script Engine Identification | ScriptEngine ScriptEngineBuildVersion ScriptEngineMajorVersion ScriptEngineMinorVersion


Visual Basic for Applications Features Not In VBScript

Visual Basic Scripting Edition
Visual Basic for Applications Features Not In VBScript
CollapseAll image DropDown image

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

Expand image Features

Category | Omitted Feature/Keyword
Array Handling | 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 !


Constants (VBScript)

Visual Basic Scripting Edition
Constants (VBScript)
DropDown image

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 basic colors that can be used in scripting.

  • Comparison Constants Defines constants used to compare strings.

  • Date and Time Constants Defines date and time constants used by various date and time functions.

  • Date Format Constants Defines constants used to format dates and times.

  • Miscellaneous Constants Defines constants that don't conveniently fit into any other category.

  • MsgBox Constants Defines constants used in the MsgBox function to describe button visibility, labeling, behavior, and return values.

  • String Constants Defines a variety of non-printable characters used in string manipulation.

  • Tristate Constants Defines constants used with functions that format numbers.

  • VarType Constants Defines the various Variant subtypes.

Requirements

Version 2


Color Constants

Visual Basic Scripting Edition
Color Constants
See Also
DropDown image

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
vbBlack | &h00 | Black
vbRed | &hFF | Red
vbGreen | &hFF00 | Green
vbYellow | &hFFFF | Yellow
vbBlue | &hFF0000 | Blue
vbMagenta | &hFF00FF | Magenta
vbCyan | &hFFFF00 | Cyan
vbWhite | &hFFFFFF | White

Requirements

Version 2

See Also

Concepts

Comparison Constants
Date and Time Constants
Date Format Constants
Miscellaneous Constants
MsgBox Constants
String Constants
Tristate Constants
VarType Constants


Comparison Constants

Visual Basic Scripting Edition
Comparison Constants
See Also
DropDown image

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

Concepts

Color Constants
Date and Time Constants
Date Format Constants
Miscellaneous Constants
MsgBox Constants
String Constants
Tristate Constants
VarType Constants


Date and Time Constants

Visual Basic Scripting Edition
Date and Time Constants
See Also
DropDown image

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
vbSunday | 1 | Sunday
vbMonday | 2 | Monday
vbTuesday | 3 | Tuesday
vbWednesday | 4 | Wednesday
vbThursday | 5 | Thursday
vbFriday | 6 | Friday
vbSaturday | 7 | Saturday
vbUseSystemDayOfWeek | 0 | Use the day of the week specified in your system settings for the first day of the week.
vbFirstJan1 | 1 | Use the week in which January 1 occurs (default).
vbFirstFourDays | 2 | Use the first week that has at least four days in the new year.
vbFirstFullWeek | 3 | Use the first full week of the year.

Requirements

Version 2

See Also

Concepts

Color Constants
Comparison Constants
Date Format Constants
Miscellaneous Constants
MsgBox Constants
String Constants
Tristate Constants
VarType Constants


Date Format Constants

Visual Basic Scripting Edition
Date Format Constants
See Also
DropDown image

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
vbGeneralDate | 0 | 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.
vbLongDate | 1 | Display a date using the long date format specified in your computer's regional settings.
vbShortDate | 2 | Display a date using the short date format specified in your computer's regional settings.
vbLongTime | 3 | Display a time using the long time format specified in your computer's regional settings.
vbShortTime | 4 | Display a time using the short time format specified in your computer's regional settings.

Requirements

Version 2

See Also

Concepts

Color Constants
Comparison Constants
Date and Time Constants
Miscellaneous Constants
MsgBox Constants
String Constants
Tristate Constants
VarType Constants


Miscellaneous Constants

Visual Basic Scripting Edition
Miscellaneous Constants
See Also
DropDown image

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 Value Description

vbObjectError

-2147221504

User-defined error numbers should be greater than this value, for example,

CopyCode image Copy Code
Err.Raise Number = vbObjectError + 1000

Requirements

Version 2

See Also

Concepts

Color Constants
Comparison Constants
Date and Time Constants
Date Format Constants
MsgBox Constants
String Constants
Tristate Constants
VarType Constants


MsgBox Constants

Visual Basic Scripting Edition
MsgBox Constants
See Also
DropDown image

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 | Description
vbOKOnly | 0 | Display OK button only.
vbOKCancel | 1 | Display OK and Cancel buttons.
vbAbortRetryIgnore | 2 | Display Abort, Retry, and Ignore buttons.
vbYesNoCancel | 3 | Display Yes, No, and Cancel buttons.
vbYesNo | 4 | Display Yes and No buttons.
vbRetryCancel | 5 | Display Retry and Cancel buttons.
vbCritical | 16 | Display Critical Message icon.
vbQuestion | 32 | Display Warning Query icon.
vbExclamation | 48 | Display Warning Message icon.
vbInformation | 64 | Display Information Message icon.
vbDefaultButton1 | 0 | First button is the default.
vbDefaultButton2 | 256 | Second button is the default.
vbDefaultButton3 | 512 | Third button is the default.
vbDefaultButton4 | 768 | Fourth button is the default.
vbApplicationModal | 0 | Application modal. The user must respond to the message box before continuing work in the current application.
vbSystemModal | 4096 | 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 | Value | Description
vbOK | 1 | OK button was clicked.
vbCancel | 2 | Cancel button was clicked.
vbAbort | 3 | Abort button was clicked.
vbRetry | 4 | Retry button was clicked.
vbIgnore | 5 | Ignore button was clicked.
vbYes | 6 | Yes button was clicked.
vbNo | 7 | No button was clicked.

Requirements

Version 2

See Also

Concepts

Color Constants
Comparison Constants
Date and Time Constants
Date Format Constants
Miscellaneous Constants
String Constants
Tristate Constants
VarType Constants


String Constants

Visual Basic Scripting Edition
String Constants
See Also
DropDown image

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
vbCr | Chr(13) | Carriage return.
VbCrLf | Chr(13) & Chr(10) | Carriage return–linefeed combination.
vbFormFeed | Chr(12) | Form feed; not useful in Microsoft Windows.
vbLf | Chr(10) | Line feed.
vbNewLine | Chr(13) & Chr(10) or Chr(10) | Platform-specific newline character; whatever is appropriate for the platform.
vbNullChar | Chr(0) | Character having the value 0.
vbNullString | String having value 0 | Not the same as a zero-length string (""); used for calling external procedures.
vbTab | Chr(9) | Horizontal tab.
vbVerticalTab | Chr(11) | Vertical tab; not useful in Microsoft Windows.

Requirements

Version 2

See Also

Concepts

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


Tristate Constants

Visual Basic Scripting Edition
Tristate Constants
See Also
DropDown image

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
vbUseDefault | -2 | Use default from computer's regional settings.
vbTrue | -1 | True
vbFalse | 0 | False

Requirements

Version 2

See Also

Concepts

Color Constants
Comparison Constants
Date and Time Constants
Date Format Constants
Miscellaneous Constants
MsgBox Constants
String Constants
VarType Constants


VarType Constants

Visual Basic Scripting Edition
VarType Constants
See Also
DropDown image

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 | Value | Description
vbEmpty | 0 | Uninitialized (default)
vbNull | 1 | Contains no valid data
vbInteger | 2 | Integer subtype
vbLong | 3 | Long subtype
vbSingle | 4 | Single subtype
vbDouble | 5 | Double subtype
vbCurrency | 6 | Currency subtype
vbDate | 7 | Date subtype
vbString | 8 | String subtype
vbObject | 9 | Object
vbError | 10 | Error subtype
vbBoolean | 11 | Boolean subtype
vbVariant | 12 | Variant (used only for arrays of variants)
vbDataObject | 13 | Data access object
vbDecimal | 14 | Decimal subtype
vbByte | 17 | Byte subtype
vbArray | 8192 | Array

Requirements

Version 2

See Also

Concepts

Color Constants
Comparison Constants
Date and Time Constants
Date Format Constants
Miscellaneous Constants
MsgBox Constants
String Constants
Tristate Constants


Errors (VBScript)

Visual Basic Scripting Edition
Errors (VBScript)
DropDown image

These sections include links to topics that explain VBScript run-time and syntax errors.

In This Section

VBScript Run-time Errors

Lists VBScript run-time errors and links to topics that explain each error.

VBScript Syntax Errors

Lists VBScript syntax errors and links to topics that explain each error.

Related Sections

VBScript Fundamentals

Introduces VBScript features and elements.


VBScript Run-time Errors

Visual Basic Scripting Edition
VBScript Run-time Errors
See Also
DropDown image

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.

Errors

Error Number | Description
429 | ActiveX component can't create object
507 | An exception occurred
449 | Argument not optional
17 | Can't perform requested operation
430 | Class doesn't support Automation
506 | Class not defined
11 | Division by zero
48 | Error in loading DLL
5020 | Expected ')' in regular expression
5019 | Expected ']' in regular expression
432 | File name or class name not found during Automation operation
92 | For loop not initialized
5008 | Illegal assignment
51 | Internal error
505 | Invalid or unqualified reference
481 | Invalid picture
5 | Invalid procedure call or argument
5021 | Invalid range in character set
94 | Invalid use of Null
448 | Named argument not found
447 | Object doesn't support current locale setting
445 | Object doesn't support this action
438 | Object doesn't support this property or method
451 | Object not a collection
504 | Object not safe for creating
503 | Object not safe for initializing
502 | Object not safe for scripting
424 | Object required
91 | Object variable not set
7 | Out of Memory
28 | Out of stack space
14 | Out of string space
6 | Overflow
35 | Sub or function not defined
9 | Subscript out of range
5017 | Syntax error in regular expression
462 | The remote server machine does not exist or is unavailable
10 | This array is fixed or temporarily locked
13 | Type mismatch
5018 | Unexpected quantifier
500 | Variable is undefined
458 | Variable uses an Automation type not supported in VBScript
450 | Wrong number of arguments or invalid property assignment

See Also

Concepts

VBScript Syntax Errors


VBScript Syntax Errors

Visual Basic Scripting Edition
VBScript Syntax Errors
See Also
DropDown image

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.

Errors

Error Number | Description
1052 | Cannot have multiple default property/method in a Class
1044 | Cannot use parentheses when calling a Sub
1053 | Class initialize or terminate do not have arguments
1058 | 'Default' specification can only be on Property Get
1057 | 'Default' specification must also specify 'Public'
1005 | Expected '('
1006 | Expected ')'
1011 | Expected '='
1021 | Expected 'Case'
1047 | Expected 'Class'
1025 | Expected end of statement
1014 | Expected 'End'
1023 | Expected expression
1015 | Expected 'Function'
1010 | Expected identifier
1012 | Expected 'If'
1046 | Expected 'In'
1026 | Expected integer constant
1049 | Expected Let or Set or Get in property declaration
1045 | Expected literal constant
1019 | Expected 'Loop'
1020 | Expected 'Next'
1050 | Expected 'Property'
1022 | Expected 'Select'
1024 | Expected statement
1016 | Expected 'Sub'
1017 | Expected 'Then'
1013 | Expected 'To'
1018 | Expected 'Wend'
1027 | Expected 'While' or 'Until'
1028 | Expected 'While,' 'Until,' or end of statement
1029 | Expected 'With'
1030 | Identifier too long
1014 | Invalid character
1039 | Invalid 'exit' statement
1040 | Invalid 'for' loop control variable
1013 | Invalid number
1037 | Invalid use of 'Me' keyword
1038 | 'loop' without 'do'
1048 | Must be defined inside a Class
1042 | Must be first statement on the line
1041 | Name redefined
1051 | Number of arguments must be consistent across properties specification
1001 | Out of Memory
1054 | Property Set or Let must have at least one argument
1002 | Syntax error
1055 | Unexpected 'Next'
1015 | Unterminated string constant

See Also

Concepts

VBScript Run-time Errors


Events (VBScript)

Visual Basic Scripting Edition
Events (VBScript)
DropDown image

These sections link to topics that explain how to use the VBScript events.

In This Section

Initialize Event

Illustrates with example code how to use the Initialize event.

Terminate Event

Illustrates with example code how to use the Terminate event.

Related Sections

VBScript Fundamentals

Introduces VBScript features and elements.


Initialize Event

Visual Basic Scripting Edition
Initialize Event
See Also
CollapseAll image DropDown image

Occurs when an instance of the associated class is created.

Private Sub Class_Initialize()
      statements
End Sub

Expand image Remarks

The statements part consists of zero or more code statements to be run when the class is initialized.

The following example illustrates the use of the Initialize event.

CopyCode image Copy Code
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.

Expand image Requirements

Version 5

Applies To: Class Object

Expand image See Also

Reference

Class Statement (VBScript)
Terminate Event

Concepts

Class Object


Terminate Event

Visual Basic Scripting Edition
Terminate Event
See Also
CollapseAll image DropDown image

Occurs when an instance of the associated class is terminated.

Private Sub Class_Terminate()
      statements
End Sub

Expand image Remarks

The statements part consists of zero or more code statements to be run when the class is initialized.

The following example illustrates the use of the Terminate event.

CopyCode image Copy Code
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.

Expand image Requirements

Version 5

Applies To: Class Object

Expand image See Also

Reference

Class Statement (VBScript)
Initialize Event

Concepts

Class Object


Functions (VBScript)

Visual Basic Scripting Edition
Functions (VBScript)
See Also
DropDown image

The following table contains the VBScript functions.

Functions

Abs | Array | Asc | Atn
CBool | CByte | CCur | CDate
CDbl | Chr | CInt | CLng
Conversions | Cos | CreateObject | CSng
CStr | Date | DateAdd | DateDiff
DatePart | DateSerial | DateValue | Day
Derived Math | Escape | Eval | Exp
Filter | FormatCurrency | FormatDateTime | FormatNumber
FormatPercent | GetLocale | GetObject | GetRef
Hex | Hour | InputBox | InStr
InStrRev | Int, Fix | IsArray | IsDate
IsEmpty | IsNull | IsNumeric | IsObject
Join | LBound | LCase | Left
Len | LoadPicture | Log | LTrim; RTrim; and Trim
Maths | Mid | Minute | Month
MonthName | MsgBox | Now | Oct
Replace | RGB | Right | Rnd
Round | ScriptEngine | ScriptEngineBuildVersion | ScriptEngineMajorVersion
ScriptEngineMinorVersion | Second | SetLocale | Sgn
Sin | Space | Split | Sqr
StrComp | String | StrReverse | Tan
Time | Timer | TimeSerial | TimeValue
TypeName | UBound | UCase | Unescape
VarType | Weekday | WeekdayName | Year

See Also

Other Resources

VBScript Language Reference


Abs Function

Visual Basic Scripting Edition
Abs Function
See Also
CollapseAll image DropDown image

Returns the absolute value of a number.

Abs(number)

Expand image Remarks

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.

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:

CopyCode image Copy Code
Dim MyNumber
MyNumber = Abs(50.3)  ' Returns 50.3.
MyNumber = Abs(-50.3) ' Returns 50.3.

Expand image Requirements

Version 1

Expand image See Also

Reference

Sgn Function


Array Function

Visual Basic Scripting Edition
Array Function
See Also
CollapseAll image DropDown image

Returns a Variant containing an array.

Array(arglist)

Expand image Remarks

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.

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.

CopyCode image Copy Code
Dim A
A = Array(10,20,30)
B = A(2)   ' B is now 30.
Note 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.

Expand image Requirements

Version 2

Expand image See Also

Reference

Dim Statement
ReDim Statement
IsArray Function
LBound Function
UBound Function
Private Statement
Public Statement
Erase Statement


Asc Function

Visual Basic Scripting Edition
Asc Function
See Also
CollapseAll image DropDown image

Returns the ANSI character code corresponding to the first letter in a string.

Asc(string)

Expand image Remarks

The string argument is any valid string expression. If the string contains no characters, a run-time error occurs.

In the following example, Asc returns the ANSI character code of the first letter of each string:

CopyCode image Copy Code
Dim MyNumber
MyNumber = Asc("A")       ' Returns 65.
MyNumber = Asc("a")       ' Returns 97.
MyNumber = Asc("Apple")   ' Returns 65.
Note 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.

Expand image Requirements

Version 1

Expand image See Also

Reference

Chr Function


Atn Function

Visual Basic Scripting Edition
Atn Function
See Also
CollapseAll image DropDown image

Returns the arctangent of a number.

Atn(number)

Expand image Remarks

The number argument can be any valid numeric expression.

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:

CopyCode image Copy Code
Dim pi
pi = 4 * Atn(1)   ' Calculate the value of pi.
Note Note

Atn is 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).

Expand image Requirements

Version 1

Expand image See Also

Reference

Cos Function
Sin Function
Tan Function

Concepts

Derived Math Functions


CBool Function

Visual Basic Scripting Edition
CBool Function
See Also
CollapseAll image DropDown image

Returns an expression that has been converted to a Variant of subtype Boolean.

CBool(expression)

Expand image Remarks

The expression argument is any valid expression.

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.

CopyCode image Copy Code
Dim A, B, Check
A = 5: B = 5           ' Initialize variables.
Check = CBool(A = B)   ' Check contains True.
A = 0                  ' Define variable.
Check = CBool(A)       ' Check contains False.

Expand image Requirements

Version 1

Expand image See Also

Reference

CByte Function
CCur Function
CDate Function
CDbl Function
CInt Function
CLng Function
CSng Function
CStr Function


CByte Function

Visual Basic Scripting Edition
CByte Function
See Also
CollapseAll image DropDown image

Returns an expression that has been converted to a Variant of subtype Byte.

CByte(expression)

Expand image Remarks

The expression argument is any valid expression.

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:

CopyCode image Copy Code
Dim MyDouble, MyByte
MyDouble = 125.5678        ' MyDouble is a Double.
MyByte = CByte(MyDouble)   ' MyByte contains 126.

Expand image Requirements

Version 1

Expand image See Also

Reference

CBool Function
CCur Function
CDate Function
CDbl Function
CInt Function
CLng Function
CSng Function
CStr Function


CCur Function

Visual Basic Scripting Edition
CCur Function
See Also
CollapseAll image DropDown image

Returns an expression that has been converted to a Variant of subtype Currency.

CCur(expression)

Expand image Remarks

The expression argument is any valid expression.

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:

CopyCode image Copy Code
Dim MyDouble, MyCurr
MyDouble = 543.214588         ' MyDouble is a Double.
MyCurr = CCur(MyDouble * 2)   ' Convert result of MyDouble * 2 (1086.429176) to a Currency (1086.4292).

Expand image Requirements

Version 1

Expand image See Also

Reference

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


CDate Function

Visual Basic Scripting Edition
CDate Function
See Also
CollapseAll image DropDown image

Returns an expression that has been converted to a Variant of subtype Date.

CDate(date)

Expand image Remarks

The date argument is any valid date expression.

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.

CopyCode image Copy Code
MyDate = "October 19, 1962"   ' Define date.
MyShortDate = CDate(MyDate)   ' Convert to Date data type.
MyTime = "4:35:47 PM"         ' Define time.
MyShortTime = CDate(MyTime)   ' Convert to Date data type.

Expand image Requirements

Version 1

Expand image See Also

Reference

IsDate Function


CDbl Function

Visual Basic Scripting Edition
CDbl Function
See Also
CollapseAll image DropDown image

Returns an expression that has been converted to a Variant of subtype Double.

CDbl(expression)

Expand image Remarks

The expression argument is any valid expression.

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.

CopyCode image Copy Code
Dim MyCurr, MyDouble
MyCurr = CCur(234.456784)              ' MyCurr is a Currency (234.4567).
MyDouble = CDbl(MyCurr * 8.2 * 0.01)   ' Convert result to a Double (19.2254576).

Expand image Requirements

Version 1

Expand image See Also

Reference

CBool Function
CByte Function
CCur Function
CDate Function
CInt Function
CLng Function
CSng Function
CStr Function


Chr Function

Visual Basic Scripting Edition
Chr Function
See Also
CollapseAll image DropDown image

Returns the character associated with the specified ANSI character code.

Chr(charcode)

Expand image Remarks

The charcode argument is a number that identifies a character.

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:

CopyCode image Copy Code
Dim MyChar
MyChar = Chr(65)   ' Returns A.
MyChar = Chr(97)   ' Returns a.
MyChar = Chr(62)   ' Returns >.
MyChar = Chr(37)   ' Returns %.
Note 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.

Expand image Requirements

Version 1

Expand image See Also

Reference

Asc Function


CInt Function

Visual Basic Scripting Edition
CInt Function
See Also
CollapseAll image DropDown image

Returns an expression that has been converted to a Variant of subtype Integer.

CInt(expression)

Expand image Remarks

The expression argument is any valid expression.

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:

CopyCode image Copy Code
Dim MyDouble, MyInt
MyDouble = 2345.5678     ' MyDouble is a Double.
MyInt = CInt(MyDouble)   ' MyInt contains 2346.
Note Note

CInt 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 CInt function always rounds it to the nearest even number. For example, 0.5 rounds to 0, and 1.5 rounds to 2.

Expand image Requirements

Version 1

Expand image See Also

Reference

CBool Function
CByte Function
CCur Function
CDate Function
CDbl Function
CLng Function
CSng Function
CStr Function
Int, Fix Functions
Round Function


CLng Function

Visual Basic Scripting Edition
CLng Function
See Also
CollapseAll image DropDown image

Returns an expression that has been converted to a Variant of subtype Long.

CLng(expression)

Expand image Remarks

The expression argument is any valid expression.

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:

CopyCode image Copy Code
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 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.

Expand image Requirements

Version 1

Expand image See Also

Reference

CBool Function
CByte Function
CCur Function
CDate Function
CDbl Function
CInt Function
CSng Function
CStr Function
Int, Fix Functions
Round Function


Conversion Functions

Visual Basic Scripting Edition
Conversion Functions
DropDown image

The following table lists the conversion functions in VBScript.

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 |


Cos Function

Visual Basic Scripting Edition
Cos Function
See Also
CollapseAll image DropDown image

Returns the cosine of an angle.

Cos(number)

Expand image Remarks

The number argument can be any valid numeric expression that expresses an angle in radians.

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:

CopyCode image Copy Code
Dim MyAngle, MySecant
MyAngle = 1.3                 ' Define angle in radians.
MySecant = 1 / Cos(MyAngle)   ' Calculate secant.

Expand image Requirements

Version 1

Expand image See Also

Reference

Atn Function
Sin Function
Tan Function

Concepts

Derived Math Functions


CreateObject Function

Visual Basic Scripting Edition
CreateObject Function
See Also
CollapseAll image DropDown image

Creates and returns a reference to an Automation object.

CreateObject(servername.typename [, location])

Expand image 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.

Expand image 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:

CopyCode image Copy Code
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:

CopyCode image Copy Code
' 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":

CopyCode image Copy Code
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.

Expand image Requirements

Version 2

Expand image See Also

Reference

GetObject Function


CSng Function

Visual Basic Scripting Edition
CSng Function
See Also
CollapseAll image DropDown image

Returns an expression that has been converted to a Variant of subtype Single.

CSng(expression)

Expand image Remarks

The expression argument is any valid expression.

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:

CopyCode image Copy Code
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.

Expand image Requirements

Version 1

Expand image See Also

Reference

CBool Function
CByte Function
CCur Function
CDate Function
CDbl Function
CInt Function
CLng Function
CStr Function


CStr Function

Visual Basic Scripting Edition
CStr Function
See Also
CollapseAll image DropDown image

Returns an expression that has been converted to a Variant of subtype String.

CStr(expression)

Expand image Remarks

The expression argument is any valid expression.

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 | CStr returns
Boolean | A String containing True or False.
Date | A String containing a date in the short-date format of your system.
Null | A run-time error.
Empty | A zero-length String ("").
Error | A String containing the word Error followed by the error number.
Other numeric | A String containing the number.

The following example uses the CStr function to convert a numeric value to a String:

CopyCode image Copy Code
Dim MyDouble, MyString
MyDouble = 437.324         ' MyDouble is a Double.
MyString = CStr(MyDouble)   ' MyString contains "437.324".

Expand image Requirements

Version 1

Expand image See Also

Reference

CBool Function
CByte Function
CCur Function
CDate Function
CDbl Function
CInt Function
CLng Function
CSng Function


Date Function

Visual Basic Scripting Edition
Date Function
See Also
CollapseAll image DropDown image

Returns the current system date.

Date

Expand image Remarks

The following example uses the Date function to return the current system date:

CopyCode image Copy Code
Dim MyDate
MyDate = Date   ' MyDate contains the current system date.

Expand image Requirements

Version 1

Expand image See Also

Reference

CDate Function
Now Function
Time Function


DateAdd Function

Visual Basic Scripting Edition
DateAdd Function
See Also
CollapseAll image DropDown image

Returns a date to which a specified time interval has been added.

DateAdd(interval, number, date)

Expand image 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.

Expand image 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

Expand image 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:

CopyCode image Copy Code
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.

Expand image Requirements

Version 2

Expand image See Also

Reference

DateDiff Function
DatePart Function


DateDiff Function

Visual Basic Scripting Edition
DateDiff Function
See Also
CollapseAll image DropDown image

Returns the number of intervals between two dates.

DateDiff(interval, date1, date2 [,firstdayofweek[, firstweekofyear]])

Expand image 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.

Expand image 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 | Description
vbUseSystemDayOfWeek | 0 | Use National Language Support (NLS) API setting.
vbSunday | 1 | Sunday (default)
vbMonday | 2 | Monday
vbTuesday | 3 | Tuesday
vbWednesday | 4 | Wednesday
vbThursday | 5 | Thursday
vbFriday | 6 | Friday
vbSaturday | 7 | Saturday

The firstweekofyear argument can have the following values:

Constant | Value | Description
vbUseSystem | 0 | Use National Language Support (NLS) API setting.
vbFirstJan1 | 1 | Start with the week in which January 1 occurs (default).
vbFirstFourDays | 2 | Start with the week that has at least four days in the new year.
vbFirstFullWeek | 3 | Start with the first full week of the new year.

Expand image 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:

CopyCode image Copy Code
Function DiffADate(theDate)
   DiffADate = "Days from today: " & DateDiff("d", Now, theDate)
End Function

Expand image Requirements

Version 2

Expand image See Also

Reference

DateAdd Function
DatePart Function


DatePart Function

Visual Basic Scripting Edition
DatePart Function
See Also
CollapseAll image DropDown image

Returns the specified part of a given date.

DatePart(interval, date[, firstdayofweek[, firstweekofyear]])

Expand image 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.

Expand image 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 | Description
vbUseSystemDayOfWeek | 0 | Use National Language Support (NLS) API setting.
vbSunday | 1 | Sunday (default)
vbMonday | 2 | Monday
vbTuesday | 3 | Tuesday
vbWednesday | 4 | Wednesday
vbThursday | 5 | Thursday
vbFriday | 6 | Friday
vbSaturday | 7 | Saturday

The firstweekofyear argument can have the following values:

Constant | Value | Description
vbUseSystem | 0 | Use National Language Support (NLS) API setting.
vbFirstJan1 | 1 | Start with the week in which January 1 occurs (default).
vbFirstFourDays | 2 | Start with the week that has at least four days in the new year.
vbFirstFullWeek | 3 | Start with the first full week of the new year.

Expand image 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.

CopyCode image Copy Code
Function GetQuarter(TheDate)
   GetQuarter = DatePart("q", TheDate)
End Function

Expand image Requirements

Version 2

Expand image See Also

Reference

DateAdd Function
DateDiff Function


DateSerial Function

Visual Basic Scripting Edition
DateSerial Function
See Also
CollapseAll image DropDown image

Returns a Variant of subtype Date for a specified year, month, and day.

DateSerial(year, month, day)

Expand image Arguments

year

Number between 100 and 9999, inclusive, or a numeric expression.

month

Any numeric expression.

day

Any numeric expression.

Expand image 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, 1–31 for days and 1–12 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.

CopyCode image Copy Code
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 1900–1999. 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.

Expand image Requirements

Version 1

Expand image See Also

Reference

Date Function
DateValue Function
Day Function
Month Function
Now Function
TimeSerial Function
TimeValue Function
Weekday Function
Year Function


DateValue Function

Visual Basic Scripting Edition
DateValue Function
See Also
CollapseAll image DropDown image

Returns a Variant of subtype Date.

DateValue(date)

Expand image Remarks

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.

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#.

CopyCode image Copy Code
Dim MyDate
MyDate = DateValue("September 11, 1963")   ' Return a date.

Expand image Requirements

Version 1

Expand image See Also

Reference

CDate Function
DateSerial Function
Day Function
Month Function
Now Function
TimeSerial Function
TimeValue Function
Weekday Function
Year Function


Day Function

Visual Basic Scripting Edition
Day Function
See Also
CollapseAll image DropDown image

Returns a whole number between 1 and 31, inclusive, representing the day of the month.

Day(date)

Expand image Remarks

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:

CopyCode image Copy Code
Dim MyDay
MyDay = Day("October 19, 1962")   ' MyDay contains 19.

Expand image Requirements

Version 1

Expand image See Also

Reference

Date Function
Hour Function
Minute Function (VBScript)
Month Function
Now Function
Second Function
Weekday Function
Year Function


Derived Math Functions

Visual Basic Scripting Edition
Derived Math Functions
See Also
DropDown image

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

Functions

Function | Derived equivalents
Secant | Sec(X) = 1 / Cos(X)
Cosecant | Cosec(X) = 1 / Sin(X)
Cotangent | Cotan(X) = 1 / Tan(X)
Inverse Sine | Arcsin(X) = Atn(X / Sqr(-X * X + 1))
Inverse Cosine | Arccos(X) = Atn(-X / Sqr(-X * X + 1)) + 2 * Atn(1)
Inverse Secant | Arcsec(X) = Atn(X / Sqr(X * X - 1)) + Sgn((X) -1) * (2 * Atn(1))
Inverse Cosecant | Arccosec(X) = Atn(X / Sqr(X * X - 1)) + (Sgn(X) - 1) * (2 * Atn(1))
Inverse Cotangent | Arccotan(X) = Atn(X) + 2 * Atn(1)
Hyperbolic Sine | HSin(X) = (Exp(X) - Exp(-X)) / 2
Hyperbolic Cosine | HCos(X) = (Exp(X) + Exp(-X)) / 2
Hyperbolic Tangent | HTan(X) = (Exp(X) - Exp(-X)) / (Exp(X) + Exp(-X))
Hyperbolic Secant | HSec(X) = 2 / (Exp(X) + Exp(-X))
Hyperbolic Cosecant | HCosec(X) = 2 / (Exp(X) - Exp(-X))
Hyperbolic Cotangent | HCotan(X) = (Exp(X) + Exp(-X)) / (Exp(X) - Exp(-X))
Inverse Hyperbolic Sine | HArcsin(X) = Log(X + Sqr(X * X + 1))
Inverse Hyperbolic Cosine | HArccos(X) = Log(X + Sqr(X * X - 1))
Inverse Hyperbolic Tangent | HArctan(X) = Log((1 + X) / (1 - X)) / 2
Inverse Hyperbolic Secant | HArcsec(X) = Log((Sqr(-X * X + 1) + 1) / X)
Inverse Hyperbolic Cosecant | HArccosec(X) = Log((Sgn(X) * Sqr(X * X + 1) +1) / X)
Inverse Hyperbolic Cotangent | HArccotan(X) = Log((X + 1) / (X - 1)) / 2
Logarithm to base N | LogN(X) = Log(X) / Log(N)

See Also

Reference

Atn Function
Cos Function
Exp Function
Log Function
Sin Function
Sqr Function
Tan Function


Escape Function

Visual Basic Scripting Edition
Escape Function
See Also
CollapseAll image DropDown image

Encodes a string so it contains only ASCII characters.

Escape(charString)

Expand image Arguments

charString

Required. String expression to be encoded.

The Escape function returns a string (in Unicode format) that contains the contents of charString. All spaces, punctuation, accented characters, and other non-ASCII characters are replaced with %xx encoding, where xx is equivalent to the hexadecimal number representing the character. Unicode characters that have a value greater than 255 are stored using the %u xxxx format.

The string that the Escape function returns is suitable for transmission with many protocols, such as the HTTP protocol.

Note Note

Because the Escape function is not designed to create a valid uniform resource identifier (URI), it should not be used to encode URIs. The JScript encodeURI method may be used to encode URIs.

Expand image Requirements

Version 5

Expand image See Also

Reference

Unescape Function
encodeURI Method (JScript 5.6)


Eval Function

Visual Basic Scripting Edition
Eval Function
See Also
CollapseAll image DropDown image

Evaluates an expression and returns the result.

Eval(expression)

Expand image Arguments

expression

Required. String containing any legal VBScript expression.

Expand image 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, the result is True; if they are not, the result is False. The Eval method always uses the second interpretation, whereas the Execute statement always uses the first.

Note 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:

CopyCode image Copy Code
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

Expand image Requirements

Version 5

Expand image See Also

Reference

Execute Statement


Exp Function

Visual Basic Scripting Edition
Exp Function
See Also
CollapseAll image DropDown image

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

Exp(number)

Expand image Remarks

The number argument can be any valid numeric expression.

If the value of number exceeds 709.782712893, an error occurs. The constant e is approximately 2.718282.

Note 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:

CopyCode image Copy Code
Dim MyAngle, MyHSin   ' Define angle in radians.
MyAngle = 1.3   ' Calculate hyperbolic sine.
MyHSin = (Exp(MyAngle) - Exp(-1 * MyAngle)) / 2

Expand image Requirements

Version 1

Expand image See Also

Reference

Log Function

Concepts

Derived Math Functions


Filter Function

Visual Basic Scripting Edition
Filter Function
See Also
CollapseAll image DropDown image

Returns a zero-based array containing a subset of a string array based on a specified filter criteria.

Filter(InputStrings, Value[, Include[, Compare]])

Expand image 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.

Expand image Settings

The Compare argument can have the following values:

Constant | Value | Description
vbBinaryCompare | 0 | Perform a binary comparison.
vbTextCompare | 1 | Perform a textual comparison.

Expand image 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":

CopyCode image Copy Code
Dim MyIndex
Dim MyArray (3)
MyArray(0) = "Sunday"
MyArray(1) = "Monday"
MyArray(2) = "Tuesday"
MyIndex = Filter(MyArray, "Mon") ' MyIndex(0) contains "Monday".

Expand image Requirements

Version 2

Expand image See Also

Reference

Replace Function


FormatCurrency Function

Visual Basic Scripting Edition
FormatCurrency Function
See Also
CollapseAll image DropDown image

Returns an expression formatted as a currency value using the currency symbol defined in the system control panel.

FormatCurrency(Expression[,NumDigitsAfterDecimal [,IncludeLeadingDigit [,UseParensForNegativeNumbers [,GroupDigits]]]])

Expand image 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.

Expand image Settings

The IncludeLeadingDigit, UseParensForNegativeNumbers, and GroupDigits arguments have the following settings:

Constant | Value | Description
TristateTrue | -1 | True
TristateFalse | 0 | False
TristateUseDefault | -2 | Use the setting from the computer's regional settings.

Expand image 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 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:

CopyCode image Copy Code
Dim MyCurrency
MyCurrency = FormatCurrency(1000)   ' MyCurrency contains $1000.00.

Expand image Requirements

Version 2

Expand image See Also

Reference

FormatDateTime Function
FormatNumber Function
FormatPercent Function


FormatDateTime Function

Visual Basic Scripting Edition
FormatDateTime Function
See Also
CollapseAll image DropDown image

Returns an expression formatted as a date or time.

FormatDateTime(Date[, NamedFormat])

Expand image Arguments

Date

Required. Date expression to be formatted.

NamedFormat

Optional. Numeric value that indicates the date/time format used. If omitted, vbGeneralDate is used.

Expand image Settings

The NamedFormat argument has the following settings:

Constant | Value | Description
vbGeneralDate | 0 | 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.
vbLongDate | 1 | Display a date using the long date format specified in your computer's regional settings.
vbShortDate | 2 | Display a date using the short date format specified in your computer's regional settings.
vbLongTime | 3 | Display a time using the time format specified in your computer's regional settings.
vbShortTime | 4 | Display a time using the 24-hour format (hh:mm).

Expand image Remarks

The following example uses the FormatDateTime function to format the expression as a long date and assign it to MyDateTime:

CopyCode image Copy Code
Function GetCurrentDate
   ' FormatDateTime formats Date in long date.
   GetCurrentDate = FormatDateTime(Date, 1)
End Function

Expand image Requirements

Version 2

Expand image See Also

Reference

FormatCurrency Function
FormatNumber Function
FormatPercent Function


FormatNumber Function

Visual Basic Scripting Edition
FormatNumber Function
See Also
CollapseAll image DropDown image

Returns an expression formatted as a number.

FormatNumber(Expression [,NumDigitsAfterDecimal [,IncludeLeadingDigit [,UseParensForNegativeNumbers [,GroupDigits]]]])

Expand image 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.

Expand image Settings

The IncludeLeadingDigit, UseParensForNegativeNumbers, and GroupDigits arguments have the following settings:

Constant | Value | Description
TristateTrue | -1 | True
TristateFalse | 0 | False
TristateUseDefault | -2 | Use the setting from the computer's regional settings.

Expand image 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 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:

CopyCode image Copy Code
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

Expand image Requirements

Version 2

Expand image See Also

Reference

FormatCurrency Function
FormatDateTime Function
FormatPercent Function


FormatPercent Function

Visual Basic Scripting Edition
FormatPercent Function
See Also
CollapseAll image DropDown image

Returns an expression formatted as a percentage (multiplied by 100) with a trailing % character.

FormatPercent(Expression[,NumDigitsAfterDecimal [,IncludeLeadingDigit [,UseParensForNegativeNumbers [,GroupDigits]]]])

Expand image 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.

Expand image Settings

The IncludeLeadingDigit, UseParensForNegativeNumbers, and GroupDigits arguments have the following settings:

Constant | Value | Description
TristateTrue | -1 | True
TristateFalse | 0 | False
TristateUseDefault | -2 | Use the setting from the computer's regional settings.

Expand image Remarks

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

Note 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:

CopyCode image Copy Code
Dim MyPercent
MyPercent = FormatPercent(2/32) ' MyPercent contains 6.25%.

Expand image Requirements

Version 2

Expand image See Also

Reference

FormatCurrency Function
FormatDateTime Function
FormatNumber Function


GetLocale Function

Visual Basic Scripting Edition
GetLocale Function
See Also
CollapseAll image DropDown image

Returns the current locale ID value.

GetLocale()

Expand image 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.

CopyCode image Copy Code
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>

Expand image See Also

Reference

SetLocale Function

Concepts

Locale ID (LCID) Chart


GetObject Function

Visual Basic Scripting Edition
GetObject Function
See Also
CollapseAll image DropDown image

Returns a reference to an Automation object from a file.

GetObject([pathname] [, class])

Expand image 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:

Expand image Arguments

appname

Required; String. Name of the application providing the object.

objectype

Required; String. Type or class of object to create.

Expand image 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:

CopyCode image Copy Code
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:

CopyCode image Copy Code
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:

CopyCode image Copy Code
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:

CopyCode image Copy Code
MyObject.Line 9, 90
MyObject.InsertText 9, 100, "Hello, world."
MyObject.SaveAs "C:\DRAWINGS\SAMPLE.DRW"
Note 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.

Expand image Requirements

Version 5

Expand image See Also

Reference

CreateObject Function


GetRef Function

Visual Basic Scripting Edition
GetRef Function
See Also
CollapseAll image DropDown image

Returns a reference to a procedure that can be bound to an event.

Set object.eventname = GetRef(procname)

Expand image 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.

Expand image 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.

CopyCode image Copy Code
<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>

Expand image Requirements

Version 5

Expand image See Also

Reference

Function Statement (VBScript)
Set Statement
Sub Statement


Hex Function

Visual Basic Scripting Edition
Hex Function
See Also
CollapseAll image DropDown image

Returns a string representing the hexadecimal value of a number.

Hex(number)

Expand image Remarks

The number argument is any valid expression.

If number is not already a whole number, it is rounded to the nearest whole number before being evaluated.

If number is | Hex returns
Null | Null.
Empty | Zero (0).
Any other number | 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:

CopyCode image Copy Code
Dim MyHex
MyHex = Hex(5)   ' Returns 5.
MyHex = Hex(10)   ' Returns A.
MyHex = Hex(459)   ' Returns 1CB.

Expand image Requirements

Version 1

Expand image See Also

Reference

Oct Function (VBScript)


Hour Function

Visual Basic Scripting Edition
Hour Function
See Also
CollapseAll image DropDown image

Returns a whole number between 0 and 23, inclusive, representing the hour of the day.

Hour(time)

Expand image Remarks

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:

CopyCode image Copy Code
Dim MyTime, MyHour
MyTime = Now
MyHour = Hour(MyTime) ' MyHour contains the number representing
                      ' the current hour.

Expand image Requirements

Version 1

Expand image See Also

Reference

Day Function
Minute Function (VBScript)
Now Function
Second Function
Time Function


InputBox Function

Visual Basic Scripting Edition
InputBox Function
See Also
CollapseAll image DropDown image

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])

Expand image 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 return–linefeed 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.

Expand image 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:

CopyCode image Copy Code
Dim Input
Input = InputBox("Enter your name")
MsgBox ("You entered: " & Input)

Expand image Requirements

Version 1

Expand image See Also

Reference

MsgBox Function


InStr Function

Visual Basic Scripting Edition
InStr Function
See Also
CollapseAll image DropDown image

Returns the position of the first occurrence of one string within another.

InStr([start, ]string1, string2[, compare])

Expand image 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.

Expand image Settings

The compare argument can have the following values:

Constant | Value | Description
vbBinaryCompare | 0 | Perform a binary comparison.
vbTextCompare | 1 | Perform a textual comparison.

Expand image Return Value

The InStr function returns the following values:

If | InStr returns
string1 is zero-length | 0
string1 is Null | Null
string2 is zero-length | start
string2 is Null | Null
string2 is not found | 0
string2 is found within string1 | Position at which match is found
start > Len(string2) | 0

Expand image Remarks

The following examples use InStr to search a string:

CopyCode image Copy Code
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 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.

Expand image Requirements

Version 1

Expand image See Also

Reference

InStrRev Function


InStrRev Function

Visual Basic Scripting Edition
InStrRev Function
See Also
CollapseAll image DropDown image

Returns the position of an occurrence of one string within another, from the end of string.

InStrRev(string1, string2[, start[, compare]])

Expand image 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.

Expand image Settings

The compare argument can have the following values:

Constant | Value | Description
vbBinaryCompare | 0 | Perform a binary comparison.
vbTextCompare | 1 | Perform a textual comparison.

Expand image Return Value

InStrRev returns the following values:

If | InStrRev returns
string1 is zero-length | 0
string1 is Null | Null
string2 is zero-length | start
string2 is Null | Null
string2 is not found | 0
string2 is found within string1 | Position at which match is found
start > Len(string2) | 0

Expand image Remarks

The following examples use the InStrRev function to search a string:

CopyCode image Copy Code
Dim SearchString, SearchChar, MyPos
SearchString ="XXpXXpXXPXXP"   ' String to search in.
SearchChar = "P"   ' Search for "P".
MyPos = InstrRev(SearchString, SearchChar, 10, 0)   ' A binary comparison starting at position 10. Returns 9.
MyPos = InstrRev(SearchString, SearchChar, -1, 1)   ' A textual comparison starting at the last position. Returns 12.
MyPos = InstrRev(SearchString, SearchChar, 8)   ' Comparison is binary by default (last argument is omitted). Returns 0.
Note Note

The syntax for the InStrRev function is not the same as the syntax for the InStr function.

Expand image Requirements

Version 2

Expand image See Also

Reference

InStr Function


Int, Fix Functions

Visual Basic Scripting Edition
Int, Fix Functions
See Also
CollapseAll image DropDown image

Returns the integer portion of a number.

Int(number)
Fix(number)

Expand image Remarks

The number argument can be any valid numeric expression. If number contains Null, Null is returned.

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:

CopyCode image Copy Code
Sgn(number) * Int(Abs(number))

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

CopyCode image Copy Code
MyNumber = Int(99.8)    ' Returns 99.
MyNumber = Fix(99.2)    ' Returns 99.
MyNumber = Int(-99.8)   ' Returns -100.
MyNumber = Fix(-99.8)   ' Returns -99.
MyNumber = Int(-99.2)   ' Returns -100.
MyNumber = Fix(-99.2)   ' Returns -99.

Expand image Requirements

Version 1

Expand image See Also

Reference

CInt Function
Round Function


IsArray Function

Visual Basic Scripting Edition
IsArray Function
See Also
CollapseAll image DropDown image

Returns a Boolean value indicating whether a variable is an array.

IsArray(varname)

Expand image Remarks

The varname argument can be any variable.

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:

CopyCode image Copy Code
Dim MyVariable
Dim MyArray(3)
MyArray(0) = "Sunday"
MyArray(1) = "Monday"
MyArray(2) = "Tuesday"
MyVariable = IsArray(MyArray) ' MyVariable contains "True".

Expand image Requirements

Version 1

Expand image See Also

Reference

IsDate Function
IsEmpty Function
IsNull Function
IsNumeric Function
IsObject Function
VarType Function
Dim Statement
ReDim Statement
Array Function
LBound Function
UBound Function
Private Statement
Public Statement
Erase Statement


IsDate Function

Visual Basic Scripting Edition
IsDate Function
See Also
CollapseAll image DropDown image

Returns a Boolean value indicating whether an expression can be converted to a date.

IsDate(expression)

Expand image Remarks

The expression argument can be any date expression or string expression recognizable as a date or time.

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:

CopyCode image Copy Code
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.

Expand image Requirements

Version 1

Expand image See Also

Reference

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


IsEmpty Function

Visual Basic Scripting Edition
IsEmpty Function
See Also
CollapseAll image DropDown image

Returns a Boolean value indicating whether a variable has been initialized.

IsEmpty(expression)

Expand image Remarks

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.

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:

CopyCode image Copy Code
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.

Expand image Requirements

Version 1

Expand image See Also

Reference

IsArray Function
IsDate Function
IsNull Function
IsNumeric Function
IsObject Function
VarType Function


IsNull Function

Visual Basic Scripting Edition
IsNull Function
See Also
CollapseAll image DropDown image

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

IsNull(expression)

Expand image Remarks

The expression argument can be any expression.

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 note 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:

CopyCode image Copy Code
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.

Expand image Requirements

Version 1

Expand image See Also

Reference

IsArray Function
IsDate Function
IsEmpty Function
IsNumeric Function
IsObject Function
VarType Function


IsNumeric Function

Visual Basic Scripting Edition
IsNumeric Function
See Also
CollapseAll image DropDown image

Returns a Boolean value indicating whether an expression can be evaluated as a number.

IsNumeric(expression)

Expand image Remarks

The expression argument can be any expression.

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:

CopyCode image Copy Code
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.

Expand image Requirements

Version 1

Expand image See Also

Reference

IsArray Function
IsDate Function
IsEmpty Function
IsNull Function
IsObject Function
VarType Function


IsObject Function

Visual Basic Scripting Edition
IsObject Function
See Also
CollapseAll image DropDown image

Returns a Boolean value indicating whether an expression references a valid Automation object.

IsObject(expression)

Expand image Remarks

The expression argument can be any expression.

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:

CopyCode image Copy Code
Dim MyInt, MyCheck, MyObject
Set MyObject = Me
MyCheck = IsObject(MyObject)   ' Returns True.
MyCheck = IsObject(MyInt)   ' Returns False.

Expand image Requirements

Version 1

Expand image See Also

Reference

IsArray Function
IsDate Function
IsEmpty Function
IsNull Function
IsNumeric Function
Set Statement
VarType Function


Join Function

Visual Basic Scripting Edition
Join Function
See Also
CollapseAll image DropDown image

Returns a string created by joining a number of substrings contained in an array.

Join(list[, delimiter])

Expand image 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.

Expand image Remarks

The following example uses the Join function to join the substrings of MyArray:

CopyCode image Copy Code
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".

Expand image Requirements

Version 2

Expand image See Also

Reference

Split Function


LBound Function

Visual Basic Scripting Edition
LBound Function
See Also
CollapseAll image DropDown image

Returns the smallest available subscript for the indicated dimension of an array.

LBound(arrayname[, dimension])

Expand image 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.

Expand image 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.

Expand image Requirements

Version 1

Expand image See Also

Reference

Dim Statement
ReDim Statement
UBound Function
IsArray Function
Array Function
Lbound Function
Private Statement
Public Statement
Erase Statement


LCase Function

Visual Basic Scripting Edition
LCase Function
See Also
CollapseAll image DropDown image

Returns a string that has been converted to lowercase.

LCase(string)

Expand image Remarks

The string argument is any valid string expression. If string contains Null, Null is returned.

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:

CopyCode image Copy Code
Dim MyString
Dim LCaseString
MyString = "VBSCript"
LCaseString = LCase(MyString)   ' LCaseString contains "vbscript".

Expand image Requirements

Version 1

Expand image See Also

Reference

UCase Function


Left Function

Visual Basic Scripting Edition
Left Function
See Also
CollapseAll image DropDown image

Returns a specified number of characters from the left side of a string.

Left(string, length)

Expand image 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.

Expand image 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:

CopyCode image Copy Code
Dim MyString, LeftString
MyString = "VBSCript"
LeftString = Left(MyString, 3) ' LeftString contains "VBS".
Note 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.

Expand image Requirements

Version 1

Expand image See Also

Reference

Len Function
Mid Function
Right Function


Len Function

Visual Basic Scripting Edition
Len Function
See Also
CollapseAll image DropDown image

Returns the number of characters in a string or the number of bytes required to store a variable.

Len(string | varname)

Expand image 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.

Expand image Remarks

The following example uses the Len function to return the number of characters in a string:

CopyCode image Copy Code
Dim MyString
MyString = Len("VBSCRIPT") ' MyString contains 8.
Note 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.

Expand image Requirements

Version 1

Expand image See Also

Reference

InStr Function


LoadPicture Function

Visual Basic Scripting Edition
LoadPicture Function
CollapseAll image DropDown image

Returns a picture object. Available only on 32-bit platforms.

LoadPicture(picturename)

Expand image Remarks

The picturename argument is a string expression that indicates the name of the picture file to be loaded.

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.

Expand image Requirements

Version 2


Log Function

Visual Basic Scripting Edition
Log Function
See Also
CollapseAll image DropDown image

Returns the natural logarithm of a number.

Log(number)

Expand image Remarks

The number argument can be any valid numeric expression greater than 0.

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:

CopyCode image Copy Code
Logn(x) = Log(x) / Log(n)

The following example illustrates a custom Function that calculates base-10 logarithms:

CopyCode image Copy Code
Function Log10(X)
   Log10 = Log(X) / Log(10)
End Function

Expand image Requirements

Version 1

Expand image See Also

Reference

Exp Function

Concepts

Derived Math Functions


LTrim; RTrim; and Trim Functions

Visual Basic Scripting Edition
LTrim; RTrim; and Trim Functions
See Also
CollapseAll image DropDown image

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)

Expand image Remarks

The string argument is any valid string expression. If string contains Null, Null is returned.

The following example uses the LTrim, RTrim, and Trim functions to trim leading spaces, trailing spaces, and both leading and trailing spaces, respectively:

CopyCode image Copy Code
Dim MyVar
MyVar = LTrim("   vbscript ")   ' MyVar contains "vbscript ".
MyVar = RTrim("   vbscript ")   ' MyVar contains "   vbscript".
MyVar = Trim("   vbscript ")   ' MyVar contains "vbscript".

Expand image Requirements

Version 1

Expand image See Also

Reference

Left Function
Right Function


Math Functions

Visual Basic Scripting Edition
Math Functions
DropDown image

The following table lists the VBScript math functions.

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 |


Mid Function

Visual Basic Scripting Edition
Mid Function
See Also
CollapseAll image DropDown image

Returns a specified number of characters from a string.

Mid(string, start[, length])

Expand image 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.

Expand image 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("VBScript is fun!", 3, 6) ' MyVar contains "Script".

Note 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.

Expand image Requirements

Version 1

Expand image See Also

Reference

Left Function
Len Function
LTrim; RTrim; and Trim Functions
Right Function


Minute Function (VBScript)

Visual Basic Scripting Edition
Minute Function (VBScript)
See Also
CollapseAll image DropDown image

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

Minute(time)

Expand image Remarks

The time argument is any expression that can represent a time. If time contains Null, Null is returned.

The following example uses the Minute function to return the minute of the hour:

CopyCode image Copy Code
Dim MyVar
MyVar = Minute(Now)

Expand image Requirements

Version 1

Expand image See Also

Reference

Day Function
Hour Function
Now Function
Second Function
Time Function


Month Function

Visual Basic Scripting Edition
Month Function
See Also
CollapseAll image DropDown image

Returns a whole number between 1 and 12, inclusive, representing the month of the year.

Month(date)

Expand image Remarks

The date argument is any expression that can represent a date. If date contains Null, Null is returned.

The following example uses the Month function to return the current month:

CopyCode image Copy Code
Dim MyVar
MyVar = Month(Now) ' MyVar contains the number corresponding to
                   ' the current month.

Expand image Requirements

Version 1

Expand image See Also

Reference

Date Function
Day Function
Now Function
Weekday Function
Year Function


MonthName Function

Visual Basic Scripting Edition
MonthName Function
See Also
CollapseAll image DropDown image

Returns a string indicating the specified month.

MonthName(month[, abbreviate])

Expand image 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.

Expand image Remarks

The following example uses the MonthName function to return an abbreviated month name for a date expression:

CopyCode image Copy Code
Dim MyVar
MyVar = MonthName(10, True) ' MyVar contains "Oct".

Expand image Requirements

Version 2

Expand image See Also

Reference

WeekdayName Function


MsgBox Function

Visual Basic Scripting Edition
MsgBox Function
See Also
CollapseAll image DropDown image

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])

Expand image 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 return–linefeed 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.

Expand image Settings

The buttons argument settings are:

Constant | Value | Description
vbOKOnly | 0 | Display OK button only.
vbOKCancel | 1 | Display OK and Cancel buttons.
vbAbortRetryIgnore | 2 | Display Abort, Retry, and Ignore buttons.
vbYesNoCancel | 3 | Display Yes, No, and Cancel buttons.
vbYesNo | 4 | Display Yes and No buttons.
vbRetryCancel | 5 | Display Retry and Cancel buttons.
vbCritical | 16 | Display Critical Message icon.
vbQuestion | 32 | Display Warning Query icon.
vbExclamation | 48 | Display Warning Message icon.
vbInformation | 64 | Display Information Message icon.
vbDefaultButton1 | 0 | First button is default.
vbDefaultButton2 | 256 | Second button is default.
vbDefaultButton3 | 512 | Third button is default.
vbDefaultButton4 | 768 | Fourth button is default.
vbApplicationModal | 0 | Application modal; the user must respond to the message box before continuing work in the current application.
vbSystemModal | 4096 | System modal; all applications are suspended until the user responds to the message box.

The first group of values (0–5) 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.

Expand image Return Value

The MsgBox function has the following return values:

Constant | Value | Button
vbOK | 1 | OK
vbCancel | 2 | Cancel
vbAbort | 3 | Abort
vbRetry | 4 | Retry
vbIgnore | 5 | Ignore
vbYes | 6 | Yes
vbNo | 7 | No

Expand image 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:

CopyCode image Copy Code
Dim MyVar
MyVar = MsgBox ("Hello World!", 65, "MsgBox Example")
   ' MyVar contains either 1 or 2, depending on which button is clicked.

Expand image Requirements

Version 1

Expand image See Also

Reference

InputBox Function


Now Function

Visual Basic Scripting Edition
Now Function
See Also
CollapseAll image DropDown image

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

Now

Expand image Remarks

The following example uses the Now function to return the current date and time:

CopyCode image Copy Code
Dim MyVar
MyVar = Now ' MyVar contains the current date and time.

Expand image Requirements

Version 1

Expand image See Also

Reference

Date Function
Day Function
Hour Function
Minute Function (VBScript)
Month Function
Second Function
Time Function
Weekday Function
Year Function


Oct Function (VBScript)

Visual Basic Scripting Edition
Oct Function (VBScript)
See Also
CollapseAll image DropDown image

Returns a string representing the octal value of a number.

Oct(number)

Expand image Remarks

The number argument is any valid expression.

If number is not already a whole number, it is rounded to the nearest whole number before being evaluated.

If number is | Oct returns
Null | Null.
Empty | Zero (0).
Any other number | 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:

CopyCode image Copy Code
Dim MyOct
MyOct = Oct(4)     ' Returns 4.
MyOct = Oct(8)     ' Returns 10.
MyOct = Oct(459)   ' Returns 713.

Expand image Requirements

Version 1

Expand image See Also

Reference

Hex Function


Replace Function

Visual Basic Scripting Edition
Replace Function
See Also
CollapseAll image DropDown image

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]]])

Expand image 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.

Expand image Settings

The compare argument can have the following values:

Constant | Value | Description
vbBinaryCompare | 0 | Perform a binary comparison.
vbTextCompare | 1 | Perform a textual comparison.

Expand image Return Value

Replace returns the following values:

If | Replace returns
expression is zero-length | Zero-length string ("").
expression is Null | An error.
find is zero-length | Copy of expression.
replacewith is zero-length | Copy of expression with all occurrences of find removed.
start > Len(expression) | Zero-length string.
count is 0 | Copy of expression.

Expand image Remarks

The return value of the Replace function is a string, with substitutions made, that begins at the position specified by start 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:

CopyCode image Copy Code
Dim MyString
' A binary comparison starting at the beginning of the string.
MyString = Replace("XXpXXPXXp", "p", "Y")
' Returns "XXYXXPXXY".

' A textual comparison starting at position 3.
MyString = Replace("XXpXXPXXp", "p", "Y", 3, -1, 1)
' Returns "YXXYXXY".

Expand image Requirements

Version 2

Expand image See Also

Reference

Filter Function


RGB Function

Visual Basic Scripting Edition
RGB Function
CollapseAll image DropDown image

Returns a whole number representing an RGB color value.

RGB(red, green, blue)

Expand image 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.

Expand image 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:

CopyCode image Copy Code
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.

Expand image Requirements

Version 2


Right Function

Visual Basic Scripting Edition
Right Function
See Also
CollapseAll image DropDown image

Returns a specified number of characters from the right side of a string.

Right(string, length)

Expand image 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.

Expand image 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:

CopyCode image Copy Code
Dim AnyString, MyStr
AnyString = "Hello World"      ' Define string.
MyStr = Right(AnyString, 1)    ' Returns "d".
MyStr = Right(AnyString, 6)    ' Returns " World".
MyStr = Right(AnyString, 20)   ' Returns "Hello World".
Note 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.

Expand image Requirements

Version 1

Expand image See Also

Reference

Left Function
Len Function
Mid Function


Rnd Function

Visual Basic Scripting Edition
Rnd Function
See Also
CollapseAll image DropDown image

Returns a random number.

Rnd[(number)]

Expand image Remarks

The number argument can be any valid numeric expression.

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 | Rnd generates
Less than zero | The same number every time, using number as the seed.
Greater than zero | The next random number in the sequence.
Equal to zero | The most recently generated number.
Not supplied | 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:

CopyCode image Copy Code
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 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.

Expand image Requirements

Version 1

Expand image See Also

Reference

Randomize Statement


Round Function

Visual Basic Scripting Edition
Round Function
See Also Example
CollapseAll image DropDown image

Returns a number rounded to a specified number of decimal places.

Round(expression[, numdecimalplaces])

Expand image 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.

Expand image Remarks

The Round function performs round to even, which is different from round to larger. The return value is the number closest to the value of expression, with the appropriate number of decimal places. If expression is exactly halfway between two possible rounded values, the function returns the possible rounded value whose rightmost digit is an even number. (In a round to larger function, a number that is halfway between two possible rounded values is always rounded to the larger number.)

Note Note

Round to even is a statistically more accurate rounding algorithm than round to larger.

Expand image Example

The following example uses the Round function to round a number to two decimal places:

CopyCode image Copy Code
Dim MyVar, pi
pi = 3.14159
MyVar = Round(pi, 2) ' MyVar contains 3.14.

This example demonstrates how rounding to even works:

CopyCode image Copy Code
Dim var1, var2, var3, var4, var5
var1 = Round(1.5)      ' var1 contains 2
var2 = Round(2.5)      ' var2 contains 2
var3 = Round(3.5)      ' var3 contains 4
var4 = Round(0.985, 2) ' var4 contains 0.98
var5 = Round(0.995, 2) ' var5 contains 1.00

Expand image Requirements

Version 2

Expand image See Also

Reference

Int, Fix Functions


ScriptEngine Function

Visual Basic Scripting Edition
ScriptEngine Function
See Also
CollapseAll image DropDown image

Returns a string representing the scripting language in use.

ScriptEngine

Expand image Return Value

The ScriptEngine function can return any of the following strings:

String | Description
VBScript | Indicates that Microsoft® Visual Basic® Scripting Edition is the current scripting engine.
JScript | Indicates that Microsoft JScript® is the current scripting engine.
VBA | Indicates that Microsoft Visual Basic for Applications is the current scripting engine.

Expand image Remarks

The following example uses the ScriptEngine function to return a string describing the scripting language in use:

CopyCode image Copy Code
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

Expand image Requirements

Version 2

Expand image See Also

Reference

ScriptEngineBuildVersion Function
ScriptEngineMajorVersion Function
ScriptEngineMinorVersion Function


ScriptEngineBuildVersion Function

Visual Basic Scripting Edition
ScriptEngineBuildVersion Function
See Also
CollapseAll image DropDown image

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

ScriptEngineBuildVersion

Expand image 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:

CopyCode image Copy Code
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

Expand image Requirements

Version 2

Expand image See Also

Reference

ScriptEngine Function
ScriptEngineMajorVersion Function
ScriptEngineMinorVersion Function


ScriptEngineMajorVersion Function

Visual Basic Scripting Edition
ScriptEngineMajorVersion Function
See Also
CollapseAll image DropDown image

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

ScriptEngineMajorVersion

Expand image 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:

CopyCode image Copy Code
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

Expand image Requirements

Version 2

Expand image See Also

Reference

ScriptEngine Function
ScriptEngineBuildVersion Function
ScriptEngineMinorVersion Function


ScriptEngineMinorVersion Function

Visual Basic Scripting Edition
ScriptEngineMinorVersion Function
See Also
CollapseAll image DropDown image

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

ScriptEngineMinorVersion

Expand image 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:

CopyCode image Copy Code
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

Expand image Requirements

Version 2

Expand image See Also

Reference

ScriptEngine Function
ScriptEngineBuildVersion Function
ScriptEngineMajorVersion Function


Second Function

Visual Basic Scripting Edition
Second Function
See Also
CollapseAll image DropDown image

Returns a whole number between 0 and 59, inclusive, representing the second of the minute.

Second(time)

Expand image Remarks

The time argument is any expression that can represent a time. If time contains Null, Null is returned.

The following example uses the Second function to return the current second:

CopyCode image Copy Code
Dim MySec
MySec = Second(Now)
   ' MySec contains the number representing the current second.

Expand image Requirements

Version 1

Expand image See Also

Reference

Day Function
Hour Function
Minute Function (VBScript)
Now Function
Time Function


SetLocale Function

Visual Basic Scripting Edition
SetLocale Function
See Also
CollapseAll image DropDown image

Sets the global locale and returns the previous locale.

SetLocale(lcid)

Expand image Remarks

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.

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.

CopyCode image Copy Code
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>

Expand image See Also

Reference

GetLocale Function

Concepts

Locale ID (LCID) Chart


Sgn Function

Visual Basic Scripting Edition
Sgn Function
See Also
CollapseAll image DropDown image

Returns an integer indicating the sign of a number.

Sgn(number)

Expand image Arguments

The number argument can be any valid numeric expression.

Expand image Return Value

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

Expand image 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:

CopyCode image Copy Code
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.

Expand image Requirements

Version 1

Expand image See Also

Reference

Abs Function


Sin Function

Visual Basic Scripting Edition
Sin Function
See Also
CollapseAll image DropDown image

Returns the sine of an angle.

Sin(number)

Expand image Remarks

The number argument can be any valid numeric expression that expresses an angle in radians.

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:

CopyCode image Copy Code
Dim MyAngle, MyCosecant
MyAngle = 1.3   ' Define angle in radians.
MyCosecant = 1 / Sin(MyAngle)   ' Calculate cosecant.

Expand image Requirements

Version 1

Expand image See Also

Reference

Atn Function
Cos Function
Tan Function

Concepts

Derived Math Functions


Space Function

Visual Basic Scripting Edition
Space Function
See Also
CollapseAll image DropDown image

Returns a string consisting of the specified number of spaces.

Space(number)

Expand image Remarks

The number argument is the number of spaces you want in the string.

The following example uses the Space function to return a string consisting of a specified number of spaces:

CopyCode image Copy Code
Dim MyString
MyString = Space(10)   ' Returns a string with 10 spaces.
MyString = "Hello" & Space(10) & "World" ' Insert 10 spaces between two strings.

Expand image Requirements

Version 1

Expand image See Also

Reference

String Function


Split Function

Visual Basic Scripting Edition
Split Function
See Also
CollapseAll image DropDown image

Returns a zero-based, one-dimensional array containing a specified number of substrings.

Split(expression[, delimiter[, count[, compare]]])

Expand image 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.

Expand image Settings

The compare argument can have the following values:

Constant | Value | Description
vbBinaryCompare | 0 | Perform a binary comparison.
vbTextCompare | 1 | Perform a textual comparison.

Expand image 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.

CopyCode image Copy Code
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

Expand image Requirements

Version 2

Expand image See Also

Reference

Join Function


Sqr Function

Visual Basic Scripting Edition
Sqr Function
CollapseAll image DropDown image

Returns the square root of a number.

Sqr(number)

Expand image Remarks

The number argument can be any valid numeric expression greater than or equal to 0.

The following example uses the Sqr function to calculate the square root of a number:

CopyCode image Copy Code
Dim MySqr
MySqr = Sqr(4)   ' Returns 2.
MySqr = Sqr(23)   ' Returns 4.79583152331272.
MySqr = Sqr(0)   ' Returns 0.
MySqr = Sqr(-4)   ' Generates a run-time error.

Expand image Requirements

Version 1


StrComp Function

Visual Basic Scripting Edition
StrComp Function
CollapseAll image DropDown image

Returns a value indicating the result of a string comparison.

StrComp(string1, string2[, compare])

Expand image 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.

Expand image Settings

The compare argument can have the following values:

Constant | Value | Description
vbBinaryCompare | 0 | Perform a binary comparison.
vbTextCompare | 1 | Perform a textual comparison.

Expand image Return Value

The StrComp function has the following return values:

If | StrComp returns
string1 is less than string2 | -1
string1 is equal to string2 | 0
string1 is greater than string2 | 1
string1 or string2 is Null | Null

Expand image 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.

CopyCode image Copy Code
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.

Expand image Requirements

Version 1


String Function

Visual Basic Scripting Edition
String Function
See Also
CollapseAll image DropDown image

Returns a repeating character string of the length specified.

String(number, character)

Expand image 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.

Expand image Remarks

If you specify a number for character greater than 255, String converts the number to a valid character code using the formula:

CopyCode image Copy Code
character Mod 256

The following example uses the String function to return repeating character strings of the length specified:

CopyCode image Copy Code
Dim MyString
MyString = String(5, "*")   ' Returns "*****".
MyString = String(5, 42)   ' Returns "*****".
MyString = String(10, "ABC")   ' Returns "AAAAAAAAAA".

Expand image Requirements

Version 1

Expand image See Also

Reference

Space Function


StrReverse Function

Visual Basic Scripting Edition
StrReverse Function
CollapseAll image DropDown image

Returns a string in which the character order of a specified string is reversed.

StrReverse(string1)

Expand image Remarks

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.

The following example uses the StrReverse function to return a string in reverse order:

CopyCode image Copy Code
Dim MyStr
MyStr = StrReverse("VBScript") ' MyStr contains "tpircSBV".

Expand image Requirements

Version 2


Tan Function

Visual Basic Scripting Edition
Tan Function
See Also
CollapseAll image DropDown image

Returns the tangent of an angle.

Tan(number)

Expand image Remarks

The number argument can be any valid numeric expression that expresses an angle in radians.

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:

CopyCode image Copy Code
Dim MyAngle, MyCotangent
MyAngle = 1.3   ' Define angle in radians.
MyCotangent = 1 / Tan(MyAngle)   ' Calculate cotangent.

Expand image Requirements

Version 1

Expand image See Also

Reference

Atn Function
Cos Function
Sin Function

Concepts

Derived Math Functions


Time Function

Visual Basic Scripting Edition
Time Function
See Also
CollapseAll image DropDown image

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

Time

Expand image Remarks

The following example uses the Time function to return the current system time:

CopyCode image Copy Code
Dim MyTime
MyTime = Time   ' Return current system time.

Expand image Requirements

Version 1

Expand image See Also

Reference

Date Function


Timer Function

Visual Basic Scripting Edition
Timer Function
See Also
CollapseAll image DropDown image

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

Timer

Expand image Remarks

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

CopyCode image Copy Code
Function TimeIt(N)
   Dim StartTime, EndTime
   StartTime = Timer
   For I = 1 To N
   Next
   EndTime = Timer
   TimeIt = EndTime - StartTime
End Function

Expand image Requirements

Version 5

Expand image See Also

Reference

Randomize Statement


TimeSerial Function

Visual Basic Scripting Edition
TimeSerial Function
See Also
CollapseAll image DropDown image

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

TimeSerial(hour, minute, second)

Expand image 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.

Expand image 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, 0–23 for hours and 0–59 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.

CopyCode image Copy Code
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.

Expand image Requirements

Version 1

Expand image See Also

Reference

DateSerial Function
DateValue Function
Hour Function
Minute Function (VBScript)
Now Function
Second Function
TimeValue Function


TimeValue Function

Visual Basic Scripting Edition
TimeValue Function
See Also
CollapseAll image DropDown image

Returns a Variant of subtype Date containing the time.

TimeValue(time)

Expand image Remarks

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.

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#).

CopyCode image Copy Code
Dim MyTime
MyTime = TimeValue("4:35:17 PM")   ' MyTime contains 4:35:17 PM.

Expand image Requirements

Version 1

Expand image See Also

Reference

DateSerial Function
DateValue Function
Hour Function
Minute Function (VBScript)
Now Function
Second Function
TimeSerial Function


TypeName Function

Visual Basic Scripting Edition
TypeName Function
See Also
CollapseAll image DropDown image

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

TypeName(varname)

Expand image Arguments

The required varname argument can be any variable.

Expand image Return Value

The TypeName function has the following return values:

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

Expand image Remarks

The following example uses the TypeName function to return information about a variable:

CopyCode image Copy Code
Dim ArrayVar(4), MyType
NullVar = Null   ' Assign Null value.

MyType = TypeName("VBScript")   ' Returns "String".
MyType = TypeName(4)            ' Returns "Integer".
MyType = TypeName(37.50)        ' Returns "Double".
MyType = TypeName(NullVar)      ' Returns "Null".
MyType = TypeName(ArrayVar)     ' Returns "Variant()".

Expand image Requirements

Version 2

Expand image See Also

Reference

IsArray Function
IsDate Function
IsEmpty Function
IsNull Function
IsNumeric Function
IsObject Function
VarType Function


UBound Function

Visual Basic Scripting Edition
UBound Function
See Also
CollapseAll image DropDown image

Returns the largest available subscript for the indicated dimension of an array.

UBound(arrayname[, dimension])

Expand image 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.

Expand image 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:

CopyCode image Copy Code
Dim A(100,3,4)
Statement | Return Value
UBound(A, 1) | 100
UBound(A, 2) | 3
UBound(A, 3) | 4

Expand image Requirements

Version 1

Expand image See Also

Reference

Dim Statement
LBound Function
ReDim Statement
Array Function
IsArray Function
Private Statement
Public Statement
Erase Statement


UCase Function

Visual Basic Scripting Edition
UCase Function
See Also
CollapseAll image DropDown image

Returns a string that has been converted to uppercase.

UCase(string)

Expand image Remarks

The string argument is any valid string expression. If string contains Null, Null is returned.

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:

CopyCode image Copy Code
Dim MyWord
MyWord = UCase("Hello World")   ' Returns "HELLO WORLD".

Expand image Requirements

Version 1

Expand image See Also

Reference

LCase Function


Unescape Function

Visual Basic Scripting Edition
Unescape Function
See Also
CollapseAll image DropDown image

Decodes a string encoded with the Escape function.

Unescape(charString)

Expand image Arguments

charString

Required. String expression to be decoded.

Expand image Remarks

The Unescape function returns a string (in Unicode format) that contains the contents of charString. ASCII character set equivalents replace all characters encoded with the %xx hexadecimal form. Characters encoded in %u xxxx format (Unicode characters) are replaced with the Unicode character with hexadecimal encoding xxxx.

Expand image Requirements

Version 5

Expand image See Also

Reference

Escape Function


VarType Function

Visual Basic Scripting Edition
VarType Function
See Also
CollapseAll image DropDown image

Returns a value indicating the subtype of a variable.

VarType(varname)

Expand image Arguments

The varname argument can be any variable.

Expand image Return Value

The VarType function returns the following values:

Constant | Value | Description
vbEmpty | 0 | Empty (uninitialized)
vbNull | 1 | Null (no valid data)
vbInteger | 2 | Integer
vbLong | 3 | Long integer
vbSingle | 4 | Single-precision floating-point number
vbDouble | 5 | Double-precision floating-point number
vbCurrency | 6 | Currency
vbDate | 7 | Date
vbString | 8 | String
vbObject | 9 | Automation object
vbError | 10 | Error
vbBoolean | 11 | Boolean
vbVariant | 12 | Variant (used only with arrays of Variants)
vbDataObject | 13 | A data-access object
vbByte | 17 | Byte
vbArray | 8192 | Array
Note 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.

Expand image 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.

CopyCode image Copy Code
Dim MyCheck
MyCheck = VarType(300)          ' Returns 2.
MyCheck = VarType(#10/19/62#)   ' Returns 7.
MyCheck = VarType("VBScript")   ' Returns 8.

Expand image Requirements

Version 1

Expand image See Also

Reference

IsArray Function
IsDate Function
IsEmpty Function
IsNull Function
IsNumeric Function
IsObject Function
TypeName Function


Weekday Function

Visual Basic Scripting Edition
Weekday Function
See Also
CollapseAll image DropDown image

Returns a whole number representing the day of the week.

Weekday(date, [firstdayofweek])

Expand image 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.

Expand image Settings

The firstdayofweek argument has these settings:

Constant | Value | Description
vbUseSystemDayOfWeek | 0 | Use National Language Support (NLS) API setting.
vbSunday | 1 | Sunday
vbMonday | 2 | Monday
vbTuesday | 3 | Tuesday
vbWednesday | 4 | Wednesday
vbThursday | 5 | Thursday
vbFriday | 6 | Friday
vbSaturday | 7 | Saturday

Expand image Return Value

The Weekday function can return any of these values:

Constant | Value | Description
vbSunday | 1 | Sunday
vbMonday | 2 | Monday
vbTuesday | 3 | Tuesday
vbWednesday | 4 | Wednesday
vbThursday | 5 | Thursday
vbFriday | 6 | Friday
vbSaturday | 7 | Saturday

Expand image Remarks

The following example uses the Weekday function to obtain the day of the week from a specified date:

CopyCode image Copy Code
Dim MyDate, MyWeekDay
MyDate = #October 19, 1962#   ' Assign a date.
MyWeekDay = Weekday(MyDate)   ' MyWeekDay contains 6 because MyDate represents a Friday.

Expand image Requirements

Version 1

Expand image See Also

Reference

Date Function
Day Function
Month Function
Now Function
Year Function


WeekdayName Function

Visual Basic Scripting Edition
WeekdayName Function
See Also
CollapseAll image DropDown image

Returns a string indicating the specified day of the week.

WeekdayName(weekday, abbreviate, firstdayofweek)

Expand image 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.

Expand image Settings

The firstdayofweek argument can have the following values:

Constant | Value | Description
vbUseSystemDayOfWeek | 0 | Use National Language Support (NLS) API setting.
vbSunday | 1 | Sunday (default)
vbMonday | 2 | Monday
vbTuesday | 3 | Tuesday
vbWednesday | 4 | Wednesday
vbThursday | 5 | Thursday
vbFriday | 6 | Friday
vbSaturday | 7 | Saturday

Expand image Remarks

The following example uses the WeekDayName function to return the specified day:

CopyCode image Copy Code
Dim MyDate
MyDate = WeekDayName(6, True)   ' MyDate contains Fri.

Expand image Requirements

Version 2

Expand image See Also

Reference

MonthName Function


Year Function

Visual Basic Scripting Edition
Year Function
See Also
CollapseAll image DropDown image

Returns a whole number representing the year.

Year(date)

Expand image Remarks

The date argument is any expression that can represent a date. If date contains Null, Null is returned.

The following example uses the Year function to obtain the year from a specified date:

CopyCode image Copy Code
Dim MyDate, MyYear
MyDate = #October 19, 1962#   ' Assign a date.
MyYear = Year(MyDate)         ' MyYear contains 1962.

Expand image Requirements

Version 1

Expand image See Also

Reference

Date Function
Day Function
Month Function
Now Function
Weekday Function


Keywords (VBScript)

Visual Basic Scripting Edition
Keywords (VBScript)
See Also
DropDown image

The following table explains how to use VBScript keywords.

Keywords

Keyword Description

Empty

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

False

The False keyword has a value equal to 0.

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.

Null

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

True

The True keyword has a value equal to -1.

See Also

Other Resources

VBScript Fundamentals


Methods (VBScript)

Visual Basic Scripting Edition
Methods (VBScript)
See Also
DropDown image

The following table includes links to topics that describe the methods in VBScript.

In This Section

Clear Method | Execute Method
Raise Method | Replace Method
Test Method | Write Method
WriteLine Method |

See Also

Other Resources

VBScript Language Reference


Clear Method (VBScript)

Visual Basic Scripting Edition
Clear Method (VBScript)
See Also
CollapseAll image DropDown image

Clears all property settings of the Err object.

object.Clear

Expand image Remarks

The object is always the Err object.

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.

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

Expand image Requirements

Version 1

Applies To: Err Object (VBScript)

Expand image See Also

Reference

Description Property (VBScript)
Number Property (VBScript)
On Error Statement
Raise Method
Source Property (VBScript)

Concepts

Err Object (VBScript)


Execute Method

Visual Basic Scripting Edition
Execute Method
See Also
CollapseAll image DropDown image

Executes a regular expression search against a specified string.

object.Execute(string)

Expand image Arguments

object

Required. Always the name of a RegExp object.

string

Required. The text string upon which the regular expression is executed.

Expand image 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.

CopyCode image Copy Code
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"))

Expand image Requirements

Version 5

Applies To: Regular Expression (RegExp) Object

Expand image See Also

Reference

Replace Method (VBScript)
Test Method (VBScript)


Raise Method

Visual Basic Scripting Edition
Raise Method
See Also
CollapseAll image DropDown image

Generates a run-time error.

object.Raise(number, source, description, helpfile, helpcontext)

Expand image 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 0–65535.

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.

Expand image 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.

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

Expand image Requirements

Version 1

Applies To: Err Object (VBScript)

Expand image See Also

Reference

Clear Method (VBScript)
Description Property (VBScript)
Number Property (VBScript)
Source Property (VBScript)

Concepts

Err Object (VBScript)


Replace Method (VBScript)

Visual Basic Scripting Edition
Replace Method (VBScript)
See Also
CollapseAll image DropDown image

Replaces text found in a regular expression search.

object.Replace(string1, string2)

Expand image 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.

Expand image 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.

CopyCode image Copy Code
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 the first pair of words in the original string:

CopyCode image Copy Code
MsgBox(ReplaceTest("(\S+)(\s+)(\S+)", "$3$2$1"))   ' Swap first pair of words.

Expand image Requirements

Version 5

Applies To: Regular Expression (RegExp) Object

Expand image See Also

Reference

Execute Method
Test Method (VBScript)


Test Method (VBScript)

Visual Basic Scripting Edition
Test Method (VBScript)
See Also
CollapseAll image DropDown image

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)

Expand image Arguments

object

Required. Always the name of a RegExp object.

string

Required. The text string upon which the regular expression is executed.

Expand image 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.

CopyCode image Copy Code
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"))

Expand image Requirements

Version 5

Applies To: Regular Expression (RegExp) Object

Expand image See Also

Reference

Execute Method
Replace Method (VBScript)


Write Method

Visual Basic Scripting Edition
Write Method
See Also Example
CollapseAll image DropDown image

Sends strings to the script debugger.

Debug.Write([str1 [, str2 [, ... [, strN]]]])

Expand image Arguments

str1, str2, ... , strN

Optional. Strings to send to the script debugger.

Expand image Remarks

The Write method sends strings to the Immediate window of the Microsoft Script Debugger at run time. If the script is not being debugged, the Write method has no effect.

The Write method is almost identical to the WriteLine method. The only difference is that the WriteLine method sends a newline character after the strings are sent.

Expand image Example

This example uses the Write method to display the value of the variable in the Immediate window of the Microsoft Script Debugger.

Note Note

To run this example, you must have a script debugger installed and the script must run in debug mode. For more information, search MSDN (http://msdn.microsoft.com) for the title "Introducing Microsoft Script Debugger".
CopyCode image Copy Code
Dim counter
counter = 42
Debug.Write "The value of counter is " & counter

Expand image Requirements

Version 3

Applies To: Debug Object

Expand image See Also

Reference

WriteLine Method


WriteLine Method

Visual Basic Scripting Edition
WriteLine Method
See Also Example
CollapseAll image DropDown image

Sends strings to the script debugger, followed by a newline character.

Debug.WriteLine([str1 [, str2 [, ... [, strN]]]])

Expand image Arguments

str1, str2, ... , strN

Optional. Strings to send to the script debugger.

Expand image Remarks

The WriteLine method sends strings, followed by a newline character, to the Immediate window of the Microsoft Script Debugger at run time. If the script is not being debugged, the WriteLine method has no effect.

The WriteLine method is almost identical to the Write method. The only difference is that the Write method does not send a newline character after sending the strings.

Expand image Example

This example uses the WriteLine method to display the value of the variable in the Immediate window of the Microsoft Script Debugger.

Note Note

To run this example, you must have a script debugger installed and the script must run in debug mode. For more information, search MSDN (http://msdn.microsoft.com) for the title "Introducing Microsoft Script Debugger".
CopyCode image Copy Code
Dim counter
counter = 42
Debug.WriteLine "The value of counter is " & counter

Expand image Requirements

Version 3

Applies To: Debug Object

Expand image See Also

Reference

Write Method


Miscellaneous

Visual Basic Scripting Edition
Miscellaneous
See Also
DropDown image

The following table includes topics with information about character sets and locale Ids in VBScript.

Character Sets and Local IDs

Character Set (0 - 127) | Character Set (128 - 255)
Locale ID (LCID) Chart |

See Also

Other Resources

VBScript Language Reference


Character Set (0 - 127)

Visual Basic Scripting Edition
Character Set (0 - 127)
See Also
DropDown image

The following table lists 0 - 127.

Character Table

Code | Char | Code | Char | Code | Char | Code | Char
0 |  | 32 | [space] | 64 | @ | 96 | `
1 |  | 33 | ! | 65 | A | 97 | a
2 |  | 34 | " | 66 | B | 98 | b
3 |  | 35 | # | 67 | C | 99 | c
4 |  | 36 | $ | 68 | D | 100 | d
5 |  | 37 | % | 69 | E | 101 | e
6 |  | 38 | & | 70 | F | 102 | f
7 |  | 39 | ' | 71 | G | 103 | g
8 | ** | 40 | ( | 72 | H | 104 | h
9 | ** | 41 | ) | 73 | I | 105 | i
10 | ** | 42 | * | 74 | J | 106 | j
11 |  | 43 | + | 75 | K | 107 | k
12 |  | 44 | , | 76 | L | 108 | l
13 | ** | 45 | - | 77 | M | 109 | m
14 |  | 46 | . | 78 | N | 110 | n
15 |  | 47 | / | 79 | O | 111 | o
16 |  | 48 | 0 | 80 | P | 112 | p
17 |  | 49 | 1 | 81 | Q | 113 | q
18 |  | 50 | 2 | 82 | R | 114 | r
19 |  | 51 | 3 | 83 | S | 115 | s
20 |  | 52 | 4 | 84 | T | 116 | t
21 |  | 53 | 5 | 85 | U | 117 | u
22 |  | 54 | 6 | 86 | V | 118 | v
23 |  | 55 | 7 | 87 | W | 119 | w
24 |  | 56 | 8 | 88 | X | 120 | x
25 |  | 57 | 9 | 89 | Y | 121 | y
26 |  | 58 | : | 90 | Z | 122 | z
27 |  | 59 | ; | 91 | [ | 123 | {
28 |  | 60 | < | 92 | \ | 124 | |
29 |  | 61 | = | 93 | ] | 125 | }
30 |  | 62 | > | 94 | ^ | 126 | ~
31 |  | 63 | ? | 95 | _ | 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

Concepts

Character Set (128 - 255)


Character Set (128 - 255)

Visual Basic Scripting Edition
Character Set (128 - 255)
See Also
DropDown image

The following table lists 128 - 255.

Characters

Code | Char | Code | Char | Code | Char | Code | Char
128 | € | 160 | [space] | 192 | À | 224 | à
129 |  | 161 | ¡ | 193 | Á | 225 | á
130 | ‚ | 162 | ¢ | 194 | Â | 226 | â
131 | ƒ | 163 | £ | 195 | Ã | 227 | ã
132 | ‚‚ | 164 | ¤ | 196 | Ä | 228 | ä
133 | … | 165 | ¥ | 197 | Å | 229 | å
134 | † | 166 | ¦ | 198 | Æ | 230 | æ
135 | ‡ | 167 | § | 199 | Ç | 231 | ç
136 | ˆ | 168 | ¨ | 200 | È | 231 | ç
137 | ‰ | 169 | © | 201 | É | 232 | è
138 | Š | 170 | ª | 202 | Ê | 233 | é
139 | ‹ | 171 | ‹‹ | 203 | Ë | 234 | ê
140 | Œ | 172 | ¬ | 204 | Ì | 235 | ë
141 |  | 173 |  | 205 | Í | 236 | ì
142 | Ž | 174 | ® | 206 | Î | 237 | í
143 |  | 175 | ¯ | 207 | Ï | 238 | î
144 |  | 176 | ° | 208 | Ð | 239 | ï
145 | ' | 177 | ± | 209 | Ñ | 240 | ð
146 | ' | 178 | ² | 210 | Ò | 241 | ñ
147 | " | 179 | ³ | 211 | Ó | 242 | ò
148 | " | 180 | ´ | 212 | Ô | 243 | ó
149 | · | 181 | µ | 213 | Õ | 244 | ô
150 | – | 182 | ¶ | 214 | Ö | 245 | õ
151 | — | 183 | · | 215 | × | 246 | ö
152 | ˜ | 184 | ¸ | 216 | Ø | 247 | ÷
153 | ™ | 185 | ¹ | 217 | Ù | 248 | ø
154 | š | 186 | º | 218 | Ú | 249 | ù
155 | › | 187 | ›› | 219 | Û | 250 | ú
156 | œ | 188 | ¼ | 220 | Ü | 251 | û
157 |  | 189 | ½ | 221 | Ý | 252 | ü
158 | ž | 190 | ¾ | 222 | Þ | 253 | ý
159 | Ÿ | 191 | ¿ | 223 | ß | 254 | þ

 Not supported on the current platform.

See Also

Concepts

Character Set (0 - 127)


Locale ID (LCID) Chart

Visual Basic Scripting Edition
Locale ID (LCID) Chart
DropDown image

The following table lists Locale IDs (LCID).

Locale IDs

Locale Description | Short String | Hex Value | Decimal Value | Locale Description | Short String | Hex Value | Decimal Value
Afrikaans | af | 0x0436 | 1078 | Icelandic | is | 0x040F | 1039
Albanian | sq | 0x041C | 1052 | Indonesian | id | 0x0421 | 1057
Arabic - United Arab Emirates | ar-ae | 0x3801 | 14337 | Italian - Italy | it-it | 0x0410 | 1040
Arabic - Bahrain | ar-bh | 0x3C01 | 15361 | Italian - Switzerland | it-ch | 0x0810 | 2064
Arabic - Algeria | ar-dz | 0x1401 | 5121 | Japanese | ja | 0x0411 | 1041
Arabic - Egypt | ar-eg | 0x0C01 | 3073 | Korean | ko | 0x0412 | 1042
Arabic - Iraq | ar-iq | 0x0801 | 2049 | Latvian | lv | 0x0426 | 1062
Arabic - Jordan | ar-jo | 0x2C01 | 11265 | Lithuanian | lt | 0x0427 | 1063
Arabic - Kuwait | ar-kw | 0x3401 | 13313 | Macedonian (FYROM) | mk | 0x042F | 1071
Arabic - Lebanon | ar-lb | 0x3001 | 12289 | Malay - Malaysia | ms-my | 0x043E | 1086
Arabic - Libya | ar-ly | 0x1001 | 4097 | Malay – Brunei | ms-bn | 0x083E | 2110
Arabic - Morocco | ar-ma | 0x1801 | 6145 | Maltese | mt | 0x043A | 1082
Arabic - Oman | ar-om | 0x2001 | 8193 | Marathi | mr | 0x044E | 1102
Arabic - Qatar | ar-qa | 0x4001 | 16385 | Norwegian - Bokml | no-no | 0x0414 | 1044
Arabic - Saudi Arabia | ar-sa | 0x0401 | 1025 | Norwegian - Nynorsk | no-no | 0x0814 | 2068
Arabic - Syria | ar-sy | 0x2801 | 10241 | Polish | pl | 0x0415 | 1045
Arabic - Tunisia | ar-tn | 0x1C01 | 7169 | Portuguese - Portugal | pt-pt | 0x0816 | 2070
Arabic - Yemen | ar-ye | 0x2401 | 9217 | Portuguese - Brazil | pt-br | 0x0416 | 1046
Armenian | hy | 0x042B | 1067 | Raeto-Romance | rm | 0x0417 | 1047
Azeri - Latin | az-az | 0x042C | 1068 | Romanian - Romania | ro | 0x0418 | 1048
Azeri - Cyrillic | az-az | 0x082C | 2092 | Romanian - Moldova | ro-mo | 0x0818 | 2072
Basque | eu | 0x042D | 1069 | Russian | ru | 0x0419 | 1049
Belarusian | be | 0x0423 | 1059 | Russian - Moldova | ru-mo | 0x0819 | 2073
Bulgarian | bg | 0x0402 | 1026 | Sanskrit | sa | 0x044F | 1103
Catalan | ca | 0x0403 | 1027 | Serbian - Cyrillic | sr-sp | 0x0C1A | 3098
Chinese - China | zh-cn | 0x0804 | 2052 | Serbian - Latin | sr-sp | 0x081A | 2074
Chinese - Hong Kong SAR | zh-hk | 0x0C04 | 3076 | Setsuana | tn | 0x0432 | 1074
Chinese - Macau SAR | zh-mo | 0x1404 | 5124 | Slovenian | sl | 0x0424 | 1060
Chinese - Singapore | zh-sg | 0x1004 | 4100 | Slovak | sk | 0x041B | 1051
Chinese - Taiwan | zh-tw | 0x0404 | 1028 | Sorbian | sb | 0x042E | 1070
Croatian | hr | 0x041A | 1050 | Spanish - Spain | es-es | 0x0C0A | 1034
Czech | cs | 0x0405 | 1029 | Spanish - Argentina | es-ar | 0x2C0A | 11274
Danish | da | 0x0406 | 1030 | Spanish - Bolivia | es-bo | 0x400A | 16394
Dutch - Netherlands | nl-nl | 0x0413 | 1043 | Spanish - Chile | es-cl | 0x340A | 13322
Dutch - Belgium | nl-be | 0x0813 | 2067 | Spanish - Colombia | es-co | 0x240A | 9226
English - Australia | en-au | 0x0C09 | 3081 | Spanish - Costa Rica | es-cr | 0x140A | 5130
English - Belize | en-bz | 0x2809 | 10249 | Spanish - Dominican Republic | es-do | 0x1C0A | 7178
English - Canada | en-ca | 0x1009 | 4105 | Spanish - Ecuador | es-ec | 0x300A | 12298
English - Caribbean | en-cb | 0x2409 | 9225 | Spanish - Guatemala | es-gt | 0x100A | 4106
English - Ireland | en-ie | 0x1809 | 6153 | Spanish - Honduras | es-hn | 0x480A | 18442
English - Jamaica | en-jm | 0x2009 | 8201 | Spanish - Mexico | es-mx | 0x080A | 2058
English - New Zealand | en-nz | 0x1409 | 5129 | Spanish - Nicaragua | es-ni | 0x4C0A | 19466
English - Phillippines | en-ph | 0x3409 | 13321 | Spanish - Panama | es-pa | 0x180A | 6154
English - South Africa | en-za | 0x1C09 | 7177 | Spanish - Peru | es-pe | 0x280A | 10250
English - Trinidad | en-tt | 0x2C09 | 11273 | Spanish - Puerto Rico | es-pr | 0x500A | 20490
English - United Kingdom | en-gb | 0x0809 | 2057 | Spanish - Paraguay | es-py | 0x3C0A | 15370
English - United States | en-us | 0x0409 | 1033 | Spanish - El Salvador | es-sv | 0x440A | 17418
Estonian | et | 0x0425 | 1061 | Spanish - Uruguay | es-uy | 0x380A | 14346
Farsi | fa | 0x0429 | 1065 | Spanish - Venezuela | es-ve | 0x200A | 8202
Finnish | fi | 0x040B | 1035 | Southern Sotho | st | 0x0430 | 1072
Faroese | fo | 0x0438 | 1080 | Swahili | sw | 0x0441 | 1089
French - France | fr-fr | 0x040C | 1036 | Swedish - Sweden | sv-se | 0x041D | 1053
French - Belgium | fr-be | 0x080C | 2060 | Swedish - Finland | sv-fi | 0x081D | 2077
French - Canada | fr-ca | 0x0C0C | 3084 | Tamil | ta | 0x0449 | 1097
French - Luxembourg | fr-lu | 0x140C | 5132 | Tatar | tt | 0X0444 | 1092
French - Switzerland | fr-ch | 0x100C | 4108 | Thai | th | 0x041E | 1054
Gaelic - Ireland | gd-ie | 0x083C | 2108 | Turkish | tr | 0x041F | 1055
Gaelic - Scotland | gd | 0x043C | 1084 | Tsonga | ts | 0x0431 | 1073
German - Germany | de-de | 0x0407 | 1031 | Ukrainian | uk | 0x0422 | 1058
German - Austria | de-at | 0x0C07 | 3079 | Urdu | ur | 0x0420 | 1056
German - Liechtenstein | de-li | 0x1407 | 5127 | Uzbek - Cyrillic | uz-uz | 0x0843 | 2115
German - Luxembourg | de-lu | 0x1007 | 4103 | Uzbek – Latin | uz-uz | 0x0443 | 1091
German - Switzerland | de-ch | 0x0807 | 2055 | Vietnamese | vi | 0x042A | 1066
Greek | el | 0x0408 | 1032 | Xhosa | xh | 0x0434 | 1076
Hebrew | he | 0x040D | 1037 | Yiddish | yi | 0x043D | 1085
Hindi | hi | 0x0439 | 1081 | Zulu | zu | 0x0435 | 1077
Hungarian | hu | 0x040E | 1038 |  |  |  |


Objects and Collections
See Also
DropDown image

The following table lists objects and collections in VBScript.

Objects and Collections

Class Object | Debug Object
Err Object | Match Object
Matches Collection | Regular Expression (RegExp) Object
SubMatches Collection |

See Also

Other Resources

VBScript Language Reference


Class Object

Visual Basic Scripting Edition
Class Object
See Also
DropDown image

This object is created by using the Class statement, and it 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:

CopyCode image Copy Code
Dim X
Set X = New classname

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

CopyCode image Copy Code
Dim X as New classname

-or-

CopyCode image Copy Code
Dim X
X = New classname

-or-

CopyCode image Copy Code
Set X = New Scripting.FileSystemObject

Events

Class Object Events

Requirements

Version 5

See Also

Reference

Class Statement (VBScript)
Dim Statement
Set Statement


Class Object Events

Visual Basic Scripting Edition
Class Object Events
DropDown image

The Class object provides access to the events of the class.

Class Objects

Initialize Event

Terminate Event


Debug Object

Visual Basic Scripting Edition
Debug Object
See Also
DropDown image

An intrinsic global object that can send output to a script debugger, such as the Microsoft Script Debugger.

Remarks

The Debug object cannot be created directly, but it is always available for use.

The Write and WriteLine methods of the Debug object display strings in the Immediate window of the Microsoft Script Debugger at run time. If the script is not being debugged, the methods have no effect.

This example uses the Write method to display the value of the variable in the Immediate window of the Microsoft Script Debugger.

Note Note

To run this example, you must have a script debugger installed and the script must run in debug mode. For more information, search MSDN (http://msdn.microsoft.com) for the title "Introducing Microsoft Script Debugger".

CopyCode image Copy Code
Dim counter
counter = 42
Debug.Write "The value of counter is " & counter

Properties and Methods

Debug Object Methods

Requirements

Version 3

See Also

Reference

Stop Statement


Debug Object Methods

Visual Basic Scripting Edition
Debug Object Methods
DropDown image

The Debug Object can send output to a script debugger, such as the Windows Script Debugger.

Methods

Write Method

WriteLine Method


Err Object (VBScript)

Visual Basic Scripting Edition
Err Object (VBScript)
See Also
DropDown image

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:

CopyCode image Copy Code
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

Reference

On Error Statement


Err Object Properties and Methods

Visual Basic Scripting Edition
Err Object Properties and Methods
DropDown image

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


Match Object

Visual Basic Scripting Edition
Match Object
See Also
DropDown image

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:

CopyCode image Copy Code
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

Concepts

Matches Collection
Regular Expression (RegExp) Object
SubMatches Collection


Match Object Properties

Visual Basic Scripting Edition
Match Object Properties
DropDown image

The Match object provides access to the read-only properties of a regular expression match.

Properties

FirstIndex Property | Length Property
Value Property |


Matches Collection

Visual Basic Scripting Edition
Matches Collection
See Also
DropDown image

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:

CopyCode image Copy Code
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 5

See Also

Reference

For Each...Next Statement

Concepts

Match Object
Regular Expression (RegExp) Object
SubMatches Collection


Regular Expression (RegExp) Object

Visual Basic Scripting Edition
Regular Expression (RegExp) Object
See Also
DropDown image

Provides simple regular expression support.

Remarks

The following code illustrates the use of the RegExp object.

CopyCode image Copy Code
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

Concepts

Match Object
Matches Collection


Regular Expression Object Properties and Methods (VBScript)

Visual Basic Scripting Edition
Regular Expression Object Properties and Methods (VBScript)
DropDown image

The Regular Expression object provides simple regular expression support.

Properties

Global Property | IgnoreCase Property
Pattern Property |

Methods

Execute Method | Replace Method
Test Method |


SubMatches Collection

Visual Basic Scripting Edition
SubMatches Collection
See Also
DropDown image

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:

CopyCode image Copy Code
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

Reference

For Each...Next Statement

Concepts

Match Object
Matches Collection
Regular Expression (RegExp) Object


Operators (VBScript)

Visual Basic Scripting Edition
Operators (VBScript)
DropDown image

The following sections explain how to use operators in VBScript.

In This Section

Operator Precedence

Explains how the order in which you use operators affects results.

Operator Summary

Includes links to operators that fall within major operational categories.

Arithmetic Operators

Includes links to topics that explain how to use individual arithmetic operators.

Comparison Operators

Includes links to topics that explain how to use individual comparison operators.

Concatenation Operators

Includes links to topics that explain how to use individual concatenation operators.

Logical Operators

Includes links to topics that explain how to use individual logical operators.

Related Sections

VBScript Fundamentals

Introduces VBScript features and elements.


Operator Precedence (VBScript)

Visual Basic Scripting Edition
Operator Precedence (VBScript)
See Also
CollapseAll image DropDown image

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.

Expand image Types of Operators

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 | Logical
Negation (-) | Equality (=) | Not
Exponentiation (^) | Inequality (<>) | And
Multiplication and division (*, /) | Less than (<) | Or
Integer division (\) | Greater than (>) | Xor
Modulus arithmetic (Mod) | Less than or equal to (<=) | Eqv
Addition and subtraction (+, -) | Greater than or equal to (>=) | Imp
String concatenation (&) | Is | &

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.

Expand image Requirements

Version 1

Expand image See Also

Reference

Is Operator

Other Resources

Operator Summary (VBScript)


Operator Summary (VBScript)

Visual Basic Scripting Edition
Operator Summary (VBScript)
DropDown image

The following sections categorize operators according to their functions within VBScript.

In This Section

Arithmetic Operators

Operators used to perform mathematical calculations.

Assignment Operator (=) (VBScript)

Operator used to assign a value to a property or variable.

Comparison Operators (VBScript)

Operators used to perform comparisons.

Concatenation Operators

Operators used to combine strings.

Logical Operators (VBScript)

Operators used to perform logical operations.

Related Sections

Operator Precedence (VBScript)

Explains how the order in which you use operators affects results.


Addition Operator (+) (VBScript)

Visual Basic Scripting Edition
Addition Operator (+) (VBScript)
See Also
CollapseAll image DropDown image

Sums two numbers.

result = expression1 + expression2

Expand image Arguments

result

Any numeric variable.

expression1

Any expression.

expression2

Any expression.

Expand image 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.

Expand image Requirements

Version 1

Expand image See Also

Reference

Concatenation Operator (&)
Subtraction Operator (-) (VBScript)
Operator Precedence (VBScript)

Concepts

Arithmetic Operators
Concatenation Operators

Other Resources

Operator Summary (VBScript)


And Operator

Visual Basic Scripting Edition
And Operator
See Also
CollapseAll image DropDown image

Performs a logical conjunction on two expressions.

result = expression1 And expression2

Expand image Arguments

result

Any numeric variable.

expression1

Any expression.

expression2

Any expression.

Expand image 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 | And expression2 is | The result is
True | True | True
True | False | False
True | Null | Null
False | True | False
False | False | False
False | Null | False
Null | True | Null
Null | False | False
Null | 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:

If bit in expression1 is | And bit in expression2 is | The result is
0 | 0 | 0
0 | 1 | 0
1 | 0 | 0
1 | 1 | 1

Expand image Requirements

Version 1

Expand image See Also

Reference

Not Operator
Operator Precedence (VBScript)
Or Operator
Xor Operator

Concepts

Logical Operators (VBScript)

Other Resources

Operator Summary (VBScript)


Assignment Operator (=) (VBScript)

Visual Basic Scripting Edition
Assignment Operator (=) (VBScript)
See Also
CollapseAll image DropDown image

Assigns a value to a variable or property.

variable = value

Expand image Arguments

variable

Any variable or any writable property.

value

Any numeric or string literal, constant, or expression.

Expand image 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.

Expand image Requirements

Version 1

Expand image See Also

Reference

Comparison Operators (VBScript)
Operator Precedence (VBScript)
Set Statement

Other Resources

Operator Summary (VBScript)


Concatenation Operator (&)

Visual Basic Scripting Edition
Concatenation Operator (&)
See Also
CollapseAll image DropDown image

Forces string concatenation of two expressions.

result = expression1 & expression2

Expand image Arguments

result

Any variable.

expression1

Any expression.

expression2

Any expression.

Expand image 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.

Expand image Requirements

Version 1

Expand image See Also

Reference

Operator Precedence (VBScript)

Concepts

Concatenation Operators

Other Resources

Operator Summary (VBScript)


Division Operator (/) (VBScript)

Visual Basic Scripting Edition
Division Operator (/) (VBScript)
See Also
CollapseAll image DropDown image

Divides two numbers and returns a floating-point result.

result = number1/number2

Expand image Arguments

result

Any numeric variable.

number1

Any numeric expression.

number2

Any numeric expression.

Expand image Remarks

If one or both expressions are Null expressions, result is Null. Any expression that is Empty is treated as 0.

Expand image Requirements

Version 1

Expand image See Also

Reference

Multiplication Operator (*) (VBScript)
Integer Division Operator (\)
Operator Precedence (VBScript)

Concepts

Arithmetic Operators

Other Resources

Operator Summary (VBScript)


Eqv Operator

Visual Basic Scripting Edition
Eqv Operator
See Also
CollapseAll image DropDown image

Performs a logical equivalence on two expressions.

result = expression1 Eqv expression2

Expand image Arguments

result

Any numeric variable.

expression1

Any expression.

expression2

Any expression.

Expand image 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 | And expression2 is | The result is
True | True | True
True | False | False
False | True | False
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:

If bit in expression1 is | And bit in expression2 is | The result is
0 | 0 | 1
0 | 1 | 0
1 | 0 | 0
1 | 1 | 1

Expand image Requirements

Version 1

Expand image See Also

Reference

Imp Operator
Operator Precedence (VBScript)

Concepts

Logical Operators (VBScript)

Other Resources

Operator Summary (VBScript)


Exponentiation Operator (^)

Visual Basic Scripting Edition
Exponentiation Operator (^)
See Also
CollapseAll image DropDown image

Raises a number to the power of an exponent.

result = number^exponent

Expand image Arguments

result

Any numeric variable.

number

Any numeric expression.

exponent

Any numeric expression.

Expand image 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.

Expand image Requirements

Version 1

Expand image See Also

Reference

Operator Precedence (VBScript)

Concepts

Arithmetic Operators

Other Resources

Operator Summary (VBScript)


Imp Operator

Visual Basic Scripting Edition
Imp Operator
See Also
CollapseAll image DropDown image

Performs a logical implication on two expressions.

result = expression1 Imp expression2

Expand image Arguments

result

Any numeric variable.

expression1

Any expression.

expression2

Any expression.

Expand image Remarks

The following table illustrates how result is determined:

If expression1 is | And expression2 is | Then result is
True | True | True
True | False | False
True | Null | Null
False | True | True
False | False | True
False | Null | True
Null | True | True
Null | False | Null
Null | 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:

If bit in expression1 is | And bit in expression2 is | Then result is
0 | 0 | 1
0 | 1 | 1
1 | 0 | 0
1 | 1 | 1

Expand image Requirements

Version 1

Expand image See Also

Reference

Eqv Operator
Operator Precedence (VBScript)

Concepts

Logical Operators (VBScript)

Other Resources

Operator Summary (VBScript)


Integer Division Operator (\)

Visual Basic Scripting Edition
Integer Division Operator (\)
See Also
CollapseAll image DropDown image

Divides two numbers and returns an integer result.

result = number1\number2

Expand image Arguments

result

Any numeric variable.

number1

Any numeric expression.

number2

Any numeric expression.

Expand image 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.

Expand image Requirements

Version 1

Expand image See Also

Reference

Multiplication Operator (*) (VBScript)
Division Operator (/) (VBScript)
Operator Precedence (VBScript)

Concepts

Arithmetic Operators

Other Resources

Operator Summary (VBScript)


Is Operator

Visual Basic Scripting Edition
Is Operator
See Also
CollapseAll image DropDown image

Compares two object reference variables.

result = object1 Is object2

Expand image Arguments

result

Any numeric variable.

object1

Any object name.

object2

Any object name.

Expand image 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:

CopyCode image Copy Code
Set A = B

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

CopyCode image Copy Code
Set A = C
Set B = C

Expand image Requirements

Version 1

Expand image See Also

Reference

Comparison Operators (VBScript)
Operator Precedence (VBScript)

Other Resources

Operator Summary (VBScript)


Mod Operator

Visual Basic Scripting Edition
Mod Operator
See Also
CollapseAll image DropDown image

Divides two numbers and returns only the remainder.

result = number1 Mod number2

Expand image Arguments

result

Any numeric variable.

number1

Any numeric expression.

number2

Any numeric expression.

Expand image 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.

CopyCode image Copy Code
A = 19 Mod 6.7

If any expression is Null, result is also Null. Any expression that is Empty is treated as 0.

Expand image Requirements

Version 1

Expand image See Also

Reference

Operator Precedence (VBScript)

Concepts

Arithmetic Operators

Other Resources

Operator Summary (VBScript)


Multiplication Operator (*) (VBScript)

Visual Basic Scripting Edition
Multiplication Operator (*) (VBScript)
See Also
CollapseAll image DropDown image

Multiplies two numbers.

result = number1*number2

Expand image Arguments

result

Any numeric variable.

number1

Any numeric expression.

number2

Any numeric expression.

Expand image 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.

Expand image Requirements

Version 1

Expand image See Also

Reference

Integer Division Operator (\)
Operator Precedence (VBScript)

Concepts

Arithmetic Operators

Other Resources

Operator Summary (VBScript)


Not Operator

Visual Basic Scripting Edition
Not Operator
See Also
CollapseAll image DropDown image

Performs logical negation on an expression.

result = Not expression

Expand image Arguments

result

Any numeric variable.

expression

Any expression.

Expand image 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

Expand image Requirements

Version 1

Expand image See Also

Reference

And Operator
Operator Precedence (VBScript)
Or Operator
Xor Operator

Concepts

Logical Operators (VBScript)

Other Resources

Operator Summary (VBScript)


Or Operator

Visual Basic Scripting Edition
Or Operator
See Also
CollapseAll image DropDown image

Performs a logical disjunction on two expressions.

result = expression1 Or expression2

Expand image Arguments

result

Any numeric variable.

expression1

Any expression.

expression2

Any expression.

Expand image Remarks

If either or both expressions evaluate to True, result is True. The following table illustrates how result is determined:

If expression1 is | And expression2 is | Then result is
True | True | True
True | False | True
True | Null | True
False | True | True
False | False | False
False | Null | Null
Null | True | True
Null | False | Null
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:

If bit in expression1 is | And bit in expression2 is | Then result is
0 | 0 | 0
0 | 1 | 1
1 | 0 | 1
1 | 1 | 1

Expand image Requirements

Version 1

Expand image See Also

Reference

And Operator
Not Operator
Operator Precedence (VBScript)
Xor Operator

Concepts

Logical Operators (VBScript)

Other Resources

Operator Summary (VBScript)


Subtraction Operator (-) (VBScript)

Visual Basic Scripting Edition
Subtraction Operator (-) (VBScript)
See Also
CollapseAll image DropDown image

Finds the difference between two numbers or indicates the negative value of a numeric expression.

' Example 1
result = number1-number2
' Example 2
-number

Expand image Arguments

result

Any numeric variable.

number

Any numeric expression.

number1

Any numeric expression.

number2

Any numeric expression.

Expand image 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.

Expand image Requirements

Version 1

Expand image See Also

Reference

Addition Operator (+) (VBScript)
Operator Precedence (VBScript)

Concepts

Arithmetic Operators

Other Resources

Operator Summary (VBScript)


Xor Operator

Visual Basic Scripting Edition
Xor Operator
See Also
CollapseAll image DropDown image

Performs a logical exclusion on two expressions.

result = expression1 Xor expression2

Expand image Arguments

result

Any numeric variable.

expression1

Any expression.

expression2

Any expression.

Expand image 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 | And expression2 is | Then result is
True | True | False
True | False | True
False | True | True
False | 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:

If bit in expression1 is | And bit in expression2 is | Then result is
0 | 0 | 0
0 | 1 | 1
1 | 0 | 1
1 | 1 | 0

Expand image Requirements

Version 1

Expand image See Also

Reference

And Operator
Not Operator
Operator Precedence (VBScript)
Or Operator

Concepts

Logical Operators (VBScript)

Other Resources

Operator Summary (VBScript)


Arithmetic Operators

Visual Basic Scripting Edition
Arithmetic Operators
DropDown image

The following table lists arithmetic operators in VBScript.

Operators

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


Comparison Operators (VBScript)

Visual Basic Scripting Edition
Comparison Operators (VBScript)
See Also
CollapseAll image DropDown image

Used to compare expressions.

result = expression1 comparisonoperator expression2
result = object1 Is object2

Expand image Parts

result

Any numeric variable.

expression

Any expression.

comparisonoperator

Any comparison operator.

object

Any object name.

Expand image 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 | True if | False if | Null if
< | Less than | expression1 < expression2 | expression1 >= expression2 | expression1 or expression2 = Null
<= | Less than or equal to | expression1 <= expression2 | expression1 > expression2 | expression1 or expression2 = Null
> | Greater than | expression1 > expression2 | expression1 <= expression2 | expression1 or expression2 = Null
>= | Greater than or equal to | expression1 >= expression2 | expression1 < expression2 | expression1 or expression2 = Null
= | Equal to | expression1 = expression2 | expression1 <> expression2 | expression1 or expression2 = Null
<> | Not equal to | expression1 <> expression2 | expression1 = expression2 | 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 | Then
Both expressions are numeric | Perform a numeric comparison.
Both expressions are strings | Perform a string comparison.
One expression is numeric and the other is a string | The numeric expression is less than the string expression.
One expression is Empty and the other is numeric | Perform a numeric comparison, using 0 as the Empty expression.
One expression is Empty and the other is a string | Perform a string comparison, using a zero-length string ("") as the Empty expression.
Both expressions are Empty | The expressions are equal.

Expand image Requirements

Version 1

Expand image See Also

Reference

Assignment Operator (=) (VBScript)
Is Operator
Operator Precedence (VBScript)

Other Resources

Operator Summary (VBScript)


Concatenation Operators

Visual Basic Scripting Edition
Concatenation Operators
DropDown image

The following table lists concatenation operators in VBScript.

Operators

& Operator

+ Operator


Logical Operators (VBScript)

Visual Basic Scripting Edition
Logical Operators (VBScript)
DropDown image

The following table lists logical operators in VBScript.

Operators

And Operator | Not Operator
Or Operator | Xor Operator


Properties (VBScript)

Visual Basic Scripting Edition
Properties (VBScript)
See Also
DropDown image

The following table lists properties in VBScript.

Properties

Description Property | FirstIndex Property
Global Property | HelpContext Property
HelpFile Property | IgnoreCase Property
Length Property | Number Property
Pattern Property | Source Property
Value Property |

See Also

Other Resources

VBScript Language Reference


Description Property (VBScript)

Visual Basic Scripting Edition
Description Property (VBScript)
See Also
CollapseAll image DropDown image

Returns or sets a descriptive string associated with an error.

object.Description [= stringexpression]

Expand image Arguments

object

Always the Err object.

stringexpression

A string expression containing a description of the error.

Expand image 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.

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

Expand image Requirements

Version 1

Applies To: Err Object (VBScript)

Expand image See Also

Reference

HelpContext Property
HelpFile Property (VBScript)
Number Property (VBScript)
Source Property (VBScript)

Concepts

Err Object (VBScript)


FirstIndex Property

Visual Basic Scripting Edition
FirstIndex Property
See Also
CollapseAll image DropDown image

Returns the position in a search string where a match occurs.

object.FirstIndex

Expand image Arguments

The object argument is always a Match object.

Expand image 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.

CopyCode image Copy Code
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"))

Expand image Requirements

Version 5

Applies To: Match Object

Expand image See Also

Reference

Length Property
Value Property (VBScript)


Global Property (VBScript)

Visual Basic Scripting Edition
Global Property (VBScript)
See Also
CollapseAll image DropDown image

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 ]

Expand image Arguments

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.

Expand image Remarks

The following code illustrates the use of the Global property (change the value assigned to Global property to see its effect):

CopyCode image Copy Code
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"))

Expand image Requirements

Version 5

Applies To: Regular Expression (RegExp) Object

Expand image See Also

Reference

IgnoreCase Property (VBScript)
Pattern Property


HelpContext Property

Visual Basic Scripting Edition
HelpContext Property
See Also
CollapseAll image DropDown image

Sets or returns a context ID for a topic in a Help File.

object.HelpContext [= contextID]

Expand image Arguments

object

Required. Always the Err object.

contextID

Optional. A valid identifier for a Help topic within the Help file.

Expand image 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:

CopyCode image Copy Code
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

Expand image Requirements

Version 2

Applies To: Err Object (VBScript)

Expand image See Also

Reference

Description Property (VBScript)
HelpFile Property (VBScript)
Number Property (VBScript)
Source Property (VBScript)


HelpFile Property (VBScript)

Visual Basic Scripting Edition
HelpFile Property (VBScript)
See Also
CollapseAll image DropDown image

Sets or returns a fully qualified path to a Help File.

object.HelpFile [= contextID]

Expand image Arguments

object

Required. Always the Err object.

contextID

Optional. Fully qualified path to the Help file.

Expand image 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.

CopyCode image Copy Code
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

Expand image Requirements

Version 2

Applies To: Err Object (VBScript)

Expand image See Also

Reference

Description Property (VBScript)
HelpContext Property
Number Property (VBScript)
Source Property (VBScript)


IgnoreCase Property (VBScript)

Visual Basic Scripting Edition
IgnoreCase Property (VBScript)
See Also
CollapseAll image DropDown image

Sets or returns a Boolean value that indicates if a pattern search is case-sensitive or not.

object.IgnoreCase [= True | False ]

Expand image Arguments

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.

Expand image Remarks

The following code illustrates the use of the IgnoreCase property (change the value assigned to IgnoreCase property to see its effect):

CopyCode image Copy Code
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"))

Expand image Requirements

Version 5

Applies To: Regular Expression (RegExp) Object

Expand image See Also

Reference

Global Property (VBScript)
Pattern Property


Length Property

Visual Basic Scripting Edition
Length Property
See Also
CollapseAll image DropDown image

Returns the length of a match found in a search string.

object.Length

Expand image Arguments

The object argument is always a Match object.

Expand image Remarks

The following code illustrates the use of the Length property:

CopyCode image Copy Code
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"))

Expand image Requirements

Version 5

Applies To: Match Object

Expand image See Also

Reference

FirstIndex Property
Value Property (VBScript)


Number Property (VBScript)

Visual Basic Scripting Edition
Number Property (VBScript)
See Also
CollapseAll image DropDown image

Returns or sets a numeric value specifying an error. Number is the Err object's default property.

object.Number [= errornumber]

Expand image Arguments

object

Always the Err object.

errornumber

An integer representing a VBScript error number or an SCODE error value.

Expand image 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.

CopyCode image Copy Code
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.

Expand image Requirements

Version 1

Applies To: Err Object (VBScript)

Expand image See Also

Reference

Description Property (VBScript)
HelpContext Property
HelpFile Property (VBScript)
Source Property (VBScript)

Concepts

Err Object (VBScript)


Pattern Property

Visual Basic Scripting Edition
Pattern Property
See Also
CollapseAll image DropDown image

Sets or returns the regular expression pattern being searched for.

object.Pattern [= "searchstring"]

Expand image 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.

Expand image 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 | 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.
(pattern) | 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 "\)".
x|y | Matches either x or y. For example, "z|wood" matches "z" or "wood". "(z|w)oo" matches "zoo" or "wood".
{n} | 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,} | 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*".
{ n , m } | 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?".
[ xyz ] | A character set. Matches any one of the enclosed characters. For example, "[abc]" matches the "a" in "plain".
[^ xyz ] | A negative character set. Matches any character not enclosed. For example, "[^abc]" matches the "p" in "plain".
[ a-z ] | 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".
[^ m-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".
\b | 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".
\B | Matches a non-word boundary. "ea*r\B" matches the "ear" in "never early".
\d | Matches a digit character. Equivalent to [0-9].
\D | Matches a non-digit character. Equivalent to [^0-9].
\f | Matches a form-feed character.
\n | Matches a newline character.
\r | Matches a carriage return character.
\s | Matches any white space including space, tab, form-feed, etc. Equivalent to "[ \f\n\r\t\v]".
\S | Matches any nonwhite space character. Equivalent to "[^ \f\n\r\t\v]".
\t | Matches a tab character.
\v | Matches a vertical tab character.
\w | Matches any word character including underscore. Equivalent to "[A-Za-z0-9_]".
\W | Matches any non-word character. Equivalent to "[^A-Za-z0-9_]".
\num | Matches num, where num is a positive integer. A reference back to remembered matches. For example, "(.)\1" matches two consecutive identical characters.
\ n | 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.
\xn | 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.

Expand image Remarks

The following code illustrates the use of the Pattern property.

CopyCode image Copy Code
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"))

Expand image Requirements

Version 5

Applies To: Regular Expression (RegExp) Object

Expand image See Also

Reference

Global Property (VBScript)
IgnoreCase Property (VBScript)


Source Property (VBScript)

Visual Basic Scripting Edition
Source Property (VBScript)
See Also
CollapseAll image DropDown image

Returns or sets the name of the object or application that originally generated the error.

object.Source [= stringexpression]

Expand image Arguments

object

Always the Err object.

stringexpression

A string expression representing the application that generated the error.

Expand image 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.

CopyCode image Copy Code
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.

Expand image Requirements

Version 1

Applies To: Err Object (VBScript)

Expand image See Also

Reference

Description Property (VBScript)
HelpContext Property
HelpFile Property (VBScript)
Number Property (VBScript)
On Error Statement

Concepts

Err Object (VBScript)


Value Property (VBScript)

Visual Basic Scripting Edition
Value Property (VBScript)
See Also
CollapseAll image DropDown image

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

object.Value

Expand image Arguments

The object argument is always a Match object.

Expand image Remarks

The following code illustrates the use of the Value property.

CopyCode image Copy Code
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"))

Expand image Requirements

Version 5

Applies To: Match Object

Expand image See Also

Reference

FirstIndex Property
Length Property


Statements (VBScript)

Visual Basic Scripting Edition
Statements (VBScript)
See Also
DropDown image

The following table lists statements in VBScript.

Statements

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 | Stop Statement
Sub Statement | While...Wend Statement
With Statement |

See Also

Other Resources

VBScript Language Reference


Call Statement

Visual Basic Scripting Edition
Call Statement
CollapseAll image DropDown image

Transfers control to a Sub or Function procedure.

[Call] name [argumentlist]

Expand image 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.

Expand image 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.

CopyCode image Copy Code
        Call MyFunction("Hello World")
Function MyFunction(text)
   MsgBox text
End Function

Expand image Requirements

Version 1


Class Statement (VBScript)

Visual Basic Scripting Edition
Class Statement (VBScript)
See Also
CollapseAll image DropDown image

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

Expand image 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.

Expand image 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.

Expand image Requirements

Version 5

Expand image See Also

Reference

Dim Statement
Function Statement (VBScript)
Private Statement
Property Get Statement
Property Let Statement
Property Set Statement
Public Statement
Set Statement
Sub Statement


Const Statement (VBScript)

Visual Basic Scripting Edition
Const Statement (VBScript)
See Also
CollapseAll image DropDown image

Declares constants for use in place of literal values.

[Public | Private] Const constname = expression

Expand image 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.

Expand image 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:

CopyCode image Copy Code
        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 Note

Constants can make your scripts self-documenting and easy to modify. Unlike variables, constants cannot be inadvertently changed while your script is running.

Expand image Requirements

Version 5

Expand image See Also

Reference

Dim Statement
Function Statement (VBScript)
Private Statement
Public Statement
Sub Statement


Dim Statement

Visual Basic Scripting Edition
Dim Statement
See Also
CollapseAll image DropDown image

Declares variables and allocates storage space.

Dim varname[([subscripts])][, varname[([subscripts])]] . . .

Expand image 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.

Expand image 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 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:

CopyCode image Copy Code
        Dim Names(9)       ' Declare an array with 10 elements.
Dim Names()        ' Declare a dynamic array.
Dim MyVar, MyNum   ' Declare two variables.

Expand image Requirements

Version 1

Expand image See Also

Reference

Private Statement
Public Statement
ReDim Statement
Set Statement
Array Function
IsArray Function
LBound Function
UBound Function
Private Statement
Public Statement
Erase Statement


Do...Loop Statement

Visual Basic Scripting Edition
Do...Loop Statement
See Also
CollapseAll image DropDown image

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 use this syntax
Do
   [statements]
   [Exit Do]
   [statements]
Loop [{While | Until} condition]

Expand image 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.

Expand image 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:

CopyCode image Copy Code
        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.

Expand image Requirements

Version 1

Expand image See Also

Reference

Exit Statement
For...Next Statement
While...Wend Statement


Erase Statement

Visual Basic Scripting Edition
Erase Statement
See Also
CollapseAll image DropDown image

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

Erase array

Expand image Arguments

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

Expand image 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 | Effect of Erase on fixed-array elements
Fixed numeric array | Sets each element to zero.
Fixed string array | Sets each element to zero-length ("").
Array of objects | 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.

CopyCode image Copy Code
Dim NumArray(9)
Dim DynamicArray()
ReDim DynamicArray(9)   ' Allocate storage space.
Erase NumArray   ' Each element is reinitialized.
Erase DynamicArray   ' Free memory used by array.

Expand image Requirements

Version 1

Expand image See Also

Reference

Dim Statement
ReDim Statement
Array Function
IsArray Function
LBound Function
UBound Function
Private Statement
Public Statement

Concepts

Nothing Keyword


Execute Statement

Visual Basic Scripting Edition
Execute Statement
See Also
CollapseAll image DropDown image

Executes one or more specified statements.

Execute statement

Expand image Arguments

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.

Expand image 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 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:

CopyCode image Copy Code
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:

CopyCode image Copy Code
S = "Sub Proc2" & vbCrLf
S = S & "   Print X" & vbCrLf
S = S & "End Sub"
Execute S

Expand image Requirements

Version 5

Expand image See Also

Reference

Eval Function
ExecuteGlobal Statement


ExecuteGlobal Statement

Visual Basic Scripting Edition
ExecuteGlobal Statement
CollapseAll image DropDown image

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

ExecuteGlobal statement

Expand image Arguments

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.

Expand image 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 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:

CopyCode image Copy Code
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:

CopyCode image Copy Code
S = "Sub Proc2" & vbCrLf
S = S & "  Print X" & vbCrLf
S = S & "End Sub"
ExecuteGlobal S

Expand image Requirements

Version 5


Exit Statement

Visual Basic Scripting Edition
Exit Statement
See Also
CollapseAll image DropDown image

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

Exit Do
Exit For
Exit Function
Exit Property
Exit Sub

Expand image Remarks

The Exit statement syntax has these forms:

Statement | Description
Exit Do | 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.
Exit For | 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 | Immediately exits the Function procedure in which it appears. Execution continues with the statement following the statement that called the Function.
Exit Property | Immediately exits the Property procedure in which it appears. Execution continues with the statement following the statement that called the Property procedure.
Exit Sub | 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:

CopyCode image Copy Code
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

Expand image Requirements

Version 1

Expand image See Also

Reference

Do...Loop Statement
For Each...Next Statement
For...Next Statement
Function Statement (VBScript)
Sub Statement


For Each...Next Statement

Visual Basic Scripting Edition
For Each...Next Statement
See Also
CollapseAll image DropDown image

Repeats a group of statements for each element in an array or collection.

For Each element In group
   [statements]
   [Exit For]
   [statements]
Next [element]

Expand image 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.

Expand image 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 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:

CopyCode image Copy Code
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

Expand image Requirements

Version 2

Expand image See Also

Reference

Do...Loop Statement
Exit Statement
For...Next Statement
While...Wend Statement


For...Next Statement

Visual Basic Scripting Edition
For...Next Statement
See Also
CollapseAll image DropDown image

Repeats a group of statements a specified number of times.

For counter = start To end [Step step]
    [statements]
    [Exit For]
    [statements]
Next

Expand image 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.

Expand image Remarks

The step argument can be either positive or negative. The value of the step argument determines loop processing as follows:

Value | Loop executes if
Positive or 0 | counter <= end
Negative | 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 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:

CopyCode image Copy Code
        For I = 1 To 10
      For J = 1 To 10
            For K = 1 To 10
            . . .
            Next
      Next
Next

Expand image Requirements

Version 1

Expand image See Also

Reference

Do...Loop Statement
Exit Statement
For Each...Next Statement
While...Wend Statement


Function Statement (VBScript)

Visual Basic Scripting Edition
Function Statement (VBScript)
See Also
CollapseAll image DropDown image

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

Expand image 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[( )]

Expand image 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.

Expand image 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 note 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.

CopyCode image Copy Code
        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 note 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 note 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.

Expand image Requirements

Version 1

Expand image See Also

Reference

Call Statement
Dim Statement
Exit Statement
Set Statement
Sub Statement

Concepts

Nothing Keyword


If...Then...Else Statement

Visual Basic Scripting Edition
If...Then...Else Statement
CollapseAll image DropDown image

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

Expand image 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.

Expand image 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 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:

CopyCode image Copy Code
        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.

Expand image Requirements

Version 1


On Error Statement

Visual Basic Scripting Edition
On Error Statement
See Also
CollapseAll image DropDown image

Enables or disables error-handling.

On Error Resume Next
On Error GoTo 0

Expand image 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.

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

Expand image Requirements

Version 1

Expand image See Also

Reference

Exit Statement

Concepts

Err Object (VBScript)


Option Explicit Statement

Visual Basic Scripting Edition
Option Explicit Statement
CollapseAll image DropDown image

Forces explicit declaration of all variables in a script.

Option Explicit

Expand image 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.

Note 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.

CopyCode image Copy Code
        Option Explicit   ' Force explicit variable declaration.
Dim MyVar   ' Declare variable.
MyInt = 10   ' Undeclared variable generates error.
MyVar = 10   ' Declared variable does not generate error.

Expand image Requirements

Version 1


Private Statement

Visual Basic Scripting Edition
Private Statement
See Also
CollapseAll image DropDown image

Declares private variables and allocates storage space. Declares, in a Class block, a private variable.

Private varname[([subscripts])][, varname[([subscripts])]] . . .

Expand image 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.

Expand image 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 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.

CopyCode image Copy Code
        Private MyNumber   ' Private Variant variable.
Private MyArray(9)   ' Private array variable.
   ' Multiple Private declarations of Variant variables.
Private MyNumber, MyVar, YourNumber

Expand image Requirements

Version 1

Expand image See Also

Reference

Dim Statement
Public Statement
ReDim Statement
Set Statement
Array Function
IsArray Function
LBound Function
UBound Function
Erase Statement


Property Get Statement

Visual Basic Scripting Edition
Property Get Statement
See Also
CollapseAll image DropDown image

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

Expand image 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.

Expand image 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.

Expand image Requirements

Version 5

Expand image See Also

Reference

Class Statement (VBScript)
Dim Statement
Exit Statement
Function Statement (VBScript)
Private Statement
Property Let Statement
Property Set Statement
Public Statement
Set Statement
Sub Statement


Property Let Statement

Visual Basic Scripting Edition
Property Let Statement
See Also
CollapseAll image DropDown image

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

Expand image 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.

Expand image 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 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.

Expand image Requirements

Version 5

Expand image See Also

Reference

Class Statement (VBScript)
Dim Statement
Exit Statement
Function Statement (VBScript)
Private Statement
Property Get Statement
Property Set Statement
Public Statement
Set Statement
Sub Statement


Property Set Statement

Visual Basic Scripting Edition
Property Set Statement
See Also
CollapseAll image DropDown image

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

Expand image 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.

Expand image 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 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).

Expand image Requirements

Version 5

Expand image See Also

Reference

Class Statement (VBScript)
Dim Statement
Exit Statement
Function Statement (VBScript)
Private Statement
Property Get Statement
Property Let Statement
Public Statement
Set Statement
Sub Statement


Public Statement

Visual Basic Scripting Edition
Public Statement
See Also
CollapseAll image DropDown image

Declares public variables and allocates storage space. Declares, in a Class block, a public variable.

Public varname[([subscripts])][, varname[([subscripts])]] . . .

Expand image 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.

Expand image 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

Expand image Requirements

Version 1

Expand image See Also

Reference

Dim Statement
Private Statement
ReDim Statement
Set Statement
Array Function
IsArray Function
LBound Function
UBound Function
Erase Statement


Randomize Statement

Visual Basic Scripting Edition
Randomize Statement
See Also
CollapseAll image DropDown image

Initializes the random-number generator.

Randomize [number]

Expand image Arguments

The number argument can be any valid numeric expression.

Expand image 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 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.

CopyCode image Copy Code
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

Expand image Requirements

Version 1

Expand image See Also

Reference

Rnd Function
Timer Function


ReDim Statement

Visual Basic Scripting Edition
ReDim Statement
See Also
CollapseAll image DropDown image

Declares dynamic-array variables, and allocates or reallocates storage space at procedure level.

ReDim [Preserve] varname(subscripts) [, varname(subscripts)] . . .

Expand image 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.

Expand image 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.

CopyCode image Copy Code
        ReDim X(10, 10, 10)
. . .
ReDim Preserve X(10, 10, 15)
Caution note 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.

Expand image Requirements

Version 1

Expand image See Also

Reference

Dim Statement
Set Statement
Array Function
IsArray Function
LBound Function
UBound Function
Private Statement
Public Statement
Erase Statement


Rem Statement

Visual Basic Scripting Edition
Rem Statement
CollapseAll image DropDown image

Includes explanatory remarks in a program.

Rem comment
' or
' comment

Expand image Arguments

The comment argument is the text of any comment you want to include. After the Rem keyword, a space is required before comment.

Expand image 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.

CopyCode image Copy Code
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.

Expand image Requirements

Version 1


Select Case Statement

Visual Basic Scripting Edition
Select Case Statement
See Also
CollapseAll image DropDown image

Executes one of several groups of statements, depending on the value of an expression.

Select Case testexpression
   [Case expressionlist-n
      [statements-n]] . . .
   [Case Else
      [elsestatements-n]]
End Select

Expand image Arguments

testexpression

Any numeric or string expression.

expressionlist-n

Required if Case appears. A comma 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.

Expand image 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.

CopyCode image Copy Code
Dim Color, MyVar
Sub ChangeBackground (Color)
   MyVar = lcase (Color)
   Select Case MyVar
      Case "red"     document.bgColor = "red"
      Case "green"   document.bgColor = "green"
      Case "blue"    document.bgColor = "blue"
      Case Else      MsgBox "pick another color"
   End Select
End Sub

Expand image Requirements

Version 1

Expand image See Also

Reference

If...Then...Else Statement


Set Statement

Visual Basic Scripting Edition
Set Statement
See Also
CollapseAll image DropDown image

Assigns an object reference to a variable or property, or associates a procedure reference with an event.

Set objectvar = {objectexpression | New classname | Nothing}
' or
Set 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.

Expand image 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.

CopyCode image Copy Code
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.

Expand image Requirements

Version 1

Expand image See Also

Reference

Assignment Operator (=) (VBScript)
Dim Statement
GetRef Function
ReDim Statement


Stop Statement

Visual Basic Scripting Edition
Stop Statement
See Also Example
CollapseAll image DropDown image

Suspends execution.

Stop

Expand image Remarks

You can place Stop statements anywhere in procedures to suspend execution. Using the Stop statement is similar to setting a breakpoint in the code.

The Stop statement suspends execution, but it does not close any files or clear any variables.

Note Note

The Stop statement has no effect unless the script is being debugged.

Expand image Example

This example uses the Stop statement to suspend execution for each iteration through the For...Next loop.

Note Note

To run this example, you must have a script debugger installed and the script must run in debug mode. For more information, search MSDN (http://msdn.microsoft.com) for the title "Introducing Microsoft Script Debugger"
CopyCode image Copy Code
For i = 1 To 5
   ' Print i to the Output window.
   Debug.Write "loop index is " & i
   ' Wait for user to resume.
   Stop
Next

Expand image Requirements

Version 3

Expand image See Also

Reference

Write Method

Concepts

Debug Object


Sub Statement

Visual Basic Scripting Edition
Sub Statement
See Also
CollapseAll image DropDown image

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

Expand image 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[( )]

Expand image 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.

Expand image 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 note Caution

Sub procedures 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 note 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.

Expand image Requirements

Version 1

Expand image See Also

Reference

Call Statement
Dim Statement
Exit Statement
Function Statement (VBScript)


While...Wend Statement

Visual Basic Scripting Edition
While...Wend Statement
See Also
CollapseAll image DropDown image

Executes a series of statements as long as a given condition is True.

While condition
   Version [statements]
Wend

Expand image 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.

Expand image 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 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:

CopyCode image Copy Code
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.

Expand image Requirements

Version 1

Expand image See Also

Reference

Do...Loop Statement


With Statement (VBScript)

Visual Basic Scripting Edition
With Statement (VBScript)
See Also
CollapseAll image DropDown image

Executes a series of statements on a single object.

With object
      statements
End With

Expand image 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.

Expand image 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.

CopyCode image Copy Code
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 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.

Expand image Requirements

Version 5

Expand image See Also

Reference

Set Statement


Script Runtime

Scripting Runtime Library
Script Runtime
DropDown image

These sections describe the components of script runtime.

In This Section

Dictionary Object

Explains the concept of the Dictionary object and links to its methods and properties.

FileSystemObject Object

Links to the FileSystemObject basics and FileSystemObject reference sections.

Script Encoder

Provides an overview of the Script Encoder command-line tool and links to topics that explain how to use it.

Related Sections

Script Encoding Sample

Provides a short script encoding example.

FileSystemObject Sample Code

Includes sample code that provides a real-world example that demonstrates many of the features available in the FileSystemObject object model.


Dictionary Object

Scripting Runtime Library
Dictionary Object
See Also
CollapseAll image DropDown image

Object that stores data key, item pairs.

Expand image 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 an integer or a string, but can be anything except an array.

The following code illustrates how to create a Dictionary object:

JScript CopyCode image Copy Code
var y = new ActiveXObject("Scripting.Dictionary");
y.add ("a", "test");
if (y.Exists("a"))
   document.write("true");
...
Visual Basic Script CopyCode image Copy Code
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"
...

Expand image Methods

Add Method (Dictionary) | Exists Method | Items Method | Keys Method | Remove Method | RemoveAll Method

Expand image Properties

Count Property | Item Property | Key Property | CompareMode Property

Expand image See Also

Reference

FileSystemObject Object
TextStream Object


CompareMode Property

Scripting Runtime Library
CompareMode Property
See Also
CollapseAll image DropDown image

Sets and returns the comparison mode for comparing string keys in a Dictionary object.

object.CompareMode[ = compare]

Expand image 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).

Expand image 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 CopyCode image Copy Code
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));
}
Visual Basic Script CopyCode image Copy Code
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.

Applies To:

Dictionary Object

Expand image See Also

Reference

Key Property


Item Property (Script Runtime)

Scripting Runtime Library
Item Property (Script Runtime)
See Also
CollapseAll image DropDown image

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]

Expand image 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.

Expand image 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 CopyCode image Copy Code
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);
}
Visual Basic Script CopyCode image Copy Code
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

Applies To:

Dictionary Object| Drives Collection| Files Collection| Folders Collection

Expand image See Also

Reference

CompareMode Property
Count Property (Script Runtime)
Key Property


Key Property

Scripting Runtime Library
Key Property
See Also
CollapseAll image DropDown image

Sets a key in a Dictionary object.

object.Key(key) = newkey

Expand image 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.

Expand image 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 CopyCode image Copy Code
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);
}
Visual Basic Script CopyCode image Copy Code
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

Applies To:

Dictionary Object

Expand image See Also

Reference

CompareMode Property
Count Property (Script Runtime)
Item Property (Script Runtime)


Add Method (Script Runtime)

Scripting Runtime Library
Add Method (Script Runtime)
See Also
CollapseAll image DropDown image

Adds a key and item pair to a Dictionary object.

object.Add (key, item)

Expand image 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.

Expand image Remarks

An error occurs if the key already exists.

The following example illustrates the use of the Add method.

JScript CopyCode image Copy Code
var d;
d = new ActiveXObject("Scripting.Dictionary");
d.Add("a", "Athens");
d.Add("b", "Belgrade");
d.Add("c", "Cairo");
Visual Basic Script CopyCode image Copy Code
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"

Applies To:

Dictionary Object

Expand image See Also

Reference

Add Method (Folders)
Exists Method (Script Runtime)
Items Method
Keys Method
Remove Method (Script Runtime)
RemoveAll Method


Exists Method (Script Runtime)

Scripting Runtime Library
Exists Method (Script Runtime)
See Also
CollapseAll image DropDown image

Returns true if a specified key exists in the Dictionary object, false if it does not.

object.Exists(key)

Expand image Arguments

object

Required. Always the name of a Dictionary object.

key

Required. Key value being searched for in the Dictionary object.

Expand image Remarks

The following example illustrates the use of the Exists method.

JScript CopyCode image Copy Code
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);
}
Visual Basic Script CopyCode image Copy Code
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

Applies To:

Dictionary Object

Expand image See Also

Reference

Add Method (Script Runtime)
Items Method
Keys Method
Remove Method (Script Runtime)
RemoveAll Method


Items Method

Scripting Runtime Library
Items Method
See Also
CollapseAll image DropDown image

Returns an array containing all the items in a Dictionary object.

object.Items( )

Expand image Remarks

The object is always the name of a Dictionary object.

The following code illustrates use of the Items method:

JScript CopyCode image Copy Code
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.
}
Visual Basic Script CopyCode image Copy Code
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

Applies To:

Dictionary Object

Expand image See Also

Reference

Add Method (Script Runtime)
Exists Method (Script Runtime)
Keys Method
Remove Method (Script Runtime)
RemoveAll Method


Keys Method

Scripting Runtime Library
Keys Method
See Also
CollapseAll image DropDown image

Returns an array containing all existing keys in a Dictionary object.

object.Keys( )

Expand image Remarks

The object is always the name of a Dictionary object.

The following code illustrates use of the Keys method:

JScript CopyCode image Copy Code
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.
}
Visual Basic Script CopyCode image Copy Code
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

Applies To:

Dictionary Object

Expand image See Also

Reference

Add Method (Script Runtime)
Exists Method (Script Runtime)
Items Method
Remove Method (Script Runtime)
RemoveAll Method


Remove Method (Script Runtime)

Scripting Runtime Library
Remove Method (Script Runtime)
See Also
CollapseAll image DropDown image

Removes a key, item pair from a Dictionary object.

object.Remove(key)

Expand image 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.

Expand image Remarks

An error occurs if the specified key, item pair does not exist.

The following code illustrates use of the Remove method:

JScript CopyCode image Copy Code
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.
Visual Basic Script CopyCode image Copy Code
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.

Applies To:

Dictionary Object

Expand image See Also

Reference

Add Method (Script Runtime)
Exists Method (Script Runtime)
Items Method
Keys Method
RemoveAll Method


RemoveAll Method

Scripting Runtime Library
RemoveAll Method
See Also
CollapseAll image DropDown image

The RemoveAll method removes all key, item pairs from a Dictionary object.

object.RemoveAll( )

Expand image Remarks

The object is always the name of a Dictionary object.

The following code illustrates use of the RemoveAll method:

JScript CopyCode image Copy Code
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.
Visual Basic Script CopyCode image Copy Code
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.

Applies To:

Dictionary Object

Expand image See Also

Reference

Add Method (Script Runtime)
Exists Method (Script Runtime)
Items Method
Keys Method
Remove Method (Script Runtime)


FileSystemObject

Scripting Runtime Library
FileSystemObject
DropDown image

The following sections explain the concept of the FileSystemObject and how to use it.

In This Section

FileSystemObject Basics

A guide to the fundamentals of the FileSystemObject.

Reference

List of elements that comprise Scripting Run-Time Reference.


FileSystemObject Basics

Scripting Runtime Library
FileSystemObject Basics
DropDown image

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.


The FileSystemObject Object Model

Scripting Runtime Library
The FileSystemObject Object Model
DropDown image

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.

When To Use

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 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.


FileSystemObject Objects

Scripting Runtime Library
FileSystemObject Objects
DropDown image

The FileSystemObject (FSO) object model contains the following objects and collections.

Objects and Collections

Object/Collection | Description
FileSystemObject | 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.
Drive | 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.
Drives | Collection. Provides a list of the drives attached to the system, either physically or logically. The Drives collection includes all drives, regardless of type. Removable-media drives need not have media inserted for them to appear in this collection.
File | 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.
Files | Collection. Provides a list of all files contained within a folder.
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.
Folders | Collection. Provides a list of all the folders within a Folder.
TextStream | Object. Allows you to read and write text files.


Programming the FileSystemObject

Scripting Runtime Library
Programming the FileSystemObject
DropDown image

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:

Visual Basic Script CopyCode image Copy Code
Dim fso
Set fso = CreateObject("Scripting.FileSystemObject")
JScript CopyCode image Copy Code
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 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:

Visual Basic Script CopyCode image Copy Code
Dim fso, f1
Set fso = CreateObject("Scripting.FileSystemObject")
Set f1 = fso.GetFile("c:\test.txt")
JScript CopyCode image Copy Code
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:

Visual Basic Script CopyCode image Copy Code
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 CopyCode image Copy Code
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:

Visual Basic Script CopyCode image Copy Code
Set fldr = fso.GetFolder("c:\")
JScript CopyCode image Copy Code
var fldr = fso.GetFolder("c:\\");

Now that you have a handle to a Folder object, you can check its Name property.

Visual Basic Script CopyCode image Copy Code
Response.Write "Folder name is: " & fldr.Name
JScript CopyCode image Copy Code
Response.Write("Folder name is: " + fldr.Name);

To find out the last time a file was modified, use the following syntax:

Visual Basic Script CopyCode image Copy Code
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 CopyCode image Copy Code
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);


Working with Drives and Folders

Scripting Runtime Library
Working with Drives and Folders
DropDown image

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)

For more information, see FileSystemObject Sample Code.

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:

Visual Basic Script CopyCode image Copy Code
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 CopyCode image Copy Code
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

For more information, see FileSystemObject Sample Code.

The following example demonstrates how to use the Folder and FileSystemObject objects to manipulate folders and gain information about them.

Visual Basic Script CopyCode image Copy Code
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 CopyCode image Copy Code
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>");
}


Working with Files

Scripting Runtime Library
Working with Files
DropDown image

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.

Visual Basic Script CopyCode image Copy Code
Dim fso, f1
Set fso = CreateObject("Scripting.FileSystemObject")
Set f1 = fso.CreateTextFile("c:\testfile.txt", True)
JScript CopyCode image Copy Code
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.

Visual Basic Script CopyCode image Copy Code
Dim fso, ts
Const ForWriting = 2
Set fso = CreateObject("Scripting. FileSystemObject")
Set ts = fso.OpenTextFile("c:\test.txt", ForWriting, True)
JScript CopyCode image Copy Code
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.

Visual Basic Script CopyCode image Copy Code
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 CopyCode image Copy Code
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 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:

Visual Basic Script CopyCode image Copy Code
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 CopyCode image Copy Code
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:

Visual Basic Script CopyCode image Copy Code
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 CopyCode image Copy Code
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 | Method
Move a file | File.Move or FileSystemObject.MoveFile
Copy a file | File.Copy or FileSystemObject.CopyFile
Delete a file | 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:

Visual Basic Script CopyCode image Copy Code
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 CopyCode image Copy Code
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!");
}


FileSystemObject Sample Code

Scripting Runtime Library
FileSystemObject Sample Code
DropDown image

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.

How to Use the 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:

Visual Basic Script CopyCode image Copy 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:

Visual Basic Script CopyCode image Copy Code
Sub Print(x)
   WScript.Echo x
End Sub
Main

The code is contained in the following section:

Visual Basic Script CopyCode image Copy Code
''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
' 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 = 1024
Const FileAttrCompressed = 2048

''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
' 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 Attr And FileAttrDirectory Then S = S & "Directory "
   If Attr And FileAttrReadOnly Then S = S & "Read-Only "
   If Attr And FileAttrHidden Then S = S & "Hidden "
   If Attr And FileAttrSystem Then S = S & "System "
   If Attr And FileAttrVolume Then S = S & "Volume "
   If Attr And FileAttrArchive Then S = S & "Archive "
   If Attr And FileAttrAlias Then S = S & "Alias "
   If Attr And 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

   ' Construct 1st line of report.
   S = S & String(2, TabStop) & "Drive"
   S = S & String(3, TabStop) & "File"
   S = S & TabStop & "Total"
   S = S & TabStop & "Free"
   S = S & TabStop & "Available"
   S = S & TabStop & "Serial" & NewLine

   ' Construct 2nd line of report.
   S = S & "Letter"
   S = S & TabStop & "Path"
   S = S & TabStop & "Type"
   S = S & TabStop & "Ready?"
   S = S & TabStop & "Name"
   S = S & TabStop & "System"
   S = S & TabStop & "Space"
   S = S & TabStop & "Space"
   S = S & TabStop & "Space"
   S = S & TabStop & "Number" & NewLine

   ' Separator line.
   S = S & String(105, "-") & NewLine

   For Each Drive In Drives
      S = S & Drive.DriveLetter
      S = S & TabStop & Drive.Path
      S = S & TabStop & ShowDriveType(Drive)
      S = S & 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 = NewLine & "Path:" & TabStop & File.Path
   S = S & NewLine & "Name:" & TabStop & File.Name
   S = S & NewLine & "Type:" & TabStop & File.Type
   S = S & NewLine & "Attribs:" & TabStop & ShowFileAttr(File)
   S = S & NewLine & "Created:" & TabStop & File.DateCreated
   S = S & NewLine & "Accessed:" & TabStop & File.DateLastAccessed
   S = S & NewLine & "Modified:" & TabStop & File.DateLastModified
   S = 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 & NewLine & "Created:" & TabStop & Folder.DateCreated
   S = S & NewLine & "Accessed:" & TabStop & Folder.DateLastAccessed
   S = S & NewLine & "Modified:" & TabStop & Folder.DateLastModified
   S = S & NewLine & "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 S
   Dim SubFolders
   Dim SubFolder
   Dim Files
   Dim 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
   <A NAME="driveinfo"></A>
   ' 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
   <A NAME="deletefile"></A>
   Set TextStream = Folder.CreateTextFile("OctopusGarden.txt")
   <A NAME="createtextfilewritetofile"></A>
   ' 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)
   <A NAME="closereadfromfile"></A>
   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 TestFolder
   Dim SubFolders
   Dim SubFolder
   Dim 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)
   <A NAME="folderinfo"></A>
   Set FSO = CreateObject("Scripting.FileSystemObject")

   If Not BuildTestDirectory(FSO) Then
      Print "Test directory already exists or cannot be created.   Cannot continue."
      Exit Sub
   End If

   Print GenerateDriveInformation(FSO) & NewLine & NewLine
   Print GenerateTestInformation(FSO) & NewLine & NewLine
   Print GetLyrics(FSO) & NewLine & NewLine
   DeleteTestDirectory(FSO)

End Sub


Scripting Run-Time Reference

Scripting Runtime Library
Scripting Run-Time Reference
DropDown image

The following sections include information about scripting run-time properties, methods, objects, and collections.

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 Sections

FileSystemObject Basics

A guide to the fundamentals of the FileSystemObject.


FileSystemObject Properties

Scripting Runtime Library
FileSystemObject Properties
DropDown image

The following sections provide details about the 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.


AtEndOfLine Property (FileSystemObject)

Scripting Runtime Library
AtEndOfLine Property (FileSystemObject)
See Also
CollapseAll image DropDown image

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

Expand image Remarks

The object is always the name of a TextStream object.

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 CopyCode image Copy Code
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);
}
Visual Basic Script CopyCode image Copy Code
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

Applies To:

TextStream Object

Expand image See Also

Reference

AtEndOfStream Property (FileSystemObject)


AtEndOfStream Property (FileSystemObject)

Scripting Runtime Library
AtEndOfStream Property (FileSystemObject)
See Also
CollapseAll image DropDown image

Returns true if the file pointer is at the end of a TextStream file; false if it is not. Read-only.

object.AtEndOfStream

Expand image Remarks

The object is always the name of a TextStream object.

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 CopyCode image Copy Code
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);
}
Visual Basic Script CopyCode image Copy Code
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

Applies To:

TextStream Object

Expand image See Also

Reference

AtEndOfLine Property (FileSystemObject)


Attributes Property

Scripting Runtime Library
Attributes Property
See Also
CollapseAll image DropDown image

Sets or returns the attributes of files or folders. Read/write or read-only, depending on the attribute.

object.Attributes [= newattributes]

Expand image 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.

Expand image Settings

The newattributes argument can have any of the following values or any logical combination of the following values:

Constant | Value | Description
Normal | 0 | Normal file. No attributes are set.
ReadOnly | 1 | Read-only file. Attribute is read/write.
Hidden | 2 | Hidden file. Attribute is read/write.
System | 4 | System file. Attribute is read/write.
Volume | 8 | Disk drive volume label. Attribute is read-only.
Directory | 16 | Folder or directory. Attribute is read-only.
Archive | 32 | File has changed since last backup. Attribute is read/write.
Alias | 1024 | Link or shortcut. Attribute is read-only.
Compressed | 2048 | Compressed file. Attribute is read-only.

Expand image Remarks

The following code illustrates the use of the Attributes property with a file:

JScript CopyCode image Copy Code
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);
}
Visual Basic Script CopyCode image Copy Code
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

Applies To:

File Object| Folder Object

Expand image See Also

Reference

DateCreated Property
DateLastAccessed Property
DateLastModified Property
Drive Property
Files Property (FileSystemObject)
IsRootFolder Property
Name Property (FileSystemObject)
ParentFolder Property
Path Property (FileSystemObject)
ShortName Property
ShortPath Property
Size Property
SubFolders Property
Type Property


AvailableSpace Property

Scripting Runtime Library
AvailableSpace Property
See Also
CollapseAll image DropDown image

Returns the amount of space available to a user on the specified drive or network share.

object.AvailableSpace

Expand image Remarks

The object is always a Drive object.

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 CopyCode image Copy Code
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);
}
Visual Basic Script CopyCode image Copy Code
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

Applies To:

Drive Object

Expand image See Also

Reference

DriveLetter Property
DriveType Property
FileSystem Property
FreeSpace Property
IsReady Property
Path Property (FileSystemObject)
RootFolder Property
SerialNumber Property
ShareName Property
TotalSize Property
VolumeName Property


Column Property (FileSystemObject)

Scripting Runtime Library
Column Property (FileSystemObject)
See Also
CollapseAll image DropDown image

Read-only property that returns the column number of the current character position in a TextStream file.

object.Column

Expand image Remarks

The object is always the name of a TextStream object.

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 CopyCode image Copy Code
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);
}
Visual Basic Script CopyCode image Copy Code
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

Applies To:

TextStream Object

Expand image See Also

Reference

Line Property (FileSystemObject)


Count Property (Script Runtime)

Scripting Runtime Library
Count Property (Script Runtime)
See Also
CollapseAll image DropDown image

Returns the number of items in a collection or Dictionary object. Read-only.

object.Count

Expand image Remarks

The object is always the name of one of the items in the Applies To list.

The following code illustrates use of the Count property:

JScript CopyCode image Copy Code
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.
}
Visual Basic Script CopyCode image Copy Code
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

Applies To:

Dictionary Object| Drives Collection| Files Collection| Folders Collection

Expand image See Also

Reference

CompareMode Property
Item Property (Script Runtime)
Key Property


DateCreated Property

Scripting Runtime Library
DateCreated Property
See Also
CollapseAll image DropDown image

Returns the date and time that the specified file or folder was created. Read-only.

object.DateCreated

Expand image Remarks

The object is always a File or Folder object.

The following code illustrates the use of the DateCreated property with a file:

JScript CopyCode image Copy Code
function ShowFileInfo(filespec)
{
   var fso, f, s;
   fso = new ActiveXObject("Scripting.FileSystemObject");
   f = fso.GetFile(filespec);
   s = "Created: " + f.DateCreated;
   return(s);
}
Visual Basic Script CopyCode image Copy Code
Function ShowFileInfo(filespec)
   Dim fso, f
   Set fso = CreateObject("Scripting.FileSystemObject")
   Set f = fso.GetFile(filespec)
   ShowFileInfo = "Created: " & f.DateCreated
End Function

Applies To:

File Object| Folder Object

Expand image See Also

Reference

Attributes Property
DateLastAccessed Property
DateLastModified Property
Drive Property
Files Property (FileSystemObject)
IsRootFolder Property
Name Property (FileSystemObject)
ParentFolder Property
Path Property (FileSystemObject)
ShortName Property
ShortPath Property
Size Property
SubFolders Property
Type Property


DateLastAccessed Property

Scripting Runtime Library
DateLastAccessed Property
See Also
CollapseAll image DropDown image

Returns the date and time that the specified file or folder was last accessed. Read-only.

object.DateLastAccessed

Expand image Remarks

The object is always a File or Folder object.

The following code illustrates the use of the DateLastAccessed property with a file:

JScript CopyCode image Copy Code
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);
}
Visual Basic Script CopyCode image Copy Code
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 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.

Applies To:

File Object| Folder Object

Expand image See Also

Reference

Attributes Property
DateCreated Property
DateLastModified Property
Drive Property
Files Property (FileSystemObject)
IsRootFolder Property
Name Property (FileSystemObject)
ParentFolder Property
Path Property (FileSystemObject)
ShortName Property
ShortPath Property
Size Property
SubFolders Property
Type Property


DateLastModified Property

Scripting Runtime Library
DateLastModified Property
See Also
CollapseAll image DropDown image

Returns the date and time that the specified file or folder was last modified. Read-only.

object.DateLastModified

Expand image Remarks

The object is always a File or Folder object.

The following code illustrates the use of the DateLastModified property with a file:

JScript CopyCode image Copy Code
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);
}
Visual Basic Script CopyCode image Copy Code
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

Applies To:

File Object| Folder Object

Expand image See Also

Reference

Attributes Property
DateCreated Property
DateLastAccessed Property
Drive Property
Files Property (FileSystemObject)
IsRootFolder Property
Name Property (FileSystemObject)
ParentFolder Property
Path Property (FileSystemObject)
ShortName Property
ShortPath Property
Size Property
SubFolders Property
Type Property


Drive Property

Scripting Runtime Library
Drive Property
See Also
CollapseAll image DropDown image

Returns the drive letter of the drive on which the specified file or folder resides. Read-only.

object.Drive

Expand image Remarks

The object is always a File or Folder object.

The following code illustrates the use of the Drive property:

JScript CopyCode image Copy Code
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);
}
Visual Basic Script CopyCode image Copy Code
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

Applies To:

File Object| Folder Object

Expand image See Also

Reference

Attributes Property
DateCreated Property
DateLastAccessed Property
DateLastModified Property
Files Property (FileSystemObject)
IsRootFolder Property
Name Property (FileSystemObject)
ParentFolder Property
Path Property (FileSystemObject)
ShortName Property
ShortPath Property
Size Property
SubFolders Property
Type Property


DriveLetter Property

Scripting Runtime Library
DriveLetter Property
See Also
CollapseAll image DropDown image

Returns the drive letter of a physical local drive or a network share. Read-only.

object.DriveLetter

Expand image Remarks

The object is always a Drive object.

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 CopyCode image Copy Code
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);
}
Visual Basic Script CopyCode image Copy Code
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

Applies To:

Drive Object

Expand image See Also

Reference

AvailableSpace Property
DriveType Property
FileSystem Property
FreeSpace Property
IsReady Property
Path Property (FileSystemObject)
RootFolder Property
SerialNumber Property
ShareName Property
TotalSize Property
VolumeName Property


Drives Property

Scripting Runtime Library
Drives Property
See Also
CollapseAll image DropDown image

Returns a Drives collection consisting of all Drive objects available on the local machine.

object.Drives

Expand image Remarks

The object is always a FileSystemObject.

Removable-media drives need not have media inserted for them to appear in the Drives collection.

You can iterate the members of the Drives collection as illustrated in the following code:

JScript CopyCode image Copy Code
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);
}
Visual Basic Script CopyCode image Copy Code
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

Applies To:

FileSystemObject Object

Expand image See Also

Reference

Drives Collection
Files Property (FileSystemObject)
SubFolders Property


DriveType Property

Scripting Runtime Library
DriveType Property
See Also
CollapseAll image DropDown image

Returns a value indicating the type of a specified drive.

object.DriveType

Expand image Remarks

The object is always a Drive object.

The following code illustrates the use of the DriveType property:

JScript CopyCode image Copy Code
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);
}
Visual Basic Script CopyCode image Copy Code
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

Applies To:

Drive Object

Expand image See Also

Reference

AvailableSpace Property
DriveLetter Property
FileSystem Property
FreeSpace Property
IsReady Property
Path Property (FileSystemObject)
RootFolder Property
SerialNumber Property
ShareName Property
TotalSize Property
VolumeName Property


Files Property (FileSystemObject)

Scripting Runtime Library
Files Property (FileSystemObject)
See Also
CollapseAll image DropDown image

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

Expand image Remarks

The object is always a Folder object.

The following code illustrates the use of the Files property:

JScript CopyCode image Copy Code
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);
}
Visual Basic Script CopyCode image Copy Code
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

Applies To:

Folder Object

Expand image See Also

Reference

Attributes Property
DateCreated Property
DateLastAccessed Property
DateLastModified Property
Drive Property
IsRootFolder Property
Name Property (FileSystemObject)
ParentFolder Property
Path Property (FileSystemObject)
ShortName Property
ShortPath Property
Size Property
SubFolders Property
Type Property


FileSystem Property

Scripting Runtime Library
FileSystem Property
See Also
CollapseAll image DropDown image

Returns the type of file system in use for the specified drive.

object.FileSystem

Expand image Remarks

The object is always a Drive object.

Available return types include FAT, NTFS, and CDFS.

The following code illustrates the use of the FileSystem property:

JScript CopyCode image Copy Code
function ShowFileSystemType(drvPath)
{
   var fso,d, s;
   fso = new ActiveXObject("Scripting.FileSystemObject");
   d = fso.GetDrive(drvPath);
   s = d.FileSystem;
   return(s);
}
Visual Basic Script CopyCode image Copy Code
Function ShowFileSystemType(drvspec)
   Dim fso,d
   Set fso = CreateObject("Scripting.FileSystemObject")
   Set d = fso.GetDrive(drvspec)
   ShowFileSystemType = d.FileSystem
End Function

Applies To:

Drive Object

Expand image See Also

Reference

AvailableSpace Property
DriveLetter Property
DriveType Property
FreeSpace Property
IsReady Property
Path Property (FileSystemObject)
RootFolder Property
SerialNumber Property
ShareName Property
TotalSize Property
VolumeName Property


FreeSpace Property

Scripting Runtime Library
FreeSpace Property
See Also
CollapseAll image DropDown image

Returns the amount of free space available to a user on the specified drive or network share. Read-only.

object.FreeSpace

Expand image Remarks

The object is always a Drive object.

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 CopyCode image Copy Code
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);
}
Visual Basic Script CopyCode image Copy Code
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

Applies To:

Drive Object

Expand image See Also

Reference

AvailableSpace Property
DriveLetter Property
DriveType Property
FileSystem Property
IsReady Property
Path Property (FileSystemObject)
RootFolder Property
SerialNumber Property
ShareName Property
TotalSize Property
VolumeName Property


IsReady Property

Scripting Runtime Library
IsReady Property
See Also
CollapseAll image DropDown image

Returns True if the specified drive is ready; False if it is not.

object.IsReady

Expand image Remarks

The object is always a Drive object.

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 CopyCode image Copy Code
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);
}
Visual Basic Script CopyCode image Copy Code
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

Applies To:

Drive Object

Expand image See Also

Reference

AvailableSpace Property
DriveLetter Property
DriveType Property
FileSystem Property
FreeSpace Property
Path Property (FileSystemObject)
RootFolder Property
SerialNumber Property
ShareName Property
TotalSize Property
VolumeName Property


IsRootFolder Property

Scripting Runtime Library
IsRootFolder Property
See Also
CollapseAll image DropDown image

Returns True if the specified folder is the root folder; False if it is not.

object.IsRootFolder

Expand image Remarks

The object is always a Folder object.

The following code illustrates the use of the IsRootFolder property:

JScript CopyCode image Copy Code
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);
}
Visual Basic Script CopyCode image Copy Code
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

Applies To:

Folder Object

Expand image See Also

Reference

Attributes Property
DateCreated Property
DateLastAccessed Property
DateLastModified Property
Drive Property
Files Property (FileSystemObject)
Name Property (FileSystemObject)
ParentFolder Property
Path Property (FileSystemObject)
ShortName Property
ShortPath Property
Size Property
SubFolders Property
Type Property


Line Property (FileSystemObject)

Scripting Runtime Library
Line Property (FileSystemObject)
See Also
CollapseAll image DropDown image

Read-only property that returns the current line number in a TextStream file.

object.Line

Expand image Remarks

The object is always the name of a TextStream object.

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 CopyCode image Copy Code
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);
}
Visual Basic Script CopyCode image Copy Code
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 & "VBScript is fun!" & vbCrLf
   Set f = fso.OpenTextFile("c:\testfile.txt", ForReading)
   ra =   f.ReadAll
   GetLine = f.Line
End Function

Applies To:

TextStream Object

Expand image See Also

Reference

Column Property (FileSystemObject)


Name Property (FileSystemObject)

Scripting Runtime Library
Name Property (FileSystemObject)
See Also
CollapseAll image DropDown image

Sets or returns the name of a specified file or folder. Read/write.

object.Name [= newname]

Expand image 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.

Expand image Remarks

The following code illustrates the use of the Name property:

JScript CopyCode image Copy Code
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);
}
Visual Basic Script CopyCode image Copy Code
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

Applies To:

File Object| Folder Object

Expand image See Also

Reference

Attributes Property
DateCreated Property
DateLastAccessed Property
DateLastModified Property
Drive Property
Files Property (FileSystemObject)
IsRootFolder Property
ParentFolder Property
Path Property (FileSystemObject)
ShortName Property
ShortPath Property
Size Property
SubFolders Property
Type Property


ParentFolder Property

Scripting Runtime Library
ParentFolder Property
See Also
CollapseAll image DropDown image

Returns the folder object for the parent of the specified file or folder. Read-only.

object.ParentFolder

Expand image Remarks

The object is always a File or Folder object.

The following code illustrates the use of the ParentFolder property with a file:

JScript CopyCode image Copy Code
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);
}
Visual Basic Script CopyCode image Copy Code
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

Applies To:

File Object| Folder Object

Expand image See Also

Reference

Attributes Property
DateCreated Property
DateLastAccessed Property
DateLastModified Property
Drive Property
Files Property (FileSystemObject)
IsRootFolder Property
Name Property (FileSystemObject)
Path Property (FileSystemObject)
ShortName Property
ShortPath Property
Size Property
SubFolders Property
Type Property


Path Property (FileSystemObject)

Scripting Runtime Library
Path Property (FileSystemObject)
See Also
CollapseAll image DropDown image

Returns the path for a specified file, folder, or drive.

object.Path

Expand image Remarks

The object is always a File, Folder, or Drive object.

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 CopyCode image Copy Code
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);
}
Visual Basic Script CopyCode image Copy Code
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

Applies To:

Drive Object| File Object| Folder Object

Expand image See Also

Reference

Attributes Property
AvailableSpace Property
DateCreated Property
DateLastAccessed Property
DateLastModified Property
Drive Property
DriveLetter Property
DriveType Property
Files Property (FileSystemObject)
FileSystem Property
FreeSpace Property
IsReady Property
IsRootFolder Property
Name Property (FileSystemObject)
ParentFolder Property
RootFolder Property
SerialNumber Property
ShareName Property
ShortName Property
ShortPath Property
Size Property
SubFolders Property
TotalSize Property
Type Property
VolumeName Property


RootFolder Property

Scripting Runtime Library
RootFolder Property
See Also
CollapseAll image DropDown image

Returns a Folder object representing the root folder of a specified drive. Read-only.

object.RootFolder

Expand image Remarks

The object is always a Drive object.

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 CopyCode image Copy Code
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);
}
Visual Basic Script CopyCode image Copy Code
Function ShowRootFolder(drvspec)
   Dim fso, f
   Set fso = CreateObject("Scripting.FileSystemObject")
   Set f = fso.GetDrive(drvspec)
   ShowRootFolder = f.RootFolder
End Function

Applies To:

Drive Object

Expand image See Also

Reference

AvailableSpace Property
DriveLetter Property
DriveType Property
FileSystem Property
FreeSpace Property
IsReady Property
Path Property (FileSystemObject)
SerialNumber Property
ShareName Property
TotalSize Property
VolumeName Property


SerialNumber Property

Scripting Runtime Library
SerialNumber Property
See Also
CollapseAll image DropDown image

Returns the decimal serial number used to uniquely identify a disk volume.

object.SerialNumber

Expand image Remarks

The object is always a Drive object.

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 CopyCode image Copy Code
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);
}
Visual Basic Script CopyCode image Copy Code
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

Applies To:

Drive Object

Expand image See Also

Reference

AvailableSpace Property
DriveLetter Property
DriveType Property
FileSystem Property
FreeSpace Property
IsReady Property
Path Property (FileSystemObject)
RootFolder Property
ShareName Property
TotalSize Property
VolumeName Property


ShareName Property

Scripting Runtime Library
ShareName Property
See Also
CollapseAll image DropDown image

Returns the network share name for a specified drive.

object.ShareName

Expand image Remarks

The object is always a Drive object.

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 CopyCode image Copy Code
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);
}
Visual Basic Script CopyCode image Copy Code
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

Applies To:

Drive Object

Expand image See Also

Reference

AvailableSpace Property
DriveLetter Property
DriveType Property
FileSystem Property
FreeSpace Property
IsReady Property
Path Property (FileSystemObject)
RootFolder Property
SerialNumber Property
TotalSize Property
VolumeName Property


ShortName Property

Scripting Runtime Library
ShortName Property
See Also
CollapseAll image DropDown image

Returns the short name used by programs that require the earlier 8.3 naming convention.

object.ShortName

Expand image Remarks

The object is always a File or Folder object.

The following code illustrates the use of the ShortName property with a File object:

JScript CopyCode image Copy Code
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);
}
Visual Basic Script CopyCode image Copy Code
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

Applies To:

File Object| Folder Object

Expand image See Also

Reference

Attributes Property
DateCreated Property
DateLastAccessed Property
DateLastModified Property
Drive Property
Files Property (FileSystemObject)
IsRootFolder Property
Name Property (FileSystemObject)
ParentFolder Property
Path Property (FileSystemObject)
ShortPath Property
Size Property
SubFolders Property
Type Property


ShortPath Property

Scripting Runtime Library
ShortPath Property
See Also
CollapseAll image DropDown image

Returns the short path used by programs that require the earlier 8.3 file naming convention.

object.ShortPath

Expand image Remarks

The object is always a File or Folder object.

The following code illustrates the use of the ShortPath property with a File object:

JScript CopyCode image Copy Code
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);
}
Visual Basic Script CopyCode image Copy Code
Function ShowShortPath(filespec)
   Dim fso, f, s
   Set fso = CreateObject("Scripting.FileSystemObject")
   Set f = fso.GetFile(filespec)
   s = "The short path for "   & UCase(f.Name) & "<BR>"
   s = s & "is: " & f.ShortPath
   ShowShortPath = s
End Function

Applies To:

File Object| Folder Object

Expand image See Also

Reference

Attributes Property
DateCreated Property
DateLastAccessed Property
DateLastModified Property
Drive Property
Files Property (FileSystemObject)
IsRootFolder Property
Name Property (FileSystemObject)
ParentFolder Property
Path Property (FileSystemObject)
ShortName Property
Size Property
SubFolders Property
Type Property


Size Property

Scripting Runtime Library
Size Property
See Also
CollapseAll image DropDown image

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

Expand image Remarks

The object is always a File or Folder object.

The following code illustrates the use of the Size property with a Folder object:

JScript CopyCode image Copy Code
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);
}
Visual Basic Script CopyCode image Copy Code
 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

Applies To:

File Object| Folder Object

Expand image See Also

Reference

Attributes Property
DateCreated Property
DateLastAccessed Property
DateLastModified Property
Drive Property
Files Property (FileSystemObject)
IsRootFolder Property
Name Property (FileSystemObject)
ParentFolder Property
Path Property (FileSystemObject)
ShortName Property
ShortPath Property
SubFolders Property
Type Property


SubFolders Property

Scripting Runtime Library
SubFolders Property
See Also
CollapseAll image DropDown image

Returns a Folders collection consisting of all folders contained in a specified folder, including those with hidden and system file attributes set.

object.SubFolders

Expand image Remarks

The object is always a Folder object.

The following code illustrates the use of the SubFolders property:

JScript CopyCode image Copy Code
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);
}
Visual Basic Script CopyCode image Copy Code
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

Applies To:

Folder Object

Expand image See Also

Reference

Attributes Property
DateCreated Property
DateLastAccessed Property
DateLastModified Property
Drive Property
Files Property (FileSystemObject)
IsRootFolder Property
Name Property (FileSystemObject)
ParentFolder Property
Path Property (FileSystemObject)
ShortName Property
ShortPath Property
Size Property
Type Property


TotalSize Property

Scripting Runtime Library
TotalSize Property
See Also
CollapseAll image DropDown image

Returns the total space, in bytes, of a drive or network share.

object.TotalSize

Expand image Remarks

The object is always a Drive object.

The following code illustrates the use of the TotalSize property:

JScript CopyCode image Copy Code
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);
}
Visual Basic Script CopyCode image Copy Code
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

Applies To:

Drive Object

Expand image See Also

Reference

AvailableSpace Property
DriveLetter Property
DriveType Property
FileSystem Property
FreeSpace Property
IsReady Property
Path Property (FileSystemObject)
RootFolder Property
SerialNumber Property
ShareName Property
VolumeName Property


Type Property

Scripting Runtime Library
Type Property
See Also
CollapseAll image DropDown image

Returns information about the type of a file or folder. For example, for files ending in .TXT, "Text Document" is returned.

object.Type

Expand image Remarks

The object is always a File or Folder object.

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 CopyCode image Copy Code
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);
}
Visual Basic Script CopyCode image Copy Code
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

Applies To:

File Object| Folder Object

Expand image See Also

Reference

Attributes Property
DateCreated Property
DateLastAccessed Property
DateLastModified Property
Drive Property
Files Property (FileSystemObject)
IsRootFolder Property
Name Property (FileSystemObject)
ParentFolder Property
Path Property (FileSystemObject)
ShortName Property
ShortPath Property
Size Property
SubFolders Property


VolumeName Property

Scripting Runtime Library
VolumeName Property
See Also
CollapseAll image DropDown image

Sets or returns the volume name of the specified drive. Read/write.

object.VolumeName [= newname]

Expand image Arguments

object

Required. Always the name of a Drive object.

newname

Optional. If provided, newname is the new name of the specified object.

Expand image Remarks

The following code illustrates the use of the VolumeName property:

JScript CopyCode image Copy Code
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);
}
Visual Basic Script CopyCode image Copy Code
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

Applies To:

Drive Object

Expand image See Also

Reference

AvailableSpace Property
DriveLetter Property
DriveType Property
FileSystem Property
FreeSpace Property
IsReady Property
Path Property (FileSystemObject)
RootFolder Property
SerialNumber Property
ShareName Property
TotalSize Property


FileSystemObject Methods

Scripting Runtime Library
FileSystemObject Methods
DropDown image

The following sections provide details about the 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.

DriveExists 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.

GetStandardStream Method

Returns a TextStream object corresponding to the standard input, output, or error stream.

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.


Add Method (Folders)

Scripting Runtime Library
Add Method (Folders)
See Also
CollapseAll image DropDown image

Adds a new folder to a Folders collection.

object.Add (folderName)

Expand image Arguments

object

Required. Always the name of a Folders collection.

folderName

Required. The name of the new Folder being added.

Expand image Remarks

The following example illustrates the use of the Add method to create a new folder.

JScript CopyCode image Copy Code
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");
}
Visual Basic Script CopyCode image Copy Code
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.

Applies To:

Folders Collection

Expand image See Also

Reference

Add Method (Script Runtime)


BuildPath Method

Scripting Runtime Library
BuildPath Method
See Also
CollapseAll image DropDown image

Appends a name to an existing path.

object.BuildPath(path, name)

Expand image 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.

Expand image 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 CopyCode image Copy Code
function GetBuildPath(path)
{
   var fso, newpath;
   fso = new ActiveXObject("Scripting.FileSystemObject");
   newpath = fso.BuildPath(path, "New   Folder");
   return(newpath);
}
Visual Basic Script CopyCode image Copy Code
Function GetBuildPath(path)
   Dim fso, newpath
   Set fso = CreateObject("Scripting.FileSystemObject")
   newpath = fso.BuildPath(path, "Sub Folder")
   GetBuildPath = newpath
End Function

Applies To:

FileSystemObject Object

Expand image See Also

Reference

GetAbsolutePathName Method
GetBaseName Method
GetDriveName Method
GetExtensionName Method
GetFileName Method
GetParentFolderName Method
GetTempName Method


Close Method (FileSystemObject)

Scripting Runtime Library
Close Method (FileSystemObject)
See Also
CollapseAll image DropDown image

Closes an open TextStream file.

object.Close( );

Expand image Remarks

The object is always the name of a TextStream object.

The following example illustrates use of the Close method.

JScript CopyCode image Copy Code
var fso;
fso = new ActiveXObject("Scripting.FileSystemObject");
a = fso.CreateTextFile("c:\\testfile.txt", true);
a.WriteLine("This is a test.");
a.Close();
Visual Basic Script CopyCode image Copy Code
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

Applies To:

FileSystemObject Object

Expand image See Also

Reference

CreateTextFile Method
OpenTextFile Method


Copy Method (FileSystemObject)

Scripting Runtime Library
Copy Method (FileSystemObject)
See Also Example
CollapseAll image DropDown image

Copies a specified file or folder from one location to another.

object.Copy( destination[, overwrite] );

Expand image 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.

Expand image 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.

Expand image Example

The following example illustrates the use of the Copy method.

JScript CopyCode image Copy Code
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");
Visual Basic Script CopyCode image Copy Code
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")

Applies To:

File Object| Folder Object

Expand image See Also

Reference

CopyFile Method
CopyFolder Method
Delete Method
Move Method
OpenAsTextStream Method


CopyFile Method

Scripting Runtime Library
CopyFile Method
See Also
CollapseAll image DropDown image

Copies one or more files from one location to another.

object.CopyFile ( source, destination[, overwrite] )

Expand image 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.

Expand image Remarks

Wildcard characters can only be used in the last path component of the source argument. For example, you can use:

JScript CopyCode image Copy Code
fso = new ActiveXObject("Scripting.FileSystemObject");
fso.CopyFile ("c:\\mydocuments\\letters\\*.doc", "c:\\tempfolder\\")
Visual Basic Script CopyCode image Copy Code
FileSystemObject.CopyFile "c:\mydocuments\letters\*.doc", "c:\tempfolder\"

But you cannot use:

JScript CopyCode image Copy Code
fso = new ActiveXObject("Scripting.FileSystemObject");
fso.CopyFile ("c:\\mydocuments\\*\\R1???97.xls", "c:\\tempfolder")
Visual Basic Script CopyCode image Copy Code
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.

Applies To:

FileSystemObject Object

Expand image See Also

Reference

Copy Method (FileSystemObject)
CopyFolder Method
CreateTextFile Method
DeleteFile Method
MoveFile Method


CopyFolder Method

Scripting Runtime Library
CopyFolder Method
See Also
CollapseAll image DropDown image

Recursively copies a folder from one location to another.

object.CopyFolder ( source, destination[, overwrite] );

Expand image 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.

Expand image Remarks

Wildcard characters can only be used in the last path component of the source argument. For example, you can use:

JScript CopyCode image Copy Code
fso = new ActiveXObject("Scripting.FileSystemObject");
fso.CopyFolder ("c:\\mydocuments\\letters\\*", "c:\\tempfolder\\")
Visual Basic Script CopyCode image Copy Code
FileSystemObject.CopyFolder "c:\mydocuments\letters\*", "c:\tempfolder\"

But you cannot use:

JScript CopyCode image Copy Code
fso = new ActiveXObject("Scripting.FileSystemObject");
fso.CopyFolder ("c:\\mydocuments\\*\\*", "c:\\tempfolder\\")
Visual Basic Script CopyCode image Copy Code
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.

Applies To:

FileSystemObject Object

Expand image See Also

Reference

CopyFile Method
Copy Method (FileSystemObject)
CreateFolder Method
DeleteFolder Method
MoveFolder Method


CreateFolder Method

Scripting Runtime Library
CreateFolder Method
See Also
CollapseAll image DropDown image

Creates a folder.

object.CreateFolder(foldername)

Expand image Arguments

object

Required. Always the name of a FileSystemObject.

foldername

Required. String expression that identifies the folder to create.

Expand image 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 CopyCode image Copy Code
var fso = new ActiveXObject("Scripting.FileSystemObject");
var a = fso.CreateFolder("c:\\new folder");
Visual Basic Script CopyCode image Copy Code
Function CreateFolderDemo
   Dim fso, f
   Set fso = CreateObject("Scripting.FileSystemObject")
   Set f = fso.CreateFolder("c:\New Folder")
   CreateFolderDemo = f.Path
End Function

Applies To:

FileSystemObject Object

Expand image See Also

Reference

CopyFolder Method
DeleteFolder Method
MoveFolder Method


CreateTextFile Method

Scripting Runtime Library
CreateTextFile Method
See Also
CollapseAll image DropDown image

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]])

Expand image 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.

Expand image Remarks

The following code illustrates how to use the CreateTextFile method to create and open a text file.

JScript CopyCode image Copy Code
var fso = new ActiveXObject("Scripting.FileSystemObject");
var a = fso.CreateTextFile("c:\\testfile.txt", true);
a.WriteLine("This is a test.");
a.Close();
Visual Basic Script CopyCode image Copy Code
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.

Applies To:

FileSystemObject Object| Folder Object

Expand image See Also

Reference

CreateFolder Method
OpenAsTextStream Method
OpenTextFile Method


Delete Method

Scripting Runtime Library
Delete Method
See Also
CollapseAll image DropDown image

Deletes a specified file or folder.

object.Delete( force );

Expand image 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.

Expand image 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 CopyCode image Copy Code
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();
Visual Basic Script CopyCode image Copy Code
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

Applies To:

File Object| Folder Object

Expand image See Also

Reference

Copy Method (FileSystemObject)
DeleteFile Method
DeleteFolder Method
Move Method
OpenAsTextStream Method


DeleteFile Method

Scripting Runtime Library
DeleteFile Method
See Also
CollapseAll image DropDown image

Deletes a specified file.

object.DeleteFile ( filespec[, force] );

Expand image 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.

Expand image 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 CopyCode image Copy Code
function DeleteFile(filespec)
{
   var fso;
   fso = new ActiveXObject("Scripting.FileSystemObject");
   fso.DeleteFile(filespec);
}
Visual Basic Script CopyCode image Copy Code
Sub DeleteAFile(filespec)
   Dim fso
   Set fso = CreateObject("Scripting.FileSystemObject")
   fso.DeleteFile(filespec)
End Sub

Applies To:

FileSystemObject Object

Expand image See Also

Reference

CopyFile Method
CreateTextFile Method
Delete Method
DeleteFolder Method
MoveFile Method


DeleteFolder Method

Scripting Runtime Library
DeleteFolder Method
See Also
CollapseAll image DropDown image

Deletes a specified folder and its contents.

object.DeleteFolder ( folderspec[, force] );

Expand image 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.

Expand image 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 CopyCode image Copy Code
function DeleteFolder(folderspec)
{
   var fso;
   fso = new ActiveXObject("Scripting.FileSystemObject");
   fso.DeleteFolder(folderspec);
}
Visual Basic Script CopyCode image Copy Code
Sub DeleteAFolder(filespec)
   Dim fso
   Set fso = CreateObject("Scripting.FileSystemObject")
   fso.DeleteFolder(filespec)
End Sub

Applies To:

FileSystemObject Object

Expand image See Also

Reference

CopyFolder Method
CreateFolder Method
Delete Method
DeleteFile Method
MoveFolder Method


DriveExists Method

Scripting Runtime Library
DriveExists Method
See Also
CollapseAll image DropDown image

Returns True if the specified drive exists; False if it does not.

object.DriveExists(drivespec)

Expand image Arguments

object

Required. Always the name of a FileSystemObject.

drivespec

Required. A drive letter or a complete path specification.

Expand image 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 CopyCode image Copy Code
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);
}
Visual Basic Script CopyCode image Copy Code
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

Applies To:

FileSystemObject Object

Expand image See Also

Reference

Drive Object
Drives Collection
FileExists Method
FolderExists Method
GetDrive Method
GetDriveName Method
IsReady Property


FileExists Method

Scripting Runtime Library
FileExists Method
See Also
CollapseAll image DropDown image

Returns True if a specified file exists; False if it does not.

object.FileExists(filespec)

Expand image 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 CopyCode image Copy Code
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);
}
Visual Basic Script CopyCode image Copy Code
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

Applies To:

FileSystemObject Object

Expand image See Also

Reference

DriveExists Method
FolderExists Method
GetFile Method
GetFileName Method


FolderExists Method

Scripting Runtime Library
FolderExists Method
See Also
CollapseAll image DropDown image

Returns True if a specified folder exists; False if it does not.

object.FolderExists(folderspec)

Expand image 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 CopyCode image Copy Code
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);
}
Visual Basic Script CopyCode image Copy Code
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

Applies To:

FileSystemObject Object

Expand image See Also

Reference

DriveExists Method
FileExists Method
GetFolder Method
GetParentFolderName Method


GetAbsolutePathName Method

Scripting Runtime Library
GetAbsolutePathName Method
See Also
CollapseAll image DropDown image

Returns a complete and unambiguous path from a provided path specification.

object.GetAbsolutePathName(pathspec)

Expand image Arguments

object

Required. Always the name of a FileSystemObject.

pathspec

Required. Path specification to change to a complete and unambiguous path.

Expand image 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 (JScript) | pathspec (VBScript) | Returned path
"c:" | "c:" | "c:\mydocuments\reports"
"c:.." | "c:.." | "c:\mydocuments"
"c:\\" | "c:\" | "c:\"
"c:*.*\\may97" | "c:*.*\may97" | "c:\mydocuments\reports\*.*\may97"
"region1" | "region1" | "c:\mydocuments\reports\region1"
"c:\\..\\..\\mydocuments" | "c:\..\..\mydocuments" | "c:\mydocuments"

The following example illustrates the use of the GetAbsolutePathName method.

JScript CopyCode image Copy Code
function ShowAbsolutePath(path)
{
   var fso, s= "";
   fso = new ActiveXObject("Scripting.FileSystemObject");
   s += fso.GetAbsolutePathName(path);
   return(s);
}
Visual Basic Script CopyCode image Copy Code
Function ShowAbsolutePath(path)
   Dim fso
   Set fso = CreateObject("Scripting.FileSystemObject")
   ShowAbsolutePath = fso.GetAbsolutePathName(path)
End Function

Applies To:

FileSystemObject Object

Expand image See Also

Reference

GetBaseName Method
GetDrive Method
GetDriveName Method
GetExtensionName Method
GetFile Method
GetFileName Method
GetFileVersion Method
GetFolder Method
GetParentFolderName Method
GetSpecialFolder Method
GetTempName Method


GetBaseName Method

Scripting Runtime Library
GetBaseName Method
See Also
CollapseAll image DropDown image

Returns a string containing the base name of the last component, less any file extension, in a path.

object.GetBaseName(path)

Expand image Arguments

object

Required. Always the name of a FileSystemObject.

path

Required. The path specification for the component whose base name is to be returned.

Expand image Remarks

The GetBaseName method returns a zero-length string ("") if no component matches the path argument.

Note 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 CopyCode image Copy Code
function ShowBaseName(filespec)
{
   var fso, s = "";
   fso = new ActiveXObject("Scripting.FileSystemObject");
   s += fso.GetBaseName(filespec);
   return(s);
}
Visual Basic Script CopyCode image Copy Code
Function GetTheBase(filespec)
   Dim fso
   Set fso = CreateObject("Scripting.FileSystemObject")
   GetTheBase = fso.GetBaseName(filespec)
End Function

Applies To:

FileSystemObject Object

Expand image See Also

Reference

GetAbsolutePathName Method
GetDrive Method
GetDriveName Method
GetExtensionName Method
GetFile Method
GetFileName Method
GetFileVersion Method
GetFolder Method
GetParentFolderName Method
GetSpecialFolder Method
GetTempName Method


GetDrive Method

Scripting Runtime Library
GetDrive Method
See Also
CollapseAll image DropDown image

Returns a Drive object corresponding to the drive in a specified path.

object.GetDrive ( drivespec )

Expand image Arguments

Argument | Description
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).

Expand image 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:

CopyCode image Copy Code
DriveSpec = GetDriveName(GetAbsolutePathName(Path))

The following example illustrates the use of the GetDrive method.

CopyCode image Copy Code
// 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

Applies To:

FileSystemObject Object

Expand image See Also

Reference

GetAbsolutePathName Method
GetBaseName Method
GetDriveName Method
GetExtensionName Method
GetFile Method
GetFileName Method
GetFileVersion Method
GetFolder Method
GetParentFolderName Method
GetSpecialFolder Method
GetTempName Method


GetDriveName Method

Scripting Runtime Library
GetDriveName Method
See Also
CollapseAll image DropDown image

Returns a string containing the name of the drive for a specified path.

object.GetDriveName(path)

Expand image Arguments

object

Required. Always the name of a FileSystemObject.

path

Required. The path specification for the component whose drive name is to be returned.

Expand image Remarks

The GetDriveName method returns a zero-length string ("") if the drive can't be determined.

Note 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 CopyCode image Copy Code
function GetDriveLetter(path)
{
   var fso, s ="";
   fso = new ActiveXObject("Scripting.FileSystemObject");
   s += fso.GetDrive(fso.GetDriveName(fso.GetAbsolutePathName(path)));
   return(s);
}
Visual Basic Script CopyCode image Copy Code
Function GetAName(DriveSpec)
   Dim fso
   Set fso = CreateObject("Scripting.FileSystemObject")
   GetAName = fso.GetDriveName(Drivespec)
End Function

Applies To:

FileSystemObject Object

Expand image See Also

Reference

GetAbsolutePathName Method
GetBaseName Method
GetDrive Method
GetExtensionName Method
GetFile Method
GetFileName Method
GetFileVersion Method
GetFolder Method
GetParentFolderName Method
GetSpecialFolder Method
GetTempName Method


GetExtensionName Method

Scripting Runtime Library
GetExtensionName Method
See Also
CollapseAll image DropDown image

Returns a string containing the extension name for the last component in a path.

object.GetExtensionName(path)

Expand image Arguments

object

Required. Always the name of a FileSystemObject.

path

Required. The path specification for the component whose extension name is to be returned.

Expand image 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 CopyCode image Copy Code
function ShowExtensionName(filespec)
{
   var fso, s = "";
   fso = new ActiveXObject("Scripting.FileSystemObject");
   s += fso.GetExtensionName(filespec);
   return(s);
}
Visual Basic Script CopyCode image Copy Code
Function GetAnExtension(DriveSpec)
   Dim fso
   Set fso = CreateObject("Scripting.FileSystemObject")
   GetAnExtension = fso.GetExtensionName(Drivespec)
End Function

Applies To:

FileSystemObject Object

Expand image See Also

Reference

GetAbsolutePathName Method
GetBaseName Method
GetDrive Method
GetDriveName Method
GetFile Method
GetFileName Method
GetFileVersion Method
GetFolder Method
GetParentFolderName Method
GetSpecialFolder Method
GetTempName Method


GetFile Method

Scripting Runtime Library
GetFile Method
See Also
CollapseAll image DropDown image

Returns a File object corresponding to the file in a specified path.

object.GetFile(filespec)

Expand image Arguments

object

Required. Always the name of a FileSystemObject.

filespec

Required. The filespec is the path (absolute or relative) to a specific file.

Expand image Remarks

An error occurs if the specified file does not exist. The GetFile method does not support the use of wildcard characters, such as ? or *.

The following example illustrates the use of the GetFile method.

JScript CopyCode image Copy Code
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);
}
Visual Basic Script CopyCode image Copy Code
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

Applies To:

FileSystemObject Object

Expand image See Also

Reference

GetAbsolutePathName Method
GetBaseName Method
GetDrive Method
GetDriveName Method
GetExtensionName Method
GetFileName Method
GetFileVersion Method
GetFolder Method
GetParentFolderName Method
GetSpecialFolder Method
GetTempName Method


GetFileName Method

Scripting Runtime Library
GetFileName Method
See Also
CollapseAll image DropDown image

Returns the last component of specified path that is not part of the drive specification.

object.GetFileName(pathspec)

Expand image Arguments

object

Required. Always the name of a FileSystemObject.

pathspec

Required. The path (absolute or relative) to a specific file.

Expand image Remarks

The GetFileName method returns a zero-length string ("") if pathspec does not end with the named component.

Note 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 CopyCode image Copy Code
function ShowFileName(filespec)
{
   var fso, s = "";
   fso = new ActiveXObject("Scripting.FileSystemObject");
   s += fso.GetFileName(filespec);
   return(s);
}
Visual Basic Script CopyCode image Copy Code
Function GetAName(DriveSpec)
   Dim fso
   Set fso = CreateObject("Scripting.FileSystemObject")
   GetAName = fso.GetFileName(DriveSpec)
End Function

Applies To:

FileSystemObject Object

Expand image See Also

Reference

GetAbsolutePathName Method
GetBaseName Method
GetDrive Method
GetDriveName Method
GetExtensionName Method
GetFile Method
GetFileVersion Method
GetFolder Method
GetParentFolderName Method
GetSpecialFolder Method
GetTempName Method


GetFileVersion Method

Scripting Runtime Library
GetFileVersion Method
See Also
CollapseAll image DropDown image

Returns the version number of a specified file.

object.GetFileVersion(pathspec)

Expand image Arguments

object

Required. Always the name of a FileSystemObject.

pathspec

Required. The path (absolute or relative) to a specific file.

Expand image Remarks

The GetFileVersion method returns a zero-length string ("") if pathspec does not end with the named component.

Note 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 CopyCode image Copy Code
function ShowFileName(filespec){
   var fso, s = "";
   fso = new ActiveXObject("Scripting.FileSystemObject");
   s += fso.GetFileVersion(filespec);
   return(s);
}
Visual Basic Script CopyCode image Copy Code
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

Applies To:

FileSystemObject Object

Expand image See Also

Reference

GetAbsolutePathName Method
GetBaseName Method
GetDrive Method
GetDriveName Method
GetExtensionName Method
GetFile Method
GetFileName Method
GetFolder Method
GetParentFolderName Method
GetSpecialFolder Method
GetTempName Method


GetFolder Method

Scripting Runtime Library
GetFolder Method
See Also
CollapseAll image DropDown image

Returns a Folder object corresponding to the folder in a specified path.

object.GetFolder(folderspec)

Expand image Arguments

object

Required. Always the name of a FileSystemObject.

folderspec

Required. The folderspec is the path (absolute or relative) to a specific folder.

Expand image Remarks

An error occurs if the specified folder does not exist.

The following example illustrates the use of the GetFolder method.

JScript CopyCode image Copy Code
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);
}
Visual Basic Script CopyCode image Copy Code
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

Applies To:

FileSystemObject Object

Expand image See Also

Reference

GetAbsolutePathName Method
GetBaseName Method
GetDrive Method
GetDriveName Method
GetExtensionName Method
GetFile Method
GetFileName Method
GetFileVersion Method
GetParentFolderName Method
GetSpecialFolder Method
GetTempName Method
Folder Object


GetParentFolderName Method

Scripting Runtime Library
GetParentFolderName Method
See Also
CollapseAll image DropDown image

Returns a string containing the name of the parent folder of the last component in a specified path.

object.GetParentFolderName(path)

Expand image 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.

Expand image Remarks

The GetParentFolderName method returns a zero-length string ("") if there is no parent folder for the component specified in the path argument.

Note 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 CopyCode image Copy Code
function ShowParentFolderName(filespec)
{
   var fso, s = "";
   fso = new ActiveXObject("Scripting.FileSystemObject");
   s += fso.GetParentFolderName(filespec);
   return(s);
}
Visual Basic Script CopyCode image Copy Code
Function GetTheParent(DriveSpec)
   Dim fso
   Set fso = CreateObject("Scripting.FileSystemObject")
   GetTheParent = fso.GetParentFolderName(Drivespec)
End Function

Applies To:

FileSystemObject Object

Expand image See Also

Reference

GetAbsolutePathName Method
GetBaseName Method
GetDrive Method
GetDriveName Method
GetExtensionName Method
GetFile Method
GetFileName Method
GetFileVersion Method
GetFolder Method
GetSpecialFolder Method
GetTempName Method


GetSpecialFolder Method

Scripting Runtime Library
GetSpecialFolder Method
See Also
CollapseAll image DropDown image

Returns the special folder object specified.

object.GetSpecialFolder(folderspec)

Expand image 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.

Expand image Settings

The folderspec argument can have any of the following values:

Constant | Value | Description
WindowsFolder | 0 | The Windows folder contains files installed by the Windows operating system.
SystemFolder | 1 | The System folder contains libraries, fonts, and device drivers.
TemporaryFolder | 2 | 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 CopyCode image Copy Code
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();
Visual Basic Script CopyCode image Copy Code
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

Applies To:

FileSystemObject Object

Expand image See Also

Reference

GetAbsolutePathName Method
GetBaseName Method
GetDrive Method
GetDriveName Method
GetExtensionName Method
GetFile Method
GetFileName Method
GetFileVersion Method
GetFolder Method
GetParentFolderName Method
GetTempName Method


GetStandardStream Method

Scripting Runtime Library
GetStandardStream Method
See Also
CollapseAll image DropDown image

Returns a TextStream object corresponding to the standard input, output, or error stream.

object.GetStandardStream(standardStreamType [, unicode ])

Expand image Arguments

standardStreamType

Required. Can be one of three constants: StdErr, StdIn, or StdOut.

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 is created as an ASCII file. If omitted, an ASCII file is assumed.

Expand image Settings

The standardStreamType can have any of the following settings:

Constant | Value | Description
StdIn | 0 | Returns a TextStream object corresponding to the standard input stream.
StdOut | 1 | Returns a TextStream object corresponding to the standard output stream.
StdErr | 2 | Returns a TextStream object corresponding to the standard error stream.

Applies To:

FileSystemObject Object

Expand image See Also

Reference

TextStream Object


GetTempName Method

Scripting Runtime Library
GetTempName Method
See Also
CollapseAll image DropDown image

Returns a randomly generated temporary file or folder name that is useful for performing operations that require a temporary file or folder.

object.GetTempName ( )

Expand image Remarks

The optional object is always the name of a FileSystemObject.

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 CopyCode image Copy Code
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();
Visual Basic Script CopyCode image Copy Code
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

Applies To:

FileSystemObject Object

Expand image See Also

Reference

GetAbsolutePathName Method
GetBaseName Method
GetDrive Method
GetDriveName Method
GetExtensionName Method
GetFile Method
GetFileName Method
GetFileVersion Method
GetFolder Method
GetParentFolderName Method
GetSpecialFolder Method


Move Method

Scripting Runtime Library
Move Method
See Also
CollapseAll image DropDown image

Moves a specified file or folder from one location to another.

object.Move( destination );

Expand image 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.

Expand image 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.

Applies To:

File Object| Folder Object

Expand image See Also

Reference

Copy Method (FileSystemObject)
Delete Method
MoveFile Method
MoveFolder Method
OpenAsTextStream Method


MoveFile Method

Scripting Runtime Library
MoveFile Method
See Also
CollapseAll image DropDown image

Moves one or more files from one location to another.

object.MoveFile ( source, destination );

Expand image 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.

Expand image 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 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 CopyCode image Copy Code
function MoveFile2Desktop(filespec)
{
   var fso;
   fso = new ActiveXObject("Scripting.FileSystemObject");
   fso.MoveFile(filespec, "c:\\windows\\desktop\\");
}
Visual Basic Script CopyCode image Copy Code
Sub MoveAFile(Drivespec)
   Dim fso
   Set fso = CreateObject("Scripting.FileSystemObject")
   fso.MoveFile Drivespec, "c:\windows\desktop\"
End Sub

Applies To:

FileSystemObject Object

Expand image See Also

Reference

CopyFile Method
DeleteFile Method
GetFile Method
GetFileName Method
Move Method
MoveFolder Method
OpenTextFile Method


MoveFolder Method

Scripting Runtime Library
MoveFolder Method
See Also
CollapseAll image DropDown image

Moves one or more folders from one location to another.

object.MoveFolder ( source, destination );

Expand image 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.

Expand image 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 CopyCode image Copy Code
function MoveFldr2Desktop(fldrspec)
{
   var fso;
   fso = new ActiveXObject("Scripting.FileSystemObject");
   fso.MoveFolder(fldrspec, "c:\\windows\\desktop\\");
}
Visual Basic Script CopyCode image Copy Code
Sub MoveAFolder(Drivespec)
   Dim fso
   Set fso = CreateObject("Scripting.FileSystemObject")
   fso.MoveFolder Drivespec, "c:\windows\desktop\"
End Sub

Applies To:

FileSystemObject Object

Expand image See Also

Reference

CopyFile Method
DeleteFile Method
GetFile Method
GetFileName Method
Move Method
MoveFile Method
OpenTextFile Method


OpenAsTextStream Method

Scripting Runtime Library
OpenAsTextStream Method
See Also
CollapseAll image DropDown image

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]])

Expand image 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.

Expand image Settings

The iomode argument can have any of the following settings:

Constant | Value | Description
ForReading | 1 | Open a file for reading only. You can't write to this file.
ForWriting | 2 | Open a file for writing. If a file with the same name exists, its previous contents are overwritten.
ForAppending | 8 | 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 | Opens the file using the system default.
TristateTrue | -1 | Opens the file as Unicode.
TristateFalse | 0 | Opens the file as ASCII.

Expand image 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 CopyCode image Copy Code
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);
}
Visual Basic Script CopyCode image Copy Code
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

Applies To:

File Object

Expand image See Also

Reference

Copy Method (FileSystemObject)
CreateTextFile Method
Delete Method
Move Method
OpenTextFile Method


OpenTextFile Method

Scripting Runtime Library
OpenTextFile Method
See Also
CollapseAll image DropDown image

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]]])

Expand image 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.

Expand image Settings

The iomode argument can have any of the following settings:

Constant | Value | Description
ForReading | 1 | Open a file for reading only. You can't write to this file.
ForWriting | 2 | Open a file for writing.
ForAppending | 8 | 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 | Opens the file using the system default.
TristateTrue | -1 | Opens the file as Unicode.
TristateFalse | 0 | Opens the file as ASCII.

Expand image Remarks

The following code illustrates the use of the OpenTextFile method to open a file for appending text:

JScript CopyCode image Copy Code
var fs, a, ForAppending;
ForAppending = 8;
fs = new ActiveXObject("Scripting.FileSystemObject");
a = fs.OpenTextFile("c:\\testfile.txt", ForAppending, false);
...
a.Close();
Visual Basic Script CopyCode image Copy Code
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

Applies To:

FileSystemObject Object

Expand image See Also

Reference

CreateTextFile Method
OpenAsTextStream Method


Read Method

Scripting Runtime Library
Read Method
See Also
CollapseAll image DropDown image

Reads a specified number of characters from a TextStream file and returns the resulting string.

object.Read(characters)

Expand image 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 CopyCode image Copy Code
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));
}
Visual Basic Script CopyCode image Copy Code
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

Applies To:

TextStream Object

Expand image See Also

Reference

ReadAll Method
ReadLine Method
Skip Method
SkipLine Method


ReadAll Method

Scripting Runtime Library
ReadAll Method
See Also
CollapseAll image DropDown image

Reads an entire TextStream file and returns the resulting string.

object.ReadAll( );

Expand image Remarks

The object is always the name of a TextStream object.

Expand image 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 CopyCode image Copy Code
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());
}
Visual Basic Script CopyCode image Copy Code
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

Applies To:

TextStream Object

Expand image See Also

Reference

Read Method
ReadLine Method
Skip Method
SkipLine Method


ReadLine Method

Scripting Runtime Library
ReadLine Method
See Also
CollapseAll image DropDown image

Reads an entire line (up to, but not including, the newline character) from a TextStream file and returns the resulting string.

object.ReadLine( )

Expand image Remarks

The object argument is always the name of a TextStream object.

Expand image Remarks

The following example illustrates the use of the Line property:

JScript CopyCode image Copy Code
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);
}
Visual Basic Script CopyCode image Copy Code
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

Applies To:

TextStream Object

Expand image See Also

Reference

Read Method
ReadAll Method
Skip Method
SkipLine Method


Skip Method

Scripting Runtime Library
Skip Method
See Also
CollapseAll image DropDown image

Skips a specified number of characters when reading a TextStream file.

object.Skip(characters)

Expand image Arguments

object

Required. Always the name of a TextStream object.

characters

Required. Number of characters to skip when reading a file.

Expand image Remarks

Skipped characters are discarded.

The following example illustrates the use of the Skip method:

JScript CopyCode image Copy Code
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);
}
Visual Basic Script CopyCode image Copy Code
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

Applies To:

TextStream Object

Expand image See Also

Reference

Close Method (FileSystemObject)
Read Method
ReadAll Method
ReadLine Method
SkipLine Method
Write Method (FileSystemObject)
WriteLine Method (FileSystemObject)
WriteBlankLines Method


SkipLine Method

Scripting Runtime Library
SkipLine Method
See Also
CollapseAll image DropDown image

Skips the next line when reading a TextStream file.

object.SkipLine( )

Expand image Remarks

The object is always the name of a TextStream object.

The following examples illustrate the use of the SkipLine method:

JScript CopyCode image Copy Code
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);
}
Visual Basic Script CopyCode image Copy Code
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 & "VBScript is fun!"
   Set f = fso.OpenTextFile("c:\testfile.txt", ForReading)
   f.SkipLine
   SkipLineInFile = f.ReadLine
End Function

Applies To:

TextStream Object

Expand image See Also

Reference

Read Method
ReadAll Method
ReadLine Method
Skip Method


Write Method (FileSystemObject)

Scripting Runtime Library
Write Method (FileSystemObject)
See Also
CollapseAll image DropDown image

Writes a specified string to a TextStream file.

object.Write(string)

Expand image Arguments

object

Required. Always the name of a TextStream object.

string

Required. The text you want to write to the file.

Expand image 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 CopyCode image Copy Code
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);
}
Visual Basic Script CopyCode image Copy Code
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

Applies To:

TextStream Object

Expand image See Also

Reference

WriteBlankLines Method
WriteLine Method (FileSystemObject)


WriteBlankLines Method

Scripting Runtime Library
WriteBlankLines Method
See Also
CollapseAll image DropDown image

Writes a specified number of newline characters to a TextStream file.

object.WriteBlankLines(lines)

Expand image Arguments

object

Required. Always the name of a TextStream object.

lines

Required. Number of newline characters you want to write to the file.

Expand image Remarks

The following example illustrates the use of the WriteBlankLines method:

JScript CopyCode image Copy Code
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);
}
Visual Basic Script CopyCode image Copy Code
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

Applies To:

TextStream Object

Expand image See Also

Reference

Write Method (FileSystemObject)
WriteLine Method (FileSystemObject)


WriteLine Method (FileSystemObject)

Scripting Runtime Library
WriteLine Method (FileSystemObject)
See Also
CollapseAll image DropDown image

Writes a specified string and newline character to a TextStream file.

object.WriteLine([string])

Expand image 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.

Expand image Remarks

The following example illustrates use of the WriteLine method:

JScript CopyCode image Copy Code
var fso, f;
fso = new ActiveXObject("Scripting.FileSystemObject");
f = fso.CreateTextFile("c:\\testfile.txt", true);
f.WriteLine("This is a test.");
f.Close();
Visual Basic Script CopyCode image Copy Code
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

Applies To:

TextStream Object

Expand image See Also

Reference

Write Method (FileSystemObject)
WriteBlankLines Method


FileSystemObject Objects (Scripting Runtime Reference)

Scripting Runtime Library
FileSystemObject Objects (Scripting Runtime Reference)
DropDown image

The following sections provide details about the FileSystemObject objects.

In This Section

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.


Drive Object

Scripting Runtime Library
Drive Object
See Also
CollapseAll image DropDown image

Provides access to the properties of a particular disk drive or network share.

Expand image Remarks

The following code illustrates the use of the Drive object to access drive properties:

JScript CopyCode image Copy Code
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);
}
Visual Basic Script CopyCode image Copy Code
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

Expand image Methods

The Drive object has no methods.

Expand image 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

Expand image See Also

Reference

Drives Collection
File Object
Files Collection
Folder Object
Folders Collection
GetDrive Method


File Object

Scripting Runtime Library
File Object
See Also
CollapseAll image DropDown image

Provides access to all the properties of a file.

Expand image Remarks

The following code illustrates how to obtain a File object and how to view one of its properties.

JScript CopyCode image Copy Code
function ShowFileInfo(filespec)
{
   var fso, f, s;
   fso = new ActiveXObject("Scripting.FileSystemObject");
   f = fso.GetFile(filespec);
   s = f.DateCreated;
   return(s);
}
Visual Basic Script CopyCode image Copy Code
Function ShowDateCreated(filespec)
   Dim fso, f
   Set fso = CreateObject("Scripting.FileSystemObject")
   Set f = fso.GetFile(filespec)
   ShowDateCreated = f.DateCreated
End Function

Expand image Methods

Copy Method | Delete Method | Move Method | OpenAsTextStream Method

Expand image 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

Expand image See Also

Reference

Drive Object
Drives Collection
Files Collection
Folder Object
Folders Collection


FileSystemObject Object

Scripting Runtime Library
FileSystemObject Object
CollapseAll image DropDown image

Provides access to a computer's file system.

Expand image Remarks

The following code illustrates how the FileSystemObject is used to return a TextStream object that can be read from or written to.

Expand image Code

JScript CopyCode image Copy Code
// JScript
var fso = new ActiveXObject("Scripting.FileSystemObject");
var a = fso.CreateTextFile("c:\\testfile.txt", true);
a.WriteLine("This is a test.");
a.Close();

Expand image Code

Visual Basic CopyCode image Copy Code
' 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

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.

Expand image 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 | GetFileVersion Method | GetFileName Method | GetFolder Method | GetParentFolderName Method | GetSpecialFolder Method | GetStandardStream Method | GetTempName Method | MoveFile Method | MoveFolder Method | OpenTextFile Method

Expand image Properties

Drives Property


Folder Object

Scripting Runtime Library
Folder Object
See Also
CollapseAll image DropDown image

Provides access to all the properties of a folder.

Expand image Remarks

The following code illustrates how to obtain a Folder object and how to return one of its properties:

JScript CopyCode image Copy Code
function ShowFolderInfo(folderspec)
{
   var fso, folder, s;
   fso = new ActiveXObject("Scripting.FileSystemObject");
   folder = fso.GetFolder(folderspec);
   s = folder.DateCreated;
   return(s);
}
Visual Basic Script CopyCode image Copy Code
Function ShowDateCreated(folderspec)
   Dim fso, f
   Set fso = CreateObject("Scripting.FileSystemObject")
   Set f = fso.GetFolder(folderspec)
   ShowDateCreated = f.DateCreated
End Function

Expand image Methods

Copy Method | Delete Method | Move Method | CreateTextFile Method

Expand image 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

Expand image See Also

Reference

Drive Object
Drives Collection
File Object
Files Collection
Folders Collection


TextStream Object

Scripting Runtime Library
TextStream Object
See Also
CollapseAll image DropDown image

Facilitates sequential access to file.

TextStream.{property  | method( )}

Expand image Arguments

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.

Expand image Remarks

In the following code, a is the TextStream object returned by the CreateTextFile method on the FileSystemObject:

JScript CopyCode image Copy Code
var fso = new ActiveXObject("Scripting.FileSystemObject");
var a = fso.CreateTextFile("c:\\testfile.txt", true);
a.WriteLine("This is a test.");
a.Close();
Visual Basic Script CopyCode image Copy Code
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.

Expand image Methods

Close Method | Read Method | ReadAll Method | ReadLine Method | Skip Method | SkipLine Method | Write Method | WriteBlankLines Method | WriteLine Method

Expand image Properties

AtEndOfLine Property | AtEndOfStream Property | Column Property | Line Property

Expand image See Also

Reference

Dictionary Object
FileSystemObject Object


FileSystemObject Collections

Scripting Runtime Library
FileSystemObject Collections
DropDown image

The following sections provide details about the 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.


Drives Collection

Scripting Runtime Library
Drives Collection
See Also
CollapseAll image DropDown image

Read-only collection of all available drives.

Expand image Remarks

Removable-media drives need not have media inserted for them to appear in the Drives collection.

The following example illustrates how to get the Drives collection using the Drives property and iterate the collection:

JScript CopyCode image Copy Code
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);
}
Visual Basic Script CopyCode image Copy Code
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
      Else
         n = "[Drive not ready]"
      End If
      s = s & n & "<BR>"
   Next
   ShowDriveList = s
End Function

Expand image Methods

The Drives collection has no methods.

Expand image Properties

Count Property | Item Property

Expand image See Also

Reference

Drive Object
Drives Property
File Object
Files Collection
Folder Object
Folders Collection


Files Collection

Scripting Runtime Library
Files Collection
See Also
CollapseAll image DropDown image

Collection of all File objects within a folder.

Expand image Remarks

The following example illustrates how to get a Files collection and iterate the collection:

JScript CopyCode image Copy Code
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);
}
Visual Basic Script CopyCode image Copy Code
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

Expand image Methods

The Files collection has no methods.

Expand image Properties

Count Property | Item Property

Expand image See Also

Reference

Drive Object
Drives Collection
File Object
Folder Object
Folders Collection


Folders Collection

Scripting Runtime Library
Folders Collection
See Also
CollapseAll image DropDown image

Collection of all Folder objects contained within a Folder object.

Expand image Remarks

The following example illustrates how to get a Folders collection and how to iterate the collection:

JScript CopyCode image Copy Code
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);
}
Visual Basic Script CopyCode image Copy Code
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

Expand image Methods

Add Method (Folders)

Expand image Properties

Count Property | Item Property

Expand image See Also

Reference

Drive Object
Drives Collection
File Object
Files Collection
Folder Object
SubFolders Property


Script Encoder Overview

Scripting Runtime Library
Script Encoder Overview
See Also
DropDown image

Script Encoder is a simple command-line tool that enables script designers to encode their final script so that Web hosts and Web clients cannot view or modify their source. Note that this encoding only prevents casual viewing of your code; it will not prevent the determined hacker from seeing what you've done and how.

Uses for Scripting

Web designers use scripting on Web pages and server-side active server pages (.ASP) to add virtually every kind of feature you can imagine. In addition, scripting is used by the Windows® Scripting Host (WSH) and in a number of other applications with equally impressive results.

Up to now, one of the shortcomings of using scripts is that they afford no protection of the intellectual property contained within, nor do they provide any assurance that what users get is what you created. Clever algorithms and carefully designed scripts were always completely visible because they were stored as plain text. As a result, script users at every level could see the script designer's code and could then take it, modify it, and make it their own. Obviously, this is not good if you're trying to get an edge in a very competitive environment.

With the introduction of scriptlets, protecting the source code becomes even more important. Script designers want to use this simple component architecture, but they don't necessarily want to share their source code with the world. After a script is encoded, changing any part of the resulting file will render it inoperable, thus ensuring the absolute integrity of your encoded script.

See Also

Concepts

Using Script Encoder
Script Encoder Syntax
Script Encoding Sample


Using Script Encoder

Scripting Runtime Library
Using Script Encoder
See Also
DropDown image

The Script Encoder encodes only scripting code, with all other file content left untouched to appear as plain text. To use the Script Encoder, develop and debug your script in the usual manner, then use this utility to encode your final script. The Script Encoder uses markers within your source code to identify where encoding should begin.

Example

For Visual Basic® Scripting Edition (VBScript), the following example illustrates how the encoding marker is used to expose a plain-text copyright message:

CopyCode image Copy Code
<SCRIPT LANGUAGE="VBScript">
'Copyright© 1998. XYZ Productions. All rights reserved.
'**Start Encode**
' Your code goes here.
</SCRIPT>

In JScript®, the encoding marker looks like this:

CopyCode image Copy Code
<SCRIPT LANGUAGE="JScript">
//Copyright© 1998. ZYX Productions. All rights reserved.
//**Start Encode**
// Your code goes here.
</SCRIPT>

When the Script Encoder is invoked, anything in the script block before the start marker is left unencoded, while everything else in the script block is encoded. Therefore, if the start marker is omitted, the entire scripting block is encoded, but if the start marker is at the end of the scripting block, nothing is encoded.

After the encoding takes place, you should be aware that the language designator in the <SCRIPT> tag has changed. For VBScript, the new designator looks like this:

CopyCode image Copy Code
<SCRIPT LANGUAGE="VBScript.Encode">

For JScript, the new designator looks like this:

CopyCode image Copy Code
<SCRIPT LANGUAGE="JScript.Encode">

The Script Encoder is invoked on the MS-DOS command line or in the Run dialog box as follows:

SRCENC [switches] inputfile outputfile

See Also

Concepts

Script Encoder Overview
Script Encoder Syntax
Script Encoding Sample


Script Encoder Syntax

Scripting Runtime Library
Script Encoder Syntax
See Also
DropDown image

Encodes scripting source code so it cannot be easily viewed or modified by users.

Syntax

SCRENC [/s] [/f] [/xl] [/l defLanguage ] [/e defExtension] input file output file

The Script Encoder syntax has these parts:

Part | Description
/s | Optional. Switch that specifies that the Script Encoder is to work silently, that is, produce no screen output. If omitted, the default is to provide verbose output.
/f | Optional. Specifies that the input file is to be overwritten by the output file. Note that this option destroys your original input source file. If omitted, the output file is not overwritten.
/xl | Optional. Specifies that the @language directive is not added at the top of .ASP files. If omitted, @language directive is added for all .ASP files.
/l defLanguage | Optional. Specifies the default scripting language (JScript® or VBScript) to use during encoding. Script blocks within the file being encoded that do not contain a language attribute are assumed to be of this specified language. If omitted, JScript is the default language for HTML pages and scriptlets, while VBScript is the default for active server pages. For plain text files, the file extension (either .js or .vbs) determines the default scripting language.
/e defExtension | Optional. Associates the input file with a specific file type. Use this switch when the input file's extension doesn't make the file type obvious, that is, when the input file extension is not one of the recognized extensions, but the file content does fall into one of the recognized types. There is no default for this option. If a file with an unrecognized extension is encountered and this option is not specified, the Script Encoder fails for that unrecognized file. Recognized file extensions are asa, asp, cdx, htm, html, js, sct, and vbs.
inputfile | Required. The name of the input file to be encoded, including any necessary path information relative to the current directory.
outputfile | Required. The name of the output file to be produced, including any necessary path information relative to the current directory.

Remarks

There are four kinds of files than can be processed by the Script Encoder. They are:

  • ASP. This format consists of a text active server page containing valid HTML and embedded scripting blocks within <SCRIPT> ... </SCRIPT> tags or <% ... %> tags. Applications that use this format include Microsoft® Internet Information Services (IIS). Recognized file extensions are .asp, .asa, and .cdx.

  • HTML. This format consists of a text file that contains valid HTML along with embedded script blocks. Applications using this scripting format include Microsoft FrontPage®, Microsoft® Visual InterDev™ and virtually all Web designers and browsers. Recognized file extensions are .htm and .html.

  • Plain text. This format consists of text file that contains only script with no surrounding tags. Applications using scripting format include Windows® Scripting Host (WSH) and Microsoft® Outlook®. Recognized file extensions are .js and .vbs, which are changed to .jse and .vbe, respectively, after encoding.

  • Scriptlet. This format consists of a text file that contains valid scriptlet code within <SCRIPT> ... </SCRIPT> tags. Recognized file extension is .sct and .wsh.

Examples

The following are examples of the use of the Script Encoder and a brief explanation of the results:

To encode input file test.html and produce output file encode.html, use:

CopyCode image Copy Code
        screnc test.html encode.html

To encode input file test.htm and overwrite the input file with the encoded output file, use:

CopyCode image Copy Code
        screnc /f test.htm

To encode all .ASP files in the current directory and place the encoded output files in c:\temp, use:

CopyCode image Copy Code
        screnc *.asp c:\temp

To encode all files in the current directory as .ASP files and place them in c:\temp, use: screnc /e asp *.* c:\temp

To encode input file test.htm and produce output file encode.htm, ensuring that all script blocks that don't have a language attribute specified use VBScript, use:

CopyCode image Copy Code
        screnc /l vbscript test.htm encode.htm

To encode all scriptlet files in the current directory and overwrite them with encoded files, while displaying no message, use:

CopyCode image Copy Code
screnc /s /f *.sct

See Also

Concepts

Script Encoder Overview
Using Script Encoder
Script Encoding Sample


Script Encoding Sample

Scripting Runtime Library
Script Encoding Sample
See Also
DropDown image

Here is a short example of a Web page that includes some JScript code that needs protecting:

Example

CopyCode image Copy Code
<HTML>
<HEAD>
<TITLE>Script Encoder Sample Page</TITLE>
<SCRIPT LANGUAGE="JScript">
<!--//
//Copyright© 1998 Microsoft Corporation. All Rights Reserved.
//**Start Encode**
function verifyCorrectBrowser(){
  if(navigator.appName == "Microsoft Internet Explorer")
    if (navigator.appVersion.indexOf ("5.") >= 0)
      return(true);
    else
      return(false);
}
function getAppropriatePage(){
  var str1 = "Had this been an actual Web site, a page compatible with ";
  var str2 = "browsers other than ";
  var str3 = "Microsoft Internet Explorer 5.0 ";
  var str4 = "would have been loaded.";
  if (verifyCorrectBrowser())
    document.write(str1 + str3 + str4);
  else
    document.write(str1 + str2 + str3 + str4);
}
//-->
</SCRIPT>
</HEAD>
<BODY onload="getAppropriatePage()">
</BODY>
</HTML>

Here's the same page as it appears after being run through the Script Encoder:

CopyCode image Copy Code
<HTML>
<HEAD>
<TITLE>Script Encoder Sample Page</TITLE>
<SCRIPT LANGUAGE="JScript.Encode">
<!--//
//Copyright© 1998 Microsoft Corporation. All Rights Reserved.
//**Start Encode**#@~^QwIAAA==@#@&0;mDkWP7nDb0zZKD.n1YAMGhk+Dvb`@#@&P,kW`UC7kLlDGDcl22gl:n~{'~Jtr1DGkW6YP&xDnD+OPA62sKD+ME#@#@&P,~~k6PvxC\rLmYGDcCwa.n.kkWU bx[+X66Pcr*cJ#,@*{~!*P~P,P~.YEMU`DDEbIP,P,+s/n@#@&P~P,~PM+O;Mx`WC^/n#pN6EU1YbWx,oObaw.WaDrCD+nmL+v#@#@&~P7lMPdY.q,'~J_CN,Y4rkP4nnPCx,C1Y;mV,+(PkrY~~l,wCLPmKhwmYk(snPSkDt~JI@#@&P~\m.PkY.+,'PE8MWA/.kPGDtDPDtmUPri@#@&,P-CMP/D.&,'Pr\rmMWkWWY~(YnDnY,2a2^WDn.,* !,Ep@#@&,P7lD,/D.c,'~JSW;s9Ptm-+,4+U~VKl9+[REI,Pr0,c\DrWHZW..mOAMGS/nM`*#@#@&P,~P9W^Es+UOchDbO+v/YMq~_,/DDfPQ~kY.c*IP,+sd@#@&~~,P[W1;s+UDRSDkD+vdYMF~_,/O.yP_,dYM&P3~dYMc*iNz&R @*^#~@
//-->
</SCRIPT>
</HEAD>
<BODY onload="getAppropriatePage()">
</BODY>
</HTML>
Note Note

After encoding, if you change even one character in the encoded text, the integrity of the entire script is lost and it can no longer be used.

See Also

Concepts

Script Encoder Overview
Using Script Encoder
Script Encoder Syntax


Script Components

Windows Script Components
Script Components
DropDown image

Microsoft Windows Script Components provide you with an easy way to create COM components using scripting languages such as Microsoft Visual Basic Scripting Edition (VBScript) and Microsoft JScript. Use script components as COM components in applications such as Microsoft Internet Information Services (IIS), Microsoft Windows Script Host, and any other application that can support COM components.

In This Section

Script Component Tutorial

Provides an overview of script component technology, and explains how to create and use script components.

Script Component Reference

Describes the XML elements and methods available when creating script components.

Behavior Handler Reference

Describes the events, methods and properties you can use with Behavior Handlers.


Script Component Tutorial

Windows Script Components
Script Component Tutorial
DropDown image

Windows Script Components provide a lightweight, component-creation mechanism that can be combined with other key technologies in the Windows platform to create components that adjust to fit the applications from which they are being called. The script component tutorial shows how this is done.

In This Section

Script Components Overview

Learn what script components are and how to use them.

Creating Script Components

Create a script component.

Using Script Components

Use a script component in your applications.

Implementing ASP Script Components

Create a script component that incorporates the functionality of Active Server Pages (ASP), allowing you to isolate and reuse ASP logic.

Implementing DHTML Behavior Script Components

Create a script component that can be used in Microsoft® Internet Explorer 5.0 to define behaviors.

Related Sections

Script Component Reference

Describes the XML elements and methods available when creating Windows Script Components.

Behavior Handler Reference

Describes the events, methods and properties you can use with Behavior Handlers.


Script Components Overview

Windows Script Components
Script Components Overview
DropDown image

Windows® Script Components are an exciting new technology that allows you to create powerful, reusable COM components with easy-to-use scripting languages such as Microsoft® Visual Basic® Scripting Edition (VBScript) and Microsoft® JScript®.

How to Create and Use Script Components

  • Introducing Script Components Learn what script components are, and the advantages to using them.

  • How Script Components Work Understand what script component technology consists of, and how to create script components.


Introducing Windows Script Components

Windows Script Components
Introducing Windows Script Components
See Also
DropDown image

Windows® Script Components provide you with an easy way to create powerful, reusable COM components in script. You create script components using any scripting language that supports the Microsoft® ActiveX® Scripting interfaces. Script languages that support these interfaces include JScript, Microsoft® Visual Basic® Scripting Edition (VBScript), PERLScript, PScript, and Python.

COM Support

This new script component technology supports common types of COM components, such as Automation, and is extensible with add-ons such as DHTML behaviors.

Script Components:

  • Are small and efficient.

  • Are easy to create, maintain, and deploy.

  • Provide the ability to create COM components.

  • Provide access to a broad range of system services.

Using script components, you can create COM components for a variety of tasks, such as performing middle-tier business logic, accessing and manipulating database data, adding transaction processing to applications, and adding interactive effects to a Web page using DHTML Behaviors.

Note Note

For more information about ActiveX Scripting interfaces, see the Microsoft Scripting Technologies Web site at www.microsoft.com.

See Also

Concepts

How Script Components Work

Other Resources

Creating Script Components


How Script Components Work

Windows Script Components
How Script Components Work
See Also
DropDown image

Windows® Script Component technology consists of three pieces: the script component run-time, interface handlers, and your script component file.

Script Component Technology Parts

  • The script component run-time (Scrobj.dll) helps dispatch COM requests to your scripts. In COM terms, Scrobj.dll functions as the inproc server for script components.

  • Interface handlers are compiled components that implement specific COM interfaces. Different interface handlers come ready to work as specific types of COM components.

    The most commonly used interface handlers, including the COM Automation interface handler, an ASP interface handler, and a handler for DHTML Behaviors, are already built into the script component run-time. Others are available as add-on components, or embedded into specific applications.

  • Your script component file is a .wsc file. Script component files are XML (Extensible Markup Language) files that contain information about what type of COM component you want to create (that is, what interface handlers you want to use). Then, depending on what functionality the handler makes available, you write script in your script component to implement those interfaces.

The script component run-time serves as an entry point for the host application. The complexities of COM, including the implementation of such COM-standard interfaces as IUnknown, are embedded in the various interface handlers. Your script component contains only the script required to implement the functionality of the COM component.

For example, one of the most common types of COM components is an Automation component, which is a component with properties and methods that can be called from other applications. The low-level COM interfaces required to implement this functionality — such as dispatching to the correct function when a method is called — are built into an Automation interface handler. In your script component file, you define the properties, methods, and events you want to expose, and the Automation handler makes sure they are called correctly when the host application needs them.

See Also

Concepts

Introducing Windows Script Components

Other Resources

Creating Script Components


Creating Script Components

Windows Script Components
Creating Script Components
DropDown image

Creating a Windows® Script Component (.wsc) file is much like creating any file containing scripts, including HTML files. The following topics provide information about the basic layout of a script component file, as well as information about creating registration information and type libraries.

In This Section

Script Component File Contents

Learn about the XML (Extensible Markup Language) elements required for a script component.

Using The Script Component Wizard

Use the Script Component Wizard to create a script component file.

Creating Registration Information

Create information in the script component file that is used to register it as a COM component.

Exposing Methods

Add methods to your script component.

Exposing Properties

Add properties to your script component.

Exposing Events

Define and fire custom events in your script component.

Creating a Script Component Type Library

Create a type library for your script component so it can be used more easily in the host application.

Referencing Other Components

Include global references to objects you need in your scripts, to external type libraries that provide constants for use in your scripts, or to resources that point to strings or values not hard-coded into your scripts.

Referencing Another Script Component in the Same Package

When including multiple script components in the same package, embed the functionality of one script component inside another.

Checking For Errors in Script Component Files

Add compile-time error checking to your script component.

Script Component Files and XML Conformance

Learn about XML conformance.


Script Component File Contents

Windows Script Components
Script Component File Contents
See Also
DropDown image

Windows® Script Component files are XML (Extensible Markup Language) that are much like HTML files, but contain special elements that define the script component and its behavior. The elements used for defining script components are not HTML tags, but are XML elements specifically used for script component definitions.

Elements of a Basic Script Component File

  • <component> and <package> elements The <component> element encloses one entire script component definition. Multiple <component> elements can appear in the same .wsc file, and are contained within a master <package> element.

  • <registration> element Includes information used to register your script component as a COM component. This element might not be required if the host application (such as Microsoft® Internet Explorer 5.0) does not directly use the Windows registry when creating an instance of the script component.

  • <public> element Encloses definitions for properties, methods, and events that your script component exposes. The definitions point to variables or functions defined in a separate <script> block.

  • <implements> element Specifies the COM interface handler for the script component, which determines what type of COM component the script component will be. For example, by specifying <implements type=ASP>, you implement the ASP interface handler and therefore get access to the ASP object model in your script component.

    The <public> element is used to specify that a script component implements the COM Automation interface handler. Therefore, you don't need to create an <implements> element for the Automation handler.

    Note Note

    The script component run-time includes interface handlers for Automation (exposed using the <public> element), for ASP, and for Internet Explorer 5.0 DHTML Behaviors. Other interface handlers are available as external DLLs. For more information about additional interface handlers and script components, see the Microsoft Scripting Technologies Web site.

  • <script> element Contains the script used to implement the logic of your script component, depending on what type of COM component you are creating. For example, if you are creating a COM Automation component, you declare properties, methods, and events in a <public> element, and then write the script to define them in one or more <script> elements.

  • <object> element Contains information about an object that you use in your script, such as another COM component.

  • <resource> elements Contain values that should not be hard-coded into script component code. Resource elements can include information that might change between versions, strings that might be translated, and other values.

  • <reference> element References a type library you want to use in script.

  • <comment> elements Contain text that is ignored when the script component is parsed and executed.

    Note Note

    If you are concerned that the .wsc files you create contain XML that conforms to XML standards, you can specify that the script component's XML parser check the XML syntax. For example, this is useful if you think you might someday use an XML editor to work with your files. Otherwise, however, it is not usually a concern. For more details, see Script Component Files and XML Conformance.

Skeleton Script Component File

The following example illustrates how to construct a script component file.

CopyCode image Copy Code
<?XML version="1.0"?>
<package>
<?component error="true" debug="true"?>

   <comment>
      This skeleton shows how script component elements are
      assembled into a .wsc file.
   </comment>

<component id="MyScriptlet">
   <registration
      progid="progID"
      description="description"
      version="version"
      clsid="{00000000-0000-0000-000000000000}"/>

   <reference object="progID">

   <public>
      <property name="propertyname"/>
      <method name="methodname"/>
      <event name="eventname"/>
   </public>

   <implements type=COMhandlerName id=internalName>
      (interface-specific definitions here)
   </implements>

   <script language="VBScript">
      <![CDATA[
      dim propertyname
      Function methodname()
      ' Script here.
      End Function
      ]]>
   </script>

   <script language="JScript">
      <![CDATA[
      function get_propertyname()
      { // Script here.
      }
      function put_propertyname(newValue)
      { // Script here.
         fireEvent(eventname)
      }
      ]]>
   </script>

   <object id="objID" classid="clsid:00000000-0000-0000-000000000000">
   <resource ID="resourceID1">string or number here</resource>
   <resource ID="resourceID2">string or number here</resource>
</component>
</package>
Note Note

In XML, you can specify elements without content (attributes only), such as the <property> and <method> elements in the previous example, by closing the element with />.

Note that:

  • The <?XML ?> declaration at the top indicates that this is an XML file and that it conforms to XML protocol. This declaration is optional; if you leave it out, you can use slightly looser syntax when creating the script component's elements. For details, see Script Component Files and XML Conformance.

  • The <package> element is optional in this example, because the file contains only one <component> element.

  • The <?component?> processing instruction includes attributes for specifying the error checking options. For details, see Checking For Errors in Script Component Files. If you do not include this element, the default options are all false.

  • A <comment> element can appear anywhere in the script component.

  • A <registration> element is not required in all cases. For example, a script component that implements the DHTML Behaviors interface handler in Internet Explorer 5.0 does not need to be registered, because Internet Explorer directly instantiates the behaviors as they are detected on the page. For details about registration requirements, see the documentation for the interface handler you are implementing, and note also which host the script component will be used in.

  • A <reference> element allows you to include a type library in the script component so you can use the library's constants in your script.

  • The <public> element encloses <property>, <method>, and <event> elements. The script that defines these appears later in the script component file.

  • The <implements> element is used to make available non-default COM interfaces. For example, you can expose the ASP interface with an <implements> type such as the following:

    CopyCode image Copy Code
    <implements type="ASP" id="iASP">

    The exact elements that appear inside an <implements> element depend on what interface you are implementing.

    Note Note

    The <implements> element is shown here with an id attribute. However, this attribute is optional, except in cases where you must disambiguate objects or variables. For details, see the <implements> element.

  • In this skeleton, there are two script elements, one for VBScript and one for JScript. If you are using only one scripting language, you do not need more than one <script> element. Because the <?XML ?> declaration appears at the top of the file, a CDATA section is required to make the script in the <script> element opaque. For details, see Script Component Files and XML Conformance.

  • The <object> element creates a reference to an object you want to use in script within the script component.

After creating the skeleton, fill in the elements to define the script component's functionality, depending on which interface handler you are implementing.

See Also

Tasks

Exposing Properties

Concepts

Checking For Errors in Script Component Files
Creating a Script Component Type Library
Creating Registration Information
Exposing Events
Exposing Methods
Implementing ASP Script Components
Implementing DHTML Behavior Script Components
Script Component Files and XML Conformance
Using the Script Component Wizard


Using the Script Component Wizard

Windows Script Components
Using the Script Component Wizard
See Also
DropDown image

The Windows® Script Component package includes a Script Component Wizard that automates the process of creating a script component (.wsc) file.

Functions that the Wizard Performs

  • Creates the .wsc file and adds basic XML elements.

  • Prompts for and creates registration information.

  • Prompts for the type of interface handler you want the script component to use.

  • Prompts for properties you want to expose and creates the necessary elements in the scripting language you specify.

  • Prompts for methods you want to expose and creates the necessary elements in the scripting language you specify.

  • Prompts for events that the script component can fire and creates the skeleton event elements.

    Note Note

    You can download and install the Script Component Wizard from http://msdn.microsoft.com/downloads. In the left pane, expand the Web Development node. Expand the Windows Script node and select Component Wizard.

The wizard creates a skeleton script component with information you provide, and writes it out as a .wsc file. Edit the .wsc file and add your script to create the script component's functionality.

Note Note

The wizard creates a script component file containing the <?XML ?> declaration at the top, meaning that the contents of the file must be XML-conformant. For more details, see Script Component Files and XML Conformance.

See Also

Concepts

Script Component File Contents
Creating Registration Information
Script Component Files and XML Conformance

Other Resources

Creating Script Components


Creating Registration Information

Windows Script Components
Creating Registration Information
See Also
DropDown image

If the host application requires it, you can register a Windows® Script Component as a COM component using a program such as Regsvr32.exe. Registration places information about the COM component in a public location (in Windows, registration information is stored in the Windows registry).

Registration Information

By reading the registration information, applications can find and load the COM component.

Note Note

Registration is not required in every case. For example, a script component that implements the DHTML Behaviors interface handler in Internet Explorer 5.0 does not need to be registered, because Internet Explorer registers the behaviors as they are detected on the page. For more details about using Behaviors, see the "Using DHTML Behaviors" topic on the Microsoft Site Builder Network (SBN) Web site. If the host application supports monikers, you can also create an instance of a script component without registering it.

When you specify registration, the most important information is:

  • A program ID (prog ID), which is the name used in the host application when creating an instance of the script component. For example, if your script component's program ID is Component.MyComponent, you can create an instance of it in Microsoft® Visual Basic® using a statement such as the following:

    CopyCode image Copy Code
    Set Component = CreateObject("Component.MyComponent")

  • A class ID, which is a GUID (globally unique ID) that uniquely identifies your script component. You can generate a GUID with a program such as Uuidgen.exe.

    Note Note

    If you create a script component using the Script Component Wizard, the wizard automatically creates a program ID and class ID for you. For details, see Using The Script Component Wizard.

Registration information also includes a description and a version number.

The registration program can create a class ID for your script component when it is registered. However, it is highly recommended that you provide a class ID for the script component yourself, to ensure that your script component has the same class ID on all computers on which it is registered. Allowing the registration program to create a class ID can also cause problems if you use the script component with development tools that store class IDs. If the registration creates a new class ID each time, it will not match the ID stored by the application.

To create registration information for the script component

  • Create an <registration> element that includes at least a program ID, and optionally, a class ID, description, and version, as shown in the following example:

    CopyCode image Copy Code
    <registration
description="My Test Component"
progid="Component.TestScript"
version="1"
classid="{2154c700-9253-11d1-a3ac-0aa0044eb5f}"/>
    Note Note

    The registration attributes can appear in any order in the <registration> element.

Running Script During Registration

The script component <registration> element also allows you to include script that will be executed when the script component is registered and unregistered. For example, you can post a message that the script component has been registered.

To run script during registration and unregistration

  • In the <registration> element, include an <script> element. To run script during registration, write a register( ) function. To run script when the script component has been unregistered, include an unregister( ) function.

    The following example shows how to post messages when the script component is registered or unregistered.

    Note Note

    A CDATA section is required to make the script in the <script> element opaque. For details, see Script Component Files and XML Conformance.

    CopyCode image Copy Code
    <registration
   description="My Test Component"
   progid="Component.TestScript"
   version="1"
   classid="{2154c700-9253-11d1-a3ac-0aa0044eb5f}">

   <script language="VBScript">
   <![CDATA[
      Function register()
         MsgBox "Component 'My Test Component' registered."
      End Function
      Function unregister()
         MsgBox "Component 'My Test Component' unregistered."
      End Function
   ]]>
   </script>
</registration>

Registering for Remote Access

If you are deploying your script component in a distributed environment, you can specify that the script component can be instantiated remotely. For example, you might be creating a script component designed to run on a server, but which will be called from code on a client. This scenario is possible if the client and server machines are properly configured with DCOM, which provides the mechanism for passing object pointers to the client from the server.

To register a script component for remote access

  • Include the remotable attribute in the <registration> element, as shown in the following example:

    CopyCode image Copy Code
    <registration
   description="My Test Component"
   progid="Component.TestScript"
   version="1"
   classid="{2154c700-9253-11d1-a3ac-0aa0044eb5f}"
   remotable=true/>

For more details about creating instances of a script component remotely, see Using a Script Component in an Application.

See Also

Concepts

Script Component File Contents
Using the Script Component Wizard
Creating a Script Component Type Library
Checking For Errors in Script Component Files
Script Component Files and XML Conformance


Exposing Methods

Windows Script Components
Exposing Methods
See Also
DropDown image

Methods are implemented as functions or subroutines in your Windows® Script Component file.

Procedures

To expose a method

  1. Create a <public> element as a child of the <component> element.

  2. In the <public> element, include a <method> element. The method element can optionally include one or more <parameter> elements to define the method's parameters.

  3. Write a procedure in any scripting language to implement the function. Place the procedure in a <script> element outside the <implements> element but within the <component> element. Be sure the function name matches the functionName, or if you did not specify a functionName, the methodName name you specified in the <method> element.

    For example, the following example shows a fragment from a script component file with two methods, factorial and getRandomNumber.

    Note Note

    A CDATA section is required to make the script in the <script> element opaque. For details, see Script Component Files and XML Conformance.

    CopyCode image Copy Code
    <public>
   <method name="factorial"/>
   <method name="random" internalName="getRandomNumber">
      <parameter name="upperBound"/>
      <parameter name="seed"/>
   </method>
</public>

<script language="VBScript">
Function factorial(n)
   <![CDATA[
   If isNumeric(n) Then
      If n <= 1 Then
         factorial = 1
      Else
         factorial = n*factorial(n-1)
      End If
   Else
      factorial = -2   ' Error code.
   End If
End Function

Function getRandomNumber(upperBound, seed)
   getRandomNumber = Cint(upperBound * Rnd(seed) + 1)
End Function
]]>
</script>

You can specify a default method for a script component so the host application can invoke the method without explicitly calling it. For example, if you have exposed a method called factorial and marked it as the default, you can call it in the following ways in Visual Basic:

CopyCode image Copy Code
Set component = CreateObject("component.MyComponent")
n = component.factorial(4)   ' Calls factorial method explicitly.
n = component(4)   ' Calls factorial method as default.

To specify a default method, include an attribute assigning a special dispatch identifier (a dispid) to the method. For more information about dispids, see Exposing Events.

To specify a default method

  • In the <method> element, include the attribute dispid="0", as shown in the following example:

    CopyCode image Copy Code
    <public>
   <method name="factorial" dispid="0"/>
</public>
    Note Note

    This technique can be used to assign either a default method or a default property, but not both. There can be only one element in the script component with the dispid of zero.

See Also

Tasks

Exposing Properties

Concepts

Exposing Events
Script Component File Contents


Exposing Properties

Windows Script Components
Exposing Properties
See Also

You can expose properties in two ways:

  • As simple values The property is simply a global variable that can be read and written by the script component's user. Because the value is stored in a global value, you can manipulate it in your Windows® Script Component file's scripts.

  • As functions The property is defined using a function. This allows you to calculate a property value, and to control whether a property is read-only, read-write, or write-only.

You can also mark a property as the default value for a script component.

To expose a property as a simple value

  1. Create a <public> element as a child of the <component> element.

  2. In the <public> element, include a <property> element that specifies the variable used to store property value.

  3. To initialize the value of a simple property, create a global variable in the <script> element with a name matching propertyName (or propertyVariable, if you specified that) and assign it a value.

  4. The following script component fragment illustrates two properties (name and tag) exposed as simple values. The properties are initialized using global variables in the <script> element.

    Note Note

    A CDATA section is required to make the script in the <script> element opaque. For details, see Script Component Files and XML Conformance.

    CopyCode image Copy Code
    <public>
   <property name="name"/>
   <property name="tag" internalName="tagVar"/>
</public>

<script language="VBScript">
   <![CDATA[
   Dim name
   name = "script component"   ' Initializes the value of name property.
   Dim tagVar
   tagVar = "10"   ' Initializes the value of tag property.
   ]]>
</script>

To expose a property using functions

  1. In the script component file's <public> element, include a <property> element that contains a <get> element to define the read function and a <put> element to define the write function. If you do not include the <put> element, the property will be read-only. If you do not include the <get> element, the property will be write-only.

  2. Write procedures in a <script> element outside the <public> element to implement the functions. The function for setting the property's value — the put function — must accept a single parameter, the value to set the property to.

    The names of the procedures must match the internal names you specified in the <property> element. If you did not specify an internalName attribute, the names of the functions must be the name of the function with the get_ prefix for a read function, and with a put_ prefix for the write function.

  3. For example, the following script component fragment is an example of a script component file that exposes three properties: sname, dateOfBirth, and age. The dateOfBirth property is defined by functions so it can include error checking. The age property is calculated, and is therefore defined as read-only.

    Note Note

    A CDATA section is required to make the script in the <script> element opaque. For details, see Script Component Files and XML Conformance.

    CopyCode image Copy Code
    <public>
   <property name="sname"/>
   <property name="age">
      <get internalName="readAge"/>
   </property>
   <property name="dateOfBirth">
      <get internalName="readDOB"/>
      <put internalName="writeDOB"/>
   </property>
</public>

<script language="VBScript">
<![CDATA[
Dim sname   ' Read-write sname property (no functions).
Dim gDOB   ' Global variable used to store date of birth.

Function readDOB()
   ' Gets value of dateOfBirth property.
   readDOB = gDOB
End Function

Function writeDOB(newDOB)
   ' Sets value of dateOfBirth property.
   If isDate(gDOB) Then
      'Error checking
      gDOB = newDOB
   End If
End Function

Function readAge()
   ' Calculates read-only age property.
   If isDate(gDOB) Then
      dobM = DatePart("m", gDOB)
      dobD = DatePart("d", gDOB)
      dobY = DatePart("yyyy", gDOB)
      todayY = DatePart("yyyy", Date)
      age = todayY - dobY

      ' Adjust if birthday has not yet occurred this year.
      bday = DateValue(dobM & "/" & dobD & "/" & todayY)
      If DateDiff("d", bday, DateValue(Date)) < 0 Then
         age = age - 1
      End If
      readAge = age
   End If
End Function
]]>
</script>

You can specify a default property for a script component so the host application can get or set the property's value without explicitly naming the property. For example, if you have exposed a property called sname and marked it as the default, you can work with it in either of these ways in Visual Basic:

CopyCode image Copy Code
Set component = CreateObject("Component.MyComponent")
n = component.sname   ' Gets property explicitly.
n = component   ' Gets value of sname as default.

To specify a default property, include an attribute assigning a special dispatch identifier (a dispid) to the method. For more information about dispids, see Exposing Events.

To specify a default property

  • In the <property> element, include the attribute dispid="0", as in the following example:

    CopyCode image Copy Code
    <property name="sname" dispid="0"/>
    Note Note

    This technique can be used to assign either a default property or a default method, but not both. There can be only one element in the script component with the dispid of zero.

See Also

Concepts

Exposing Events
Exposing Methods
Script Component File Contents
Script Component Files and XML Conformance


Exposing Events

Windows Script Components
Exposing Events
See Also
DropDown image

To add event capability to a Windows® Script Component:

  • Declare each event that you want to be able to fire.

  • Call a function to fire the event as required in the script component.

Some host environments also require that you generate a type library which they use to bind to events. For details, see Creating a Script Component Type Library.

Note Note

The Behavior handler exposes events in a slightly different way. For details, see Exposing Custom Events in Behavior Script Components.

Declaring Events

Each event you want to be able to fire must be individually declared.

To declare an event

  1. Create a <public> element as a child of the <component> element.

  2. In the <public> element, include an <event> element for each event you want to declare.

  3. For example, the following script component fragment shows how to expose two events:

    CopyCode image Copy Code
    <public>
   <property name="sname"/>
   <method name="factorial"/>
   <event name="namechanged"/>
   <event name="querydone"/>
</public>

Specifying Dispatch Identifiers

COM programming provides event notification via dispatch identifiers (each referred to as a dispid), which are integer values that identify a component's events. The dispid is compiled into the component's type library and then used by the host application to bind to events.

The process of creating a type library for script components automatically generates dispids for your script component's events. However, if you prefer, you can specify your own dispids. Doing so allows you to:

  • Guarantee that events in your script component will always have the same dispid. If the type library generator assigns dispids, they can change each time the library is generated.

  • Map events in your script component to dispids with specific numbers. For example, if you want to fire a standard COM event such as an error notification, you can map your event to the values used by convention in COM.

To specify a dispid for an event, include the dispid attribute in the <event> element, as in the following example:

CopyCode image Copy Code
<public>
   <event name="namechanged" dispid="22">
</public>

Dispids must be unique within the script component. You can specify a negative value for a dispid to map to conventional events, but must use only specified ranges, such as -999 to -500 for controls. For details about reserved dispid ranges, refer to documentation for DISPID in the MSDN library.

Note Note

The dispid number zero is used to identify a default method or property. For more details, see Exposing Methods and Exposing Properties.

Firing an Event

You can fire an event by calling the fireEvent method, specifying the name of the event to fire. You cannot fire events that you did not expose in the <implements> element. You can fire an event in any script in your script component file. For example, the following illustrates how you can fire an event when a property value changes.

CopyCode image Copy Code
<script language="VBScript">
<![CDATA[
Sub put_lowercaseName(newLCName)
   name = newLCName
   fireEvent("namechanged")
End Sub
]]>
</script>

See Also

Tasks

Exposing Properties

Concepts

Exposing Custom Events in Behavior Script Components
Exposing Methods
Handling Script Component Events in the Host Application
Script Component File Contents


Creating a Script Component Type Library

Windows Script Components
Creating a Script Component Type Library
See Also
DropDown image

You can generate a type library for your Windows® Script Component containing information about its interfaces and members. In some host applications (such as Visual Basic), type libraries are necessary to enable events for the script component, while in other host applications, type libraries are optional. However, even if a type library is not required, generating one can make working with a script component easier and less error-prone in the host application.

For example, if you are using Visual Basic as your host application, use the References dialog box to select a script component's type library. This allows you to bind events to the script component and make them visible in Visual Basic. In addition, when you are writing Visual Basic code that references the script component, Visual Basic uses the type library information in statement completion and in the Object Browser so you can easily see and use properties, methods, and events that the script component exposes.

Note Note

For information about using a type library in the host application, refer to the application's documentation.

Procedures

To create a script component type library

  • In Windows Explorer, right-click the script component .wsc file, and then choose Generate Type Library.

    A .tlb file is generated for the script component with the same name as the script component file, written to the folder where the .wsc file is, and registered in the Windows registry.

For more precise control over generating type libraries, you can generate the type library dynamically from script inside the script component file, or you can use a command-line interface.

Generating Type Libraries Dynamically

The script component run-time includes an Automation interface implemented by the Component.TypeLib object. You can use this object in script to generate a type library from within the script component file. This is particularly useful for creating a type library automatically when the script component is registered.

To create a script component type library dynamically

  1. In script inside the script component file, create an instance of the Component.TypeLib object by using syntax such as the following:

    CopyCode image Copy Code
    set oTL = CreateObject("Scriptlet.TypeLib")

  2. Set the following properties of the Component.TypeLib object:

    Property/Method Description

    AddURL

    (Method) Adds the URL of the script component file from which to generate the type library. You can call this method property multiple times to include multiple script components in the type library.

    Path

    (Property) The path and file where the type library will be written. The default path is the current directory and the default name is the name of the script component file with a .tlb extension. If the object is unable to create the specified library, it defaults to creating a type library called component.tlb.

    Doc

    (Property) A string containing any information that is stored in the registry with the type library information.

    GUID

    (Property) A GUID for the type library. (This is not the GUID for the script component.) If you do not provide one, the TypeLib object will create one, but then the type library will have a different GUID on each machine. The GUID must be exactly in this format, where x represents a hex value:

    CopyCode image Copy Code
    {xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx}

    Name

    (Property) The internal name for the type library. This name is displayed in some applications, such as the Visual Basic Object Browser.

    MajorVersion

    (Property) An integer value you assign.

    MinorVersion

    (Property) An integer value you assign.

  3. Call the type library object's Write method to create the .tlb file, then register it.

  4. If you want to create an additional type library, call the TypeLib object's Reset method to clear the list of script component files in the AddURL property, reset the URLs and any other properties you want, and then call the Write method again.

For example, the following script in a <registration> element creates a type library dynamically.

Note Note

A CDATA section is required to make the script in the <script> element opaque. For details, see Script Component Files and XML Conformance.

CopyCode image Copy Code
<registration
   description="My Test Component"
   progid="Component.TestScript"
   version="1"
   classid="{2154c700-9253-11d1-a3ac-0aa0044eb5f}">
   <script language="VBScript">
   <![CDATA[
   Function Register()
      Set oTL = CreateObject("Scriptlet.TypeLib")
         oTL.AddURL "d:\components\MyComponent.wsc"   ' Script component URL.
         oTL.AddURL "d:\components\YourComponent.wsc"
         oTL.Path = "d:\components\MyComponent.tlb"   ' .tlb path.
         oTL.Doc = "Sample component typelib"   ' Documentation string.
         oTL.GUID = "{a1e1e3e0-a252-11d1-9fa1-00a0c90fffc0}"
         oTL.Name = "MyComponentTLib" ' Internal name for tlb.
         oTL.MajorVersion = 1
         oTL.MinorVersion = 0
         oTL.Write ' Write tlib to disk.
         oTL.Reset ' Clear list of URLs in AddURL/.
      End Function
   ]]>
   </script>
</registration>

Command-line Interface

If you are comfortable using the Command Prompt window, you can call the Rundll32.exe program to create type libraries.

To create a type library from the command prompt

  • Call Rundll32.exe using this syntax:

    CopyCode image Copy Code
    rundll32.exe path\scrobj.dll,TypeLib options

    Where:

    • path The path where Scrobj.dll is located on your computer.

    • options A set of flags and values you can use to specify type library information in the form -flag:value. You can specify the options in any order. The following flags are supported, with values as described under the previous section, To create a script component type library dynamically.

      -name:Name

      -file:Path

      -doc:\"Doc\"

      -guid:GUID

      -major:MajorVersion

      -minor:MinorVersion

      -URL:AddURL

For example, the following command creates a type library called MyComponent.tlb from the script component MyComponent.wsc (the command is wrapped for clarity):

CopyCode image Copy Code
rundll32.exe c:\winnt\system32\scrobj.dll,TypeLib
   -name:MyComponentTLib -file:d:\components\MyComponent.tlb
   -doc:\"Sample component typelib\"
   -guid:{a1e1e3e0-a252-11d1-9fa1-00a0c90fffc0} -major:1 -minor:0
   -URL:d:\components\MyComponent.wsc

Troubleshooting Type Libraries

The process of generating a type library can fail for various reasons. The error you see might not be clear enough in all cases to make it obvious where the problem lies. If you are unable to generate a type library, review the following list of likely causes for the failure.

  • If a property is defined by functions, the get and put functions must have the same number of arguments with the same names. For details, see Exposing Properties.

    Note Note

    It is possible to define a script component in which the get and put property functions have different numbers of arguments, but you cannot create a type library for that script component.

  • If you are exposing events, you cannot use the same dispatch identifiers (dispid) more than once in a script component. Additionally, you cannot use a negative value for the dispid unless it is within a specified range. For details, see Exposing Methods.

  • The ID attributes of elements in the script component must be unique. If you are generating a type library from more than one script component, then the IDs must be unique in the type library as a whole.

See Also

Concepts

Script Component File Contents
Creating Registration Information
Checking For Errors in Script Component Files
Script Component Files and XML Conformance


Referencing Other Components

Windows Script Components
Referencing Other Components
See Also
DropDown image

Your Windows® Script Component can include references to external components that you need to create the script component, such as:

  • Additional COM objects

  • Type libraries

  • Resources, such as numbers and text, that you do not want to hard-code into your script component's scripts.

Referencing Additional COM Components

In your script component, it might be necessary to create instances of other COM components as needed. You can do so in two ways:

  • In script Create instances of other objects directly in your script. For example, you can use the CreateObject function in Microsoft® Visual Basic® Scripting Edition (VBScript) or the new ActiveXObject Object in JScript.

  • Using an OBJECT element Use an <object> element similar to the <OBJECT> tag you use in HTML pages. Using an <object> element makes objects globally available to any script and allows scripting tools to provide statement completion. It also provides a convenient way to summarize and document the objects you use in your script component.

    Note Note

    Although <object> elements in script components are similar to <OBJECT> tags in HTML pages, the list of attributes for an <object> element in a script component is shorter, because script components do not present a user interface.

To create an OBJECT element

  • Create an <object> element. This element should be inside the <component> element, but outside of any other element such as a <script> element.

The following example shows an object definition in a script component.

CopyCode image Copy Code
<object id="cnn" progid="ADODB.Connection"/>

Referencing an External Type Library

Many components that you might work with support type libraries, which provide a complete listing of the component's classes and their members. By referencing the component's type libraries, you can use constants defined in the type library.

To include a reference to a type library

  • Include a <reference> element in your script component that specifies the location and name of the type library to include. For example:

    CopyCode image Copy Code
    <reference object="ADODB.Connection.2.0"/>

Referencing Resources

Resource elements can include information that might change between versions, strings that might be translated, and other values.

To reference resources

  1. In the script component, but outside of the <public> and <script> elements (and <implements> element, if any), create one <resource> element for each resource you want to define, giving each element a unique ID. The following example shows two <resource> elements:

    Note Note

    A CDATA section is required to make the contents of the <resource> element opaque to the parser. For details, see Script Component Files and XML Conformance.

    CopyCode image Copy Code
    <component id="MyScriptlet">
<public>
   <method name="random" internalName="getRandomNumber"/>
</public>
<resource id="errNonNumeric"><![CDATA[Non-numeric value passed]]>
</resource>
<resource id="errOutOfRange"><![CDATA[Passed value is out of range ]]>
</resource>

  2. In your script, include the resource text or number by calling the getResource function, as shown in the following example.

    Note Note

    A CDATA section is required to make the script in the <script> element opaque to the parser. For details, see Script Component Files and XML Conformance.

    CopyCode image Copy Code
    <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

Concepts

Script Component File Contents
Referencing Another Script Component in the Same Package


Referencing Another Script Component in the Same Package

Windows Script Components
Referencing Another Script Component in the Same Package
See Also
DropDown image

You can create a package that contains multiple Windows® Script Components, so you can also instantiate and use one of the script components from the other without having to register the second script component.

Scenario

For example, you might create one script component that implements the Automation interface and exposes a series of properties and methods. A second script component in the same package might implement the ASP interface, which provides access to the server object model for Microsoft® Internet Information Services (IIS). You can then create a method or property in the Automation script component that exposes the ASP script component and makes its members available.

To reference one script component from another, create a skeleton member — a property or method — in one method that exposes the second script component.

To reference another script component in the same script component file

  1. Declare a property or method in the first script component.

  2. As part of the definition for the new property or method, call the createComponent function.

    For example, the following shows two script components in the same package. In the first script component, the math method simply references the second script component, which exposes the add method and the multiply method.

    Note Note

    A CDATA section is required to make the script in the <script> element opaque. For details, see Script Component Files and XML Conformance.

    CopyCode image Copy Code
    <?XML version="1.0"?>
<package>
<component id="component1">
<registration progid="Component.FrontEnd"/>
<public>
   <property name="math"/>
</public>
<script language="JScript">
<![CDATA[
var math = createComponent("component2")
   ]]>
</script>
</component>

<component id="component2">
<registration progid="Component.Math"/>
<public>
   <method name="add"/>
   <method name="multiply"/>
</public>
<script language="JScript">
<![CDATA[
function add(n1, n2){
   return n1+n2;
}
function multiply(n1, n2){
   return n1*n2;
}
]]>
</script>
</component>
</package>

To invoke the referenced script component, call the full member hierarchy to get to its methods or properties. The following example illustrates a few ways to do this:

CopyCode image Copy Code
' Creates instance of first script component.
set o1 = CreateObject("Component.FrontEnd")

' Invokes the second script component's functions directly.
msgbox(o1.math.add(3,5))
msgbox(o1.math.multiply(3,5))

' Creates a second object that references the math method directly.
Set o2 = o1.math()
msgbox(o2.add(4,5))
msgbox(o2.multiply(4,5))

Each time you call the createComponent() function, it creates a new instance of the referenced script component. If you need to preserve instance information between calls, store the pointer to the second script component in a global variable, as in the following example.

Note Note

A CDATA section is required to make the script in the <script> element opaque. For details, see Script Component Files and XML Conformance.

CopyCode image Copy Code
<component id="component1">
<registration progid="Component.FrontEnd"/>
<public>
   <property name="math">
      <get/>
   </property>
</public>
<script language="JScript">
<![CDATA[
var m = createComponent("component2")
function get_math(){
   return m
}
   ]]>
</script>
</component>

(Component2 as in previous example)

See Also

Reference

<package> Element (Script Component)
<component> Element

Concepts

Script Component File Contents


Checking For Errors in Script Component Files

Windows Script Components
Checking For Errors in Script Component Files
See Also
DropDown image

Because Windows® Script Components are used as COM components, they normally run silently. However, while you are developing your script component file, you might find it useful to know about errors in the file. You can specify three types of error checking:

  • Check for XML validity. For details, see Script Component Files and XML Conformance.

  • Allow notification for syntax and run-time errors. By default, if an error occurs in a script component file, a generic error message is displayed. By specifying error notification, you can have the script component parser display details about the error.

  • Allow debugging. By default, you cannot use the script debugger for script components. If you enable debugging, you can launch the script debugger in response to an error, by setting a breakpoint, or with a Stop (Microsoft® Visual Basic® Scripting Edition (VBScript)) or debugger (JScript) statement.

Setting Error Options

Specify error options as attributes of the XML <?component?> processing instruction.

To specify error checking

  • Include the <?component?> processing instruction at the top of the script component file (but after the optional <?XML ?> declaration) with one or more of the following attributes:

    • error Set this to true to display detailed error messages for syntax or run-time errors in the script component.

    • debug Set this to true to enable debugging. If this debugging is not enabled, you cannot launch the script debugger for a script component in any way.

For example, the following enables all three error reporting options:

CopyCode image Copy Code
<?component error="true" debug="true"?>
Note Tip

Turn error reporting off before deploying your script component to a production environment.

See Also

Concepts

Script Component File Contents
Using the Script Component Wizard
Creating Registration Information
Creating a Script Component Type Library
Script Component Files and XML Conformance


Script Component Files and XML Conformance

Windows Script Components
Script Component Files and XML Conformance
See Also
DropDown image

Windows® Script Components are XML files and should follow the XML version 1.0 conventions for how elements are defined in the file. Although XML elements superficially resemble HTML tags, XML is a more strictly defined protocol. For example, element names are case-sensitive.

Abiding by XML Standards

To make it easier to create script components, the script component run-time (Scrobj.dll) allows you to specify how strictly you want the XML in your file to be interpreted. Script component XML can be interpreted fairly loosely, allowing the same sorts of variations in tags that HTML does.

However, you can also specify XML validation in your script component file, which causes the script component run-time to check that your script component file's XML conforms closely to the XML standard. If you will ever be using an XML editing tool to work with your script component, you should set XML validation.

When you specify XML validation, you must make sure that your script component file conforms to the following rules.

  • Element types and attribute names are case-sensitive. Element types and attributes names are usually all lowercase, except multipart names such as internalName. In XML files that conform closely to XML standards, all names must follow naming conventions exactly.

  • Attribute values require quotation marks. Values for attributes must be in single or double quotation marks. For example, without XML validation, you can specify language=JScript in a <script> element. But to follow XML rules, the same attribute would be language="JScript".

  • Reserved characters in script elements must be made opaque. Script elements frequently include greater than (<) and less than (>) symbols, the ampersand symbol (&), and other characters that are reserved in XML. If you are creating a closely conformant XML file, you must make sure that these reserved characters do not confuse the XML parser. You can individually mark characters with escape sequences (for example, specify "<" as "&lt;"), or you can make an entire script element opaque by enclosing it in a <![CDATA[ ...]]> section. Without XML validation, the script component XML parser treats <script> elements as opaque by default.

    Note Note

    Do not include a CDATA section in script if you have not specified closely conformant XML parsing. If you do, the script component will report errors when you try to register, instantiate, or call it.

For more details about XML standards, see the XML specification Web site and the Microsoft® XML Web site.

To specify XML conformance

  • Include the <?XML ?> declaration as the first element in your file:

    CopyCode image Copy Code
    <?XML version="1.0" ?>
    Note Note

    If you create a script component using the Script Component Wizard, the <?XML?> declaration is added to the file, and the script component's XML is parsed strictly.

If this element is missing, the script component run-time assumes that you do not want XML validation. However, you will probably not be able to work with the file using an XML editor.

See Also

Concepts

Script Component File Contents
Using the Script Component Wizard
Checking For Errors in Script Component Files


Using Script Components

Windows Script Components
Using Script Components
DropDown image

After you have created a Windows® Script Component, you can use it in your applications.

Script Components Versus COM Components

Using script components is similar to using other COM components, however, each host application uses a slightly different way to instantiate COM components.

  • Registering a Script Component Register and unregister a script component.

  • Using a Script Component in an Application Create an instance of a script component in a host application.

  • Handling Script Component Events in the Host Application Detect and respond to custom script component events.


Registering a Script Component
DropDown image

To register a Windows® Script Component, you must have the script component run-time Scrobj.dll available, and it must be registered on your computer. When you install the script component package from the Microsoft® Scripting Technologies Web site, Scrobj.dll is automatically loaded and registered on your computer.

Note Note

Registration is not required if you are creating a script component to be called via DHTML Behaviors, because Microsoft®Internet Explorer 5.0 can use this type of script component without prior registration.

This topic provides information about:

  • Registering a Script Component

  • Registering a Script Component for Remote Instantiation

  • Unregistering a Script Component

Registering a Script Component

You can register a script component on a local computer using a variety of methods.

To register a script component

  1. In Windows Explorer, right-click the script component (.wsc) file, and then choose Register.

    –or–

  2. Use the new version of Regsvr32.exe that ships with the script component package, and use this command:

    CopyCode image Copy Code
    regsvr32 URL/component_name.wsc

    For example, to register a script component called MyComponent.wsc, use syntax such as this:

    CopyCode image Copy Code
    regsvr32 file:\\myserver\MyComponent.wsc

    -or–

  3. If you do not have the version of Regsvr32.exe that ships with the script component package, use the existing version and register the script component run-time DLL using syntax such as the following:

    CopyCode image Copy Code
    regsvr32 scrobj.dll /n /i:URL/component_name.ext

    For example, to register a script component called MyComponent.wsc, use syntax such as this:

    CopyCode image Copy Code
    regsvr32 scrobj.dll /n /i:http://myserver/MyComponent.wsc

Registering a Script Component for Remote Instantiation

If you intend to create a remote instance of a script component, the script component must be registered on the remote computer where it resides. You must also register it on each local computer from which you intend to instantiate the script component, so that DCOM can have a starting point in the registry from which to find and instantiate the remote script component.

To register a script component for remote instantiation

  1. Determine the program ID and class ID of the script component to be instantiated remotely.

    Note Note

    The script component must have the same class ID on both the local and remote computers, so you must provide a class ID in the script component's <registration> element.

  2. On each local computer, create the following registry entry:

    CopyCode image Copy Code
    HKEY_CLASSES_ROOT\componentProgID

    where componentProgID is the program ID of the script component to instantiate.

  3. Under the new entry, create the CLSID key and set its value to the class ID of the script component, enclosing the class ID in brackets.

    Note Tip

    An easy way to create the proper registry information is to register the script component on the server where it will be instantiated. Then using Regedit.exe, locate the HKEY_CLASSES_ROOT\componentProgID entry. From the Registry menu, choose Export Registry File, which creates a .reg file. This file can be distributed to local computers, and users can simply run the file to create the appropriate registry entries.

Unregistering a Script Component

If you no longer need to have a script component registered on your computer, you can unregister it using one of these methods:

  • Right-click the script component file name in Windows Explorer, and then choose Unregister.

  • Run Regsvr32.exe with the -u flag.

See Also

Concepts

Creating Registration Information
Script Component File Contents
Using a Script Component in an Application


Using a Script Component in an Application

Windows Script Components
Using a Script Component in an Application
See Also
DropDown image

After creating a Windows® Script Component, you can use it as you would any COM component, by calling it from a host application such as Microsoft® Visual Basic®, C++, Microsoft® Internet Explorer, or other applications.

Creating an Instance of the Script Component

There are a variety of options for creating an instance of the script component, depending on the host application, the type of script component you are using, and where the script component is deployed. The primary difference, however, is whether you want to create an instance of the script component locally (on the same computer as the application) or remotely (on another computer).

Note Note

Script components written for DHTML Behaviors are instantiated differently than traditional COM objects. For details, see Using DHTML Behaviors on the Microsoft Site Builder Network (SBN) Web site.

In either case, there are a few points to bear in mind. If you create an instance of the script component and change the .wsc file while using that instance, your instance of the component is not updated. To update it, create a new instance of the script component.

The exact properties and methods you can use are defined by the <public> element and by scripts in the script component file. If you are working in an environment that supports statement completion, such as Visual Basic, you can see a script component's properties and methods if you generate and use a type library. For details, see Creating a Script Component Type Library.

If your attempt to create an instance of the script component fails, a likely cause is a syntax or run-time error in the script component file. A parsing error in any XML element (including the <registration> element) can cause the instantiation to fail. While you are developing your script component file, set error checking options in the <?component?> processing instruction as described in Checking For Errors in Script Component Files.

Note Tip

To make it easier for the host application to know about the COM interfaces exposed by a script component, the script component run-time can generate a type library, which contains information about the properties, methods, and events available in the script component. For details, see Creating a Script Component Type Library.

Creating Local Instances of Script Components

If the script component is installed on the same computer as the host application, you can register the script component as its own component as described in Registering a Script Component. You can then use the host application's normal means for creating an object instance, such as the CreateObject function. For example, to create an instance of the script component that was registered with the program ID Component.MyComponent in Visual Basic, use a statement such as this:

CopyCode image Copy Code
Set oComponent = CreateObject("Component.MyComponent")
Note Note

If your host application is Visual Basic and you want to handle events fired by the script component, you must bind the object early with a Dim statement that includes the WithEvents keyword, such as the following:

CopyCode image Copy Code
        Dim WithEvents scMyComponent As MyComponentPrivate Sub Command1_Click()   Set scMyComponent=CreateObject("MyComponent")End Sub
Note Note

For details, see Handling Script Component Events in the Host Application. This is not necessary if you do not intend to write handlers for script component events.

On a Web page, you can use the <OBJECT> tag to create an instance of the script component. You must know the class ID of the script component and include it in the <OBJECT> tag, as in the following example:

CopyCode image Copy Code
<OBJECT
   ID="oComponent"
   CLASSID="clsid:855c8606-49ba-11d2-a428-00c04f8ec80b">
</OBJECT>

If the script component is not registered on the local computer, you can use the script component moniker to create an instance of it. The moniker is supported in functions such as GetObject. The script component run-time, Scrobj.dll, must be registered on the local computer.

Note Note

The GetObject function is not supported for script components in Microsoft® Internet Explorer for security reasons.

For example, the following illustrates how to call the Visual Basic GetObject function to create an instance of an unregistered script component:

CopyCode image Copy Code
Set oComponent = GetObject("script:c:\COM\MyComponent.wsc")

If the .wsc file referenced by the moniker contains more than one script component, you can specify the script component to instantiate by adding its name to the file name with a hash mark (#) as a delimiter. The following creates an instance of the script component whose ID is "math" contained in the file MyComponent.wsc:

CopyCode image Copy Code
Set oComponent = GetObject("script:c:\COM\MyComponent.wsc#math")

Using a URL moniker allows you to create an instance of a script component that resides on another computer, such as a Web server. Use a complete URL (with HTTP protocol) as the location for the script component, as in the following example:

CopyCode image Copy Code
Set oComponent = GetObject("script:http://myserver/MyComponent.wsc")

Internet Explorer 5.0 supports DHTML Behavior syntax for creating instances of script components, which works somewhat differently than the traditional syntax for instantiating objects and will ensure that the script component cannot access potential unsafe system objects. For an example, see Using DHTML Behaviors on the Microsoft Site Builder Network (SBN) Web site.

Creating Remote Instances of Script Components

If the remotable attribute of a script component's <registration> element has been set to "true," the script component can be instantiated remotely from another computer using Distributed COM (DCOM).

Both computers must have basic DCOM installed. A computer is correctly configured with DCOM if it is running any of the following:

  • Windows NT 4.0, Windows 98, Windows Millennium Edition, Windows 2000, or Windows XP

  • Windows 95 running Internet Explorer 4.0

  • Windows 95 with the OEM Service Release 2 (OSR2) or later. For details, see the Windows 95 OSR2 page on the Microsoft® Web site.

  • Windows 95 with DCOM for Windows 95, version 1.2. For details, see the DCOM for Windows 95 page on the Microsoft® Web site.

The script component itself must be deployed as follows:

  • On the local computer, you do not require either the script component itself (.wsc file) or the script component run-time (Scrobj.dll) at the time you instantiate the script component. However, you must have a reference to the remote script component in the local Windows registry for DCOM. For details, see Registering a Script Component.

  • On the remote computer, you require the script component and the script component runtime. Both must be registered.

When you create an instance of a remote script component, it works within your application as if it were a local object; you call its methods and get and set its properties normally. However, the remote script component's script runs on the remote machine and has access to that machine's resources (within any limitations imposed by security, and so forth). Communication between the host application on the local machine and the script component on the remote machine is handled automatically and invisibly by DCOM.

To create a remote instance of a script component, call the CreateObject method, passing it the name of the remote computer as a parameter.

Note Note

The ability to use CreateObject for instantiating remote script components requires Visual Basic 6.0 or later or VBScript 5.0 or later.

The following Visual Basic example shows how to do this on a computer named "myserver":

CopyCode image Copy Code
Set newS = CreateObject("Component.MyComponent", "myserver")
Note Note

There can be a slight delay when you first instantiate a remote script component while DCOM establishes communication between the computers.

See Also

Concepts

Creating Registration Information
How Script Components Work
Introducing Windows Script Components
Registering a Script Component

Other Resources

Creating Script Components


Handling Script Component Events in the Host Application

Windows Script Components
Handling Script Component Events in the Host Application
See Also
DropDown image

Most host applications can receive Windows® Script Component events as they do any other events. However, some host applications require some setup before they can receive script component events.

Setup Considerations

In Visual Basic, for example, you must use early (compile-time) binding to the component in order to receive events. Early binding requires a type library, so you must have generated a type library for the script component. For details, see Creating a Script Component Type Library. In addition, when you declare the object variable for the component, you must specify the WithEvents keyword. (The class name used in the Dim statement is the ID that you assigned in the script component's <component> element.)

Note Note

If you are creating a Behavior script component, events are exposed using the DHTML object model. For details, see Exposing Custom Events in Behavior Script Components.

An example in Visual Basic might look like this:

CopyCode image Copy Code
Dim WithEvents Scriptlet1 as MyScriptlet
Set Scriptlet1 = CreateObject("MyScriptlet")
Sub Scriptlet1_namechanged
   MsgBox("Value of name property changed")
End Sub

See Also

Concepts

Exposing Events


Implementing ASP Script Components

Windows Script Components
Implementing ASP Script Components
DropDown image

Using a Windows® Script Component, you can include the functionality of Active Server Pages (ASP). Doing so allows you to isolate server script into a component that can be easily called from ASP pages and which makes it easy to reuse ASP code. For example, you might have several ASP pages that process forms. Rather than implement all the form-processing logic directly in each ASP page, the ASP pages could all call a script component with form-handling logic that you create.

Creating an ASP Script Component

To create an ASP script component, create a script component normally, as described in Script Component File Contents. Use the <implements> element to implement the ASP interface handler, setting the type attribute of the <implements> element to "ASP." Doing so provides the means for accessing ASP objects: Response, Request, Server, Session, and Application. In an ASP script component, you can use these objects as you would directly in an ASP page. The ASP interface handler is built into the script component run-time (Scrobj.dll), so no external interface handler is required.

When the script component runs, it uses the same namespace as the ASP page that called it. The script component can access the Request and Server objects as if it were in the ASP page that called it. The script component also has access to the same Session and Application variables that the calling ASP page does. Similarly, if the ASP script component calls a method on the Response object, the result of these calls is available in the calling page. For example, if you call Response.Write, the output is directed to the calling ASP page.

The following shows a simple ASP script component that exposes a property and a method. The applicationVar1 property makes available the hypothetical Application variable called Var1. The AddDate method outputs the current date into the calling ASP page.

Note Note

A CDATA section is required to make the script in the <script> element opaque. For details, see Script Component Files and XML Conformance.

CopyCode image Copy Code
<component id="ASPScriptlet">
<registration progid="ASPScriptlet"/>

<public>
   <property name="applicationVar1"/>
   <method name="AddDate"/>
</public>

<implements type="ASP"/>
<script language="VBScript">
<![CDATA[
dim applicationVar1
applicationVar1 = Application("Var1")
Sub AddDate()
   Response.Write(Date)
End Sub
]]>
</script>
</component>

The calling ASP page might look like this:

CopyCode image Copy Code
<HTML>
<HEAD>
<TITLE>Testing the Script Components ASP Handler</TITLE>
</HEAD>
<BODY BGCOLOR="#FFFFFF">
<H1>Testing the ASP Handler</H1>
<%Set wscASP = CreateObject("ASPScriptlet")%>
<P>The current date is <%= wscASP.AddDate()%></P>

<P>The value of the Application(Var1) variable is <%= wscASP.applicationVar1%></P>

</BODY>
</HTML>


Implementing DHTML Behavior Script Components

Windows Script Components
Implementing DHTML Behavior Script Components
DropDown image

Windows® Script Components provide a lightweight, easily maintainable way to create components for implementing DHTML Behaviors available in Microsoft® Internet Explorer 5.0. Using a script component allows script developers to implement behaviors using Microsoft® Visual Basic® Scripting Edition (VBScript), Microsoft® JScript® (ECMAScript), or any third party scripting language that supports the Microsoft® ActiveX® Scripting interfaces.

Benefits of Creating Behavior Script Components

For general information about DHTML Behaviors, see http://msdn.microsoft.com/workshop.

By creating Behavior script components, you can:

  • Expose behaviors by binding functions in the script component to events raised in the containing document, either for specific elements or for the DHTML document or DHTML window objects.

  • Define layouts, which contain HTML text that is inserted into the containing document when the behavior is called.

  • Expose custom properties and methods that extend the set of members for an element in the containing page.

  • Expose custom events which the script component can fire at any time. For example, a script component can fire a custom event after changing the contents of a DHTML element on the page.

  • Bind a script component function to certain standard events such as when the document is loaded or when the content of the element changes.

In this section you will find information about the following:

  • Creating a Behavior Script Component See what elements to put into a Behavior script component file, how to share information with the containing document, what DHTML features apply to Behavior script components, and what to watch for when scripting.

  • Exposing Properties and Methods in Behavior Script Components Create properties and methods that extend those already available in DHTML elements.

  • Exposing Custom Events in Behavior Script Components Expose and fire events from the script component to the containing document.

  • Behavior Handler Reference A list of XML elements, properties, and methods used in Behavior script components.


Creating a Behavior Script Component

Windows Script Components
Creating a Behavior Script Component
See Also
DropDown image

Creating a Behavior script component is similar to creating any other kind of script component, except that you are linking Microsoft® Internet Explorer events to script that is run in response to those events.

This topic is divided into the following sections:

  • Creating a Behavior Script Component File

  • Behavior-Related Enhancements to the DHTML Object Model

  • Getting Event Parameters in the Script Component

  • Scope Rules

  • Timing Considerations

Creating a Behavior Script Component File

A Behavior script component includes an <implements> element that specifies the Behavior interface handler. Within the <implements> element, you use:

  • <attach>elements to bind events from the containing document to functions created in a separate <script> element in the script component.

  • <layout>elements to define HTML text to be inserted into the containing document.

  • <event>elements to define custom events that will be fired by the script component.

Behavior script components can also include custom properties and methods that extend those already available for the element in the containing document. For details, see Exposing Properties and Methods in Behavior Script Components.

The following example shows a Behavior script component that changes the color of an element in the containing page whenever the mouse is passed over the element. To do this, the sample binds the DHTML onmouseover and onmouseout events to functions in the script component that set the element's DHTML style attribute. The sample also sets the document's link color when the document is initialized by binding to the DHTML window object's onload event.

In addition to binding events to script, the script component also inserts text into any <H1> elements in the containing document that are linked to this script component. Finally, it exposes and fires an event called onchange, which extends the DHTML window object's event object with a custom property called newvalue.

Note Note

A CDATA section is required to make the script in the <script> element opaque. For details, see Script Component Files and XML Conformance.

CopyCode image Copy Code
<?XML version="1.0"?>
<component>
<implements type="Behavior">
   <comment>The following will cause the do_nmousedown and
   do_mouseout functions to be called when the mouse is
   passed over the element in the containing document.</comment>

   <attach event="onmouseover" handler="do_onmouseover"/>
   <attach event="onmouseout" handler="do_onmouseout"/>

   <comment> This will call the init function when the onload
   event of window is fired.</comment>

   <attach for="window" event="onload" handler="docinit"/>

   <comment>The following defines HTML text that will appear in
   the containing document.</comment>

   <layout>
      <h1>This is the HTML to show in the element</h1>
   </layout>

   <comment>The following defines a custom event that is fired
   from within the script component by the fireEvent method.</comment>

   <public>
      <event name="onchange"/>
   </public>

</implements>
<script language="JScript">
<![CDATA[
var normalColor, normalSpacing;
function do_onmouseover(){
   // Save original values.
   normalColor = style.color;
   normalSpacing= style.letterSpacing;
   style.color = "red";
   style.letterSpacing = 2;
   oEvent = createEventObject();
   oEvent.newcolor = "red";
   fireEvent("onchange",oEvent);
}
function do_onmouseout(){
   // Reset to original values.
   style.color = normalColor;
   style.letterSpacing = normalSpacing;
}

function docinit(){
   document.linkColor = "red";
}
]]>
</script>
</component>

There are a few things to point out in the preceding code:

  • From a script component procedure, the implied this pointer in an event handler refers to the containing function, not to the element on which the event is being fired.

  • Just as in an HTML page, it is possible to place inline script within a <script> in a script component. In this instance, the global variables normalColor and normalSpacing are defined in inline script.

    Note Note

    Inline script is executed even before the behavior is applied to the element, which limits what statements can be executed in inline script. For example, if the same behavior in the example exposed a property called hiliteColor, the inline script could refer to hiliteColor directly (in other words, it resolves against the script component's namespace). It is illegal, however, to refer to hiliteColor as Behavior.element.hiliteColor from an inline script, because at that point, the behavior has not yet been applied to the element. For more information, see Scope Rules and Timing Considerations later in this topic.

Behavior-Related Enhancements to the DHTML Object Model

The following enhancements were made to the DHTML object model for Microsoft® Internet Explorer 5 in order to add support for behaviors.

  • The cascading style sheet (CSS) behavior attribute specifies the location of the behavior.

  • The DHTML attachEvent and detachEvent methods enable a Behavior script component to receive event notifications from the containing page, by specifying a function that gets called whenever the event fires on the object.

  • The DHTML uniqueID property enables a behavior script component to assign an ID to the element. This can be useful in cases where a script component injects code into the containing page and needs to specify the ID of the element to which the behavior is being applied.

Getting Event Parameters in the Script Component

In DHTML, the DHTML event object provides information about the event. Although in DHTML the event object is accessible to event handlers through the DHTML window object, in a behavior script component the event object is passed in as a parameter to the event handler.

The following code from a hypothetical calculator script component demonstrates keyboard and mouse events bound to a script component function called doCalc. The doCalc function uses the event object to get information about the conditions under which the event was fired.

Note Note

A CDATA section is required to make the script in the <script> element opaque. For details, see Script Component Files and XML Conformance.

CopyCode image Copy Code
<implements type="Behavior">
   <attach event="onclick" handler="doCalc"/>
   <attach event="onkeydown" handler="doCalc"/>
</implements>

<script language="jscript">
<![CDATA[
function doCalc(oEventParam){
   oElement = oEventParam.srcElement;
   if(oEventParam.type == "keydown"){
      sVal = KeyCodeToChar(oEventParam.keyCode);
   }
   else{
      if (oEventParam.srcElement.type != "button"){
         return;}
      sVal = stripBlanks(oEventParam.srcElement.value);
   }
}
// other script here
]]>
</script>

Scope Rules

When working with script components, you actually work with three namespaces: the behavior, the element, and the containing document. Scope rules define the order in which name conflicts are resolved in a behavior script component. A name will be resolved in this order:

The name is resolved to one defined by the behavior anywhere in the script component, whether a variable, a behavior-defined property, a method, or an event.

If the name is not resolved successfully, it is resolved to a property, method, or event that applies to the element.

Finally, the name is resolved to the name of a property, method, or event that applies to the window object in the containing page.

In the following example, note how the names have been resolved, using the scope rules defined above:

  • normalColor Resolves to the variable defined by the behavior at the top of the script.

  • style Resolves to the style property of the element in the containing document.

    CopyCode image Copy Code
    <implements type="Behavior">
   <attach event="onmouseover" handler="do_onmouseover"/>
   <attach event="onmouseout "handler="do_onmouseout"/>
</implements>

<script language="JScript">
<![CDATA[
var normalColor, normalSpacing;
function event_onmouseover()
{
   // Save original values.
   normalColor = style.color;
   normalSpacing = style.letterSpacing;

   style.color = "red";
   style.letterSpacing = 2;
}
function event_onmouseout()
{
   // Reset to original values.
   style.color = normalColor;
   style.letterSpacing = normalSpacing;
}
]]>
</script>

Timing Considerations

When creating behaviors, it is important to know when the behavior is applied to the element. Until the behavior has been applied, scripts cannot have access to the values of behavior-defined properties that might be set in the document.

Because the behavior is encapsulated in a separate file from the HTML document, it is downloaded separately from the rest of the document. As the document and behavior are parsed and loaded, the behavior receives notifications of progress through the function specified with the attachNotification method. Currently, the behavior is notified with a "contentChange" or a "documentReady" notification. The "contentChange" notification is sent when the content of the element to which the behavior has been attached has been parsed, and any time thereafter that the content of the element is changed. The "documentReady" notification is sent when the document has been downloaded and parsed.

Because inline script in the script component file is executed as soon as the behavior is instantiated, the values of behavior-defined attributes and properties that are being set in the document may not be accessible from an inline script. However, these properties will be available as soon as the first "contentChange" notification is sent.

See Also

Concepts

Exposing Properties and Methods in Behavior Script Components
Exposing Custom Events in Behavior Script Components

Other Resources

Behavior Handler Reference


Exposing Properties and Methods in Behavior Script Components

Windows Script Components
Exposing Properties and Methods in Behavior Script Components
See Also
DropDown image

Behavior script components can expose custom properties and methods in a manner similar to Automation script components. Behavior script component properties and methods extend the properties and methods available to elements in the containing page. For example, you might create a behavior script component that changes the color of an element when the mouse is passed over it. By defining a property in the script component, you can make available a custom property in the document, perhaps called hiliteColor, that allows the Web page author to set the color with which text gets highlighted.

A behavior can override an element's default behavior by exposing a property or method of the same name as that which is already defined for the element.

Properties and methods are defined in a <public> element separate from the <implements> element used to specify the Behavior handler. For details, see Exposing Properties and Exposing Methods.

Exposing a Property

Properties are exposed in a <public> element, as in any script component. The following script component fragment shows a Behavior script component that exposes the custom property hiliteColor. If the containing page does not specifically set the property's value, the default is set to "red."

Note Note

A CDATA section is required to make the script in the <script> element opaque. For details, see Script Component Files and XML Conformance.

CopyCode image Copy Code
<public>
   <property name="hiliteColor"/>
</public>

<implements type="Behavior">
   <attach for="window" event="onload" handler="event_onload">
</implements>

<script language="JScript">
<![CDATA[
   var hiliteColor;
   function event_onload(){
      // Initialize the properties.
      if (hiliteColor == null){
         hiliteColor = "red";}
   }
   // Further script here.
]]>
</script>

Exposing a Method

Exposing a method in a Behavior script component is identical to doing so in an Automation script component. For details, see Exposing Methods. In a Behavior script component, methods exposed in the script component extend those already available for the element in the containing document.

See Also

Concepts

Exposing Custom Events in Behavior Script Components


Exposing Custom Events in Behavior Script Components

Windows Script Components
Exposing Custom Events in Behavior Script Components
See Also
DropDown image

Behavior script components, like Automation script components, can expose custom events that are fired inside the script component and can be handled in the containing document. An event is declared in the <public> element as in the following:

Example

CopyCode image Copy Code
<public>
   <event name="onResultChange" />
</public>

The event can then be fired by calling the fireEvent method in script:

CopyCode image Copy Code
<script language="JScript">
   // Other code here.
   fireEvent("onResultChange");
   // Other code here.
</script>

A behavior can override an element's default behavior by exposing an event of the same name as one that is already defined for the element. For example, a behavior that exposes an onclick event can override the element's default onclick event.

Getting and Setting Custom Event Information

Your custom script component event can get access to the DHTML event object, which maintains event-specific information. You can use this object to:

  • Change existing event object properties, such as keyCode, that have been set by in the calling event.

  • Create new (expando) properties of the event object in order to pass information about your event back to the containing event.

In your script component code, call the createEventObject method to create a new instance of an event object, and then set one or more properties on the new event object. When you call the fireEvent method, you can pass the new event object with the event name.

To create a new expando property, simply name it when assigning its value in your script. The following shows how you can create a new property called myprop for the event object:

CopyCode image Copy Code
oEvent = createEventObject();
oEvent.myprop = "a new value"
Note Note

You can create expando properties only if you are using Microsoft® JScript® (or JavaScript). This feature is not supported in Microsoft® Visual Basic® Scripting Edition (VBScript).

Example

The following script component fragment is derived from a calculator script component sample. The sample defines a custom onResultChange event that is fired to the containing document whenever the result changes. Event-specific information (the actual calculation result) is passed via the expando property called result.

Note Note

A CDATA section is required to make the script in the <script> element opaque. For details, see Script Component Files and XML Conformance.

CopyCode image Copy Code
<public>
   <event name="onResultChange" />
</public>

<implements type="Behavior">
   <attach event="onclick" handler="doCalc"/>
</implements>

<script language="JScript">
<![CDATA[
function doCalc()
{
   // Code here to perform calculation. Results are placed into
   // the variable sResult.
   oEvent = createEventObject();
   oEvent.result = sResult;
   fireEvent("onResultChange",oEvent);
}
]]>
</script>

The following shows what the containing page looks like. When the onResultChange event fires, the results of the calculation are extracted from expando property result of the DHTML window.event object and displayed in the resultWindow <DIV> element.

CopyCode image Copy Code
<HTML>
<HEAD>
<xml:namespace prefix="LK" />
<style>
   LK\:CALC {behavior:url(calc.wsc)}
</style>
<script language="JScript">
function showResults(){
   resultWindow.innerText=window.event.result;
}
</script>
</HEAD>

<LK:CALC id="myCalc" onResultChange="showResults()">
<TABLE>
<TR>
   <DIV ID=resultWindow
      STYLE="border: '.025cm solid gray'"
      ALIGN=RIGHT>0.</DIV>
</TR>
<TR>
   <TD><INPUT TYPE=BUTTON VALUE=" 0 "></TD>
   <TD><INPUT TYPE=BUTTON VALUE="+/-"></TD>
   <TD><INPUT TYPE=BUTTON VALUE=" . "></TD>
   <TD><INPUT TYPE=BUTTON VALUE=" + "></TD>
   <TD><INPUT TYPE=BUTTON VALUE=" = "></TD>
<TR>
</TABLE>
</LK:CALC>
</HTML>

See Also

Concepts

Exposing Properties and Methods in Behavior Script Components


Script Component Reference

Windows Script Components
Script Component Reference
CollapseAll image DropDown image

When creating Windows® Script Component files, use XML elements to define different parts of your script component, such as the registration information, scripts, and objects that you intend to reference in your script component's code. You can also call methods to perform tasks in the script component. The following table lists the available XML elements and methods.

Note Note

Specific handlers, such as the Behavior handler, expose additional XML elements, methods, and other members. For more information, refer to the documentation for specific handlers.

Expand image XML Elements

  • <?component?>

  • <?XML ?>

  • <comment>

  • <component>

  • <event>

  • <implements>

  • <method>

  • <object>

  • <package>

  • <property>

  • <public>

  • <reference>

  • <registration>

  • <resource>

  • <script>

Expand image Methods and Functions

  • createComponent

  • fireEvent

  • getResource


<?component?>

Windows Script Components
<?component?>
See Also Example
CollapseAll image DropDown image

Specifies attributes for error handling.

<?component error="flag" debug="flag" ?>

Expand image Values

flag

A Boolean value: "true" or "false," 1 or 0, or "yes" or "no." The default value for all attributes is false.

Expand image Remarks

Because script components are used as COM components, they normally run silently. However, while you are developing your script component file, you might find it useful to be notified about errors in the file. You can specify these types of error notification:

  • error Set this to true to allow error messages for syntax or run-time errors in the script component file.

  • debug Set this to true to enable debugging. If this debugging is not enabled, you cannot launch the script debugger for a script component in any way.

Expand image Example

CopyCode image Copy Code
<?component error="true" debug="true" ?>

Expand image See Also

Concepts

Checking For Errors in Script Component Files
Script Component File Contents


<?XML ?>

Windows Script Components
<?XML ?>
See Also Example
CollapseAll image DropDown image

Indicates that the file should be parsed as XML.

<?XML version="version" standalone="DTDflag" encoding="encname" ?>

Expand image Values

version

A string in the form n.n specifying the XML level of the file. Use the value 1.0.

DTDflag

(Optional) A 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."

encname

(Optional) A string that describes the character set encoding used by the XML document. The string may include any of the character sets supported by Microsoft® Internet Explorer.

Expand image Remarks

This declaration must be the first element (including white space) in the file.

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 must be in single or double quotes, and all elements are parsed. If the declaration is not included, the compiler allows looser syntax.

In general, you should include this declaration and follow XML conventions if your script component file will ever be edited in an XML-conformant editor.

Expand image Example

CopyCode image Copy Code
<?XML version="1.0" standalone="yes" encoding="UTF-16" ?>

Expand image See Also

Concepts

Script Component Files and XML Conformance


<comment> Element

Windows Script Components
<comment> Element
See Also Example
CollapseAll image DropDown image

Marks text in a script component file that should be ignored.

<comment>
      text here
</comment>

Expand image Remarks

Use the <comment> element inside other XML elements to enclose text that is not markup and not data, but that you want to include for other purposes, such as documentation.

Expand image Example

The following script component fragment shows a <comment> element inside a <public> element.
CopyCode image Copy Code
<public>
   <comment>
      This implements an Automation component with the
      method "random" and the property "uppercaseName"
   </comment>
   <method name="random" internalName="getRandomNumber"/>
   <property name="uppercaseName">
      <get internalName="get_ucname"/>
      <put internalName="put_ucname"/>
   </property>
</public>

Expand image See Also

Concepts

Script Component File Contents


<component> Element

Windows Script Components
<component> Element
See Also Example
CollapseAll image DropDown image

Encloses an entire Windows Script Component definition.

<component id=componentid>
   script component information here
</component>

Expand image Values

componentid

A string that uniquely identifies the script component. This value is useful if a document contains multiple script components or when you are generating one type library for several script components. Identifiers must begin with a letter and can contain no spaces. The identifier must be unique within a script component package.

If specified, this value functions as the class name for the script component in the host application. For example, if you specify the component ID "MyComponent" in the <component> element, the script component is identified as the class MyComponent in the Visual Basic object browser. If no component ID is specified, the default value is ComponentCoClass.

Expand image Remarks

In script component files, an entire script component definition — including<registration>, <public> and <implements> elements — must appear inside a <component> element. If the file contains multiple script components, they must in turn be enclosed within a <package> element.

Expand image Example

The following shows a simple but complete script component that includes a factorial method and a name property.

Note Note

A CDATA section is required to make the script in the <script> element opaque. For details, see Script Component Files and XML Conformance.
CopyCode image Copy Code
<?XML version="1.0"?>
<component>
<registration>
   description="My Test Component"
   progid="Component.TestScript"
   version="1"
   classid="{2154c700-9253-11d1-a3ac-0aa0044eb5f}"
</registration>

<public>
   <property name="name"/>
   <method name="factorial"/>
</public>

<script language="VBScript">
   <![CDATA[
   Function factorial(n)
      If isNumeric(n) Then
         If n <= 1 Then
            factorial = 1
         Else
            factorial = n*factorial(n-1)
         End If
      Else
         factorial = -2   ' Error code.
      End If
   End Function
   ]]>
</script>
</component>

Expand image See Also

Concepts

Script Component File Contents


<event> Element

Windows Script Components
<event> Element
See Also Example
CollapseAll image DropDown image

Declares the name of a custom event that can be fired from within the script component.

<event name="name" dispid="dispid"/>

Expand image Values

name

The name of an event being exposed.

dispid

(Optional) A numeric value specifying the dispatch ID for the event, which is compiled into the component's type library and then used by the host application to bind to events. If you do not specify a dispatch ID, it is assigned automatically to the event when the type library is created. Specifying your own dispatch ID allows you to make sure the dispatch ID for an event is always the same, even if you recreate the type library. It also allows you to map your event to a specific dispatch ID, such as those used by convention in COM. For more details, see Exposing Events.

Expand image Remarks

To fire an event, use the fireEvent method.

Expand image Example

The following script component fragment defines two events (namechanged and querydone) and shows how to fire one of them (namechanged).

Note Note

A CDATA section is required to make the script in the <script> element opaque. For details, see Script Component Files and XML Conformance.
CopyCode image Copy Code
<public>
   <property name="name">
      <get/>
      <put/>
   </property>
   <event name="namechanged"/>
   <event name="querydone" dispid="22"/>
<public>

<script language="VBScript">
<![CDATA[
var gName
Sub get_lowercaseName()
   get_lowercaseName = name
End Sub

Sub put_lowercaseName(newLCName)
   gName = newLCName
   fireEvent("namechanged")
End Sub
   ]]>
</script>

Expand image See Also

Tasks

Exposing Properties

Reference

<method> Element
<property> Element
fireEvent Method (Script Component)

Concepts

Exposing Events
Exposing Methods


<implements> Element

Windows Script Components
<implements> Element
See Also Example
CollapseAll image DropDown image

Specifies additional COM interface handlers for a script component.

<implements type="COMHandlerName" [id="internalName"] [default=fAssumed]>
   handler-specific information here
</implements>

Expand image Values

COMHandlerName

The name of the interface handler to reference. Interface handlers are usually implemented as DLLs, which you must be sure are available and registered in the production environment for your script component. Some handlers, such as the Automation and ASP handlers, are built into the script component run-time (Scrobj.dll). Examples of available interface handlers include:

Interface handler Description How implemented

ASP

Allows a script component to get access to the Microsoft Internet Information Services (IIS) Active Server Pages (ASP) object model.

Built into Scrobj.dll

DHTML Behaviors

Allows a behavior script component to communicate with the containing page so it can fire events and access the DHTML object model.

Built into Scrobj.dll
internalName

(Optional) A name you can use to reference the handler in your script. By default, properties, methods, events, and other members of a script component are available in the global namespace. However, if there is a naming conflict between <implements> elements, the names can be disambiguated by prefixing them with the ID of the <implements> element to which they belong, as in the following:

CopyCode image Copy Code
<implements type="Behavior" id="sctBehavior">
   [...]
</implements>

[...]

<script language="JScript">
   // [...]
   sctBehavior.fireEvent("onResultChange",oEvent);
</script>
fAssumed

(Optional) A Boolean flag indicating that the internalName is assumed in scripts. The default value for this attribute is true, and members of the object model exposed by the handler are added to the global script namespace and can be accessed unqualified. You only need to include this attribute if you want to set it to false and therefore hide members of a specific <implements> element.

Expand image Remarks

Interface handlers extend the script component run-time. An interface handler is a compiled component (generally written in C++) that implements specific COM interfaces.

Script components by default implement the COM Automation interface (specifically, the IDispatchEx COM interface). The Automation object's properties, methods, and events are defined in the script component's <public> element. Because the Automation handler is implemented by default, you do not need to implement it with the <implements> element.

Script components can also implement additional COM interfaces by including an <implements> element. Inside the <implements> element, you specify information specific to the interfaces you are implementing. Each interface handler requires different information. For example, a Behavior script component can include <attach> and <layout> elements that are specific to the DHTML Behavior interface.

Expand image Example

CopyCode image Copy Code
<implements type="Behavior">
   <event name="onResultChange" />
</implements>

Expand image See Also

Concepts

How Script Components Work
Script Component File Contents


<method> Element

Windows Script Components
<method> Element
See Also Example
CollapseAll image DropDown image

Declares a method.

<method name="methodName" internalName="functionName" dispid=dispID>
   [<parameter name="parameterID"/>]
</method>

Expand image Values

methodName

The name of the method to expose.

functionName

(Optional) The name of the procedure (function or subroutine) in the script component file that implements the method. If you do not specify an internal name, methodName is used.

Note Tip

In XML, you can implement elements that have no content (such as the <method> element) by closing the element with />.

dispID

(Optional) COM dispatch ID for the method. If no dispid is specified, the dispid is automatically generated. If the dispid is set to 0 (zero), the method becomes the script component's default method. For more information about dispids, see Exposing Events.

parameterID

If a parameter is explicitly declared for the method, identifies the parameter's name.

Expand image Remarks

A method is implemented as a procedure (function or subroutine) in a separate <script> element. The <method> element maps the name of the method to the procedure used to implement it.

You can optionally declare the parameters for your method. Doing so is not required, but exposes parameter information if you generate a type library for your script component (see Creating a Script Component Type Library).

Expand image Example

The following script component fragment defines two methods (factorial and random). The random method includes definitions for its parameters, and binds to a function called getRandomNumber.

Note Note

A CDATA section is required to make the script in the <script> element opaque. For details, see Script Component Files and XML Conformance.
CopyCode image Copy Code
<public>
   <method name="factorial"/>
   <method name="random" internalName="getRandomNumber">
      <parameter name="upperBound">
      <parameter name="seed">
   </method>
</public>

<script language="VBScript">
<![CDATA[
   Function factorial(n)
      If isNumeric(n) Then
         If n <= 1 Then
            factorial = 1
         Else
            factorial = n*factorial(n-1)
         End If
      Else
         factorial = -2    ' Error code.
      End If
   End Function

   Function getRandomNumber(upperBound, seed)
      upperBound = CInt(upperBound)
      Randomize
      getRandomNumber = Cint(upperBound * Rnd(seed) + 1)
   End Function
]]>
</script>

Expand image See Also

Tasks

Exposing Properties

Reference

<event> Element
<property> Element

Concepts

Exposing Events
Exposing Methods


<object> Element (Script Component)

Windows Script Components
<object> Element (Script Component)
See Also Example
CollapseAll image DropDown image

Defines objects that can be referenced by script.

<object id="objID" {classid="clsid:GUID" | progid="progID"} [events="hookevents"] />

Expand image Values

objID

A name by which the object can be referenced 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 script component. For example, if you specify the name CObj, you can reference the object in your script this way:

CopyCode image Copy Code
x = CObj.Prop1
GUID

(Optional) A reference to the class ID (GUID) under which the object has been registered. Use "clsid:" followed by the class ID (without curly brackets). Either a classid or a progid attribute must be specified. For example:

CopyCode image Copy Code
classid="clsid:2154c700-9253-11d1-a3ac-0aa0044eb5f"
progID

(Optional) The program ID of the object, which can be specified as an alternative to the class ID. Either a classid or a progid attribute must be specified.

hookevents

(Optional) A value (either "true" or "false") that determines if you can hook events from the object. By default, hookevents is false. If the attribute is true, you can connect to any events the object may fire. You must add an event handler for each event that is to be handled.

Expand image Remarks

The <object> element provides a way to expose objects globally for use in scripting within the script component without having to use a function such as CreateObject(). Using an <object> element makes the object available with global scope, and allows scripting tools to provide statement completion for the object's members.

Expand image Example

The following script component fragment includes an <object> element to create an object reference to the ADODB.Connection object.

Note Note

A CDATA section is required to make the script in the <script> element opaque. For details, see Script Component Files and XML Conformance.
CopyCode image Copy Code
<registration progid="ADOScriptlet"/>
<object id="cnn" progid="ADODB.Connection"/>
<public>
   <property name="cnnState"/>
   <method name="openconnection"/>
</public>

<script language="VBScript">
<![CDATA[
Dim cnnState
Function openconnection()
   cnn.ConnectionString = "driver={SQL Server};server=<enterserver>;" & _
      "uid=<enterlogon>;pwd=<enterpassword>;database=<enterdatabase>"
   cnn.Open
   If cnn.State = 1 Then
      cnnState = "open"
      cnn.Close
   Else
      cnnState = "closed"
   End If
End Function
]]>
</script>

Expand image See Also

Concepts

Script Component File Contents


<package> Element (Script Component)

Windows Script Components
<package> Element (Script Component)
See Also Example
CollapseAll image DropDown image

Encloses multiple script component definitions.

<package>
   one or more script components here
</package>

Expand image Remarks

The <package> element is optional when a .wsc file contains only one script component definition.

Expand image Example

CopyCode image Copy Code
<package>
<component id="MyScriptlet">
   (script component information here)
</component>

<component id="MyOtherScriptlet">
   (script component information here)
</component>
</package>

Expand image See Also

Concepts

Script Component File Contents


<property> Element

Windows Script Components
<property> Element
See Also Example
CollapseAll image DropDown image

Declares a property.

<property name="propertyName" [internalName="propertyVariable"] />

–or–
<property name="propertyName">
   <get [internalName="getFunctionName"] />
   <put [internalName="putFunctionName"] />
</property>

Expand image Values

propertyName

The name of the property to expose. Unless you specify an internalName attribute, this name must match the name of a global variable that will be used to hold the property's value.

propertyVariable

(Optional) The name of the global variable in the scriptlet file's <script> element that will hold the value for propertyName. If you do not include the internalName attribute, the property value is maintained in a variable named the same as propertyName. Specifying the internalName attribute allows you to use different names for the property and its corresponding global variable.

getFunctionName

(Optional) The name of a procedure that is used to read the value of the property. If you include <get> element but no <put> element, the property will be read-only. If you include a <get> element but do not specify an internalName attribute, the method used to read the property value must have the name of the property plus the get_ prefix (for example, get_lastname).

putFunctionName

(Optional) The name of a procedure that is used to write the value of the property. If you include a <put> element but no <get> element, the property will be write-only. If you include a <put> element but do not specify an internalName attribute, the method used to read the property value must have the name of the property plus the put_ prefix (for example, put_lastname).

Note Tip

In XML, you can implement elements that have no content (such as the <property> element) by closing the element with />.

Expand image Remarks

Properties can be exposed as simple values. In that case, the property is treated as a global variable inside the script component file.

You can also implement properties as procedures (functions or subroutines), which allows you to calculate a property value and to control whether a property is read-only, read-write, or write-only. In this technique, properties are implemented as a procedure (function or subroutine) in a separate <script> element. The <property> element maps the name of the property to the procedures used to implement it. The names of the procedures must match the internal names you specified in the <property> element.

When putFunctionName is called, it is passed one argument that contains the value to which to set the property.

In addition to the standard syntax shown above, you can use a shorthand notation to specify information what would otherwise be added using child tags. For example, if you want to declare a property with a "get" and "put" accessor of the same name as the property, you can use the following syntax:

CopyCode image Copy Code
<property name="myproperty" get put/>

which is functionally equivalent to:

CopyCode image Copy Code
        <property name="myproperty">
   <get/>
   <put/>
</property>

If you wanted to explicitly name those accessors differently from the default, you can use the following syntax:

CopyCode image Copy Code
<property name="myproperty" get="testget" put="testput"/>

To specify a default property, include the attribute dispid="0" in the <property> element. For details, see Exposing Properties.

Expand image Example

The following script component fragment shows the definition for four properties (sname, age, dateOfBirth, and mstatus). The sname property is a simple value. The age property is read-only, and is implemented with the function readAge. The dateOfBirth property is read-write, and is implemented with the functions readDOB and writeDOB. Finally, the mstatus property is implemented with the default functions get_mstatus and put_mstatus.

Note Note

A CDATA section is required to make the script in the <script> element opaque. For details, see Script Component Files and XML Conformance.
CopyCode image Copy Code
<public>
   <property name="sname"/>
   <property name="age">
      <get internalName="readAge"/>
   </property>
   <property name="dateOfBirth">
      <get internalName="readDOB"/>
      <put internalName="writeDOB"/>
   </property>
   <property name="mstatus">
      <get/>
      <put/>
   </property>
</public>

<script language="VBScript">
<![CDATA[
Dim sname   ' Read-write sname property (no functions).
Dim gDOB   ' Global variable used to store date of birth.
Dim gMStatus   ' global variable used to store marital status.

Function readDOB()
   ' Gets value of dateOfBirth property.
   readDOB = gDOB
End Function

Function writeDOB(newDOB)
   ' Sets value of dateOfBirth property.
   If isDate(gDOB) Then
      ' Error checking.
      gDOB = newDOB
   End If
End Function

Function readAge()
   ' Calculates read-only age property.
   If isDate(gDOB) Then
      dobM = DatePart("m", gDOB)
      dobD = DatePart("d", gDOB)
      dobY = DatePart("yyyy", gDOB)
      todayY = DatePart("yyyy", Date)
      age = todayY - dobY

      ' Adjust if birthday has not yet occurred this year.
      bday = DateValue(dobM & "/" & dobD & "/" & todayY)
      If DateDiff("d", bday, DateValue(Date)) < 0 Then
         age = age - 1
      End If
      readAge = age
   End If
End Function

Function get_mstatus()
   ' Reads value of mstatus property.
   get_mstatus = gMStatus
End Function

Function put_mstatus(s)
   ' Writes value of mstatus property.
   If s = "M" Or s = "S" Then
      gMStatus = s
   Else
      gMStatus = "?"
   End If
End Function
]]>
</script>

Expand image See Also

Tasks

Exposing Properties

Reference

<event> Element
<method> Element

Concepts

Exposing Events
Exposing Methods


<public> Element

Windows Script Components
<public> Element
See Also
CollapseAll image DropDown image

Encloses the script component's property, method, and event declarations.

<public>
   <property name="pname"/>
   <method name="mname"/>
   <event name="ename"/>
</public>

Expand image See Also

Tasks

Exposing Properties

Reference

<event> Element
<method> Element
<property> Element

Concepts

Exposing Events
Exposing Methods


<reference> Element (Script Component)

Windows Script Components
<reference> Element (Script Component)
See Also Example
CollapseAll image DropDown image

Includes a reference to an external type library.

<reference [object="progID" |guid="typelibGUID"] [version="version"]>

Expand image Values

progID

The program ID from which the type library can be derived, which can include a version number (for example, ADO.Recordset.2.0). This can include 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) The 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.

Expand image Remarks

Referencing a type library in your script component allows you to use constants defined in the type library in 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.

The <reference> element should appear inside the <component> element. If there is more than one script component in the package, the type library applies to only the script component in whose <component> element it is declared.

Expand image Example

In the following script component fragment, referencing the type library for ADO (contained in the file MSAD015.DLL) allows you to use ADO constants such as adStateOpen in your scripts.

Note Note

A CDATA section is required to make the script in the <script> element opaque. For details, see Script Component Files and XML Conformance.
CopyCode image Copy Code
<reference object="ADODB.Connection.2.0"/>
<registration progid="ADOScriptlet"/>
<public>
   <property name="cnnstate"/>
   <method name="openConnection"/>
   <method name="closeConnection"/>
</public>

<script language="VBScript">
<![CDATA[
Dim cnn
Dim cnnState
Function openConnection()
   Set cnn = CreateObject("ADODB.Connection")
   cnn.ConnectionString = "driver={SQL Server};server=<enterserver>;" & _
      "uid=<enterlogon>;pwd=<enterpassword>;database=<enterdatabase>"
   cnn.Open
   If cnn.State = adStateOpen Then
      cnnState = "open"
   Else
      cnnState = "closed"
   End If
End Function

Function closeConnection()
   cnn.Close
   cnnState = "closed"
End Function
]]>
</script>

Expand image See Also

Concepts

Referencing Other Components


<registration> Element

Windows Script Components
<registration> Element
See Also Example
CollapseAll image DropDown image

Defines information used to register the script component as a COM component.

<registration progid="progID" classid="GUID" description="description"
   version="version" [remotable=remoteFlag]/>

–or–
<registration progid="progID" classid="GUID" description="description"
      version="version" [remotable=remoteFlag]>
      <script>
            (registration and unregistration script)
      </script>
</registration>

Expand image Values

progID

(Optional) A text name that programmers use to reference your script component when creating an instance of it. For example, if your script component's program ID is Component.MyComponent, you can create an instance of it in Microsoft® Visual Basic using a statement such as the following:

Set Component = CreateObject("Component.MyComponent")

Note Note

Although a progid attribute is optional, you must include either a progid or a classid attribute (you can include both). If only the progid attribute is specified, the class ID is generated automatically. If only the class ID is created, then no progid is registered and the object can be created only by referencing the class ID directly.

GUID

(Optional) A GUID that you have generated using a class ID generation program (such as Uuidgen.exe). If you do not include a class ID, the registration program assigns a class ID to your script component.

description

(Optional) A text description of the script component that is stored in the registry and that is used in certain tools such as the Visual Basic object browser.

version

(Optional) A numeric version number that you assign. The version is appended to the program ID with a period (for example, MyComponent.1) when applications request a version-specific name. Use only numbers (decimal points are not allowed).

Note Note

The registration attributes can appear in any order in the <registration> element.

remoteFlag

(Optional) A Boolean value indicating whether the script component can be instantiated remotely using DCOM. For details, Using a Using a Script Component in an Application.

Expand image Remarks

After a script component is created, it can be registered using a program such as Regsvr32.exe, which reads the information in the <registration> element and writes it into the computer's Windows Registry. For example, a script component can be registered this way:

CopyCode image Copy Code
regsvr32 file:\\myserver\MyComponent.wsc
Note Note

A <registration> element is not required in all cases. For example, a script component that implements the DHTML Behaviors interface handler in Microsoft® Internet Explorer 5.0 does not need to be registered, because Internet Explorer registers the behaviors as they are detected on the page. For details about registration requirements, see the documentation for the interface handler you are implementing and note also which host the script component will be used in.

If you do not include class ID information, the registration program assigns a class ID to your script component at the time it is registered. However, the script component will have a different class ID everywhere it is registered. It is highly recommended that you provide a class ID for the script component yourself, to ensure that your script component has the same class ID on all computers on which it is registered.

Allowing the registration program to create a class ID can cause problems if you use the script component with development tools that store class IDs. If the registration creates a new class ID each time, it will not match the ID stored by the application.

You can optionally run scripts when a script component is registered and unregistered. To do so, include a <script> element within the <registration> element. To run script during registration, write a register( ) function. To run script when the script component has been unregistered, include an unregister( ) function.

Expand image Example

The following shows a typical <registration> element that includes both a prog ID and a class ID.

CopyCode image Copy Code
<registration
   progid="Component.TestScript"
   classid="{2154c700-9253-11d1-a3ac-0aa0044eb5f}"
   description="My Test Component"
   version="1"/>

The following registration element allows the script component to be instantiated via DCOM:

CopyCode image Copy Code
<registration>
   progid="Component.TestScript"
   classid="{2154c700-9253-11d1-a3ac-0aa0044eb5f}"
   version="1"
   description="My Test Component"
   remotable=true/>

The following example shows a <registration> element that includes script to be run when the script component is registered and unregistered.

Note Note

A CDATA section is required to make the script in the <script> element opaque. For details, see Script Component Files and XML Conformance.

CopyCode image Copy Code
<registration
   progid="Component.TestScript"
   classid="{2154c700-9253-11d1-a3ac-0aa0044eb5f}">
   version="1"
   description="My Test Component">

   <script language="VBScript">
      Function register()
         MsgBox "Component 'My Test Component' registered."
      End Function
      Function unregister()
         MsgBox "Component 'My Test Component' unregistered."
      End Function
   </script>
   ]]>
</registration>

Expand image See Also

Concepts

Creating Registration Information
Registering a Script Component


<resource> Element (Script Component)

Windows Script Components
<resource> Element (Script Component)
See Also Example
CollapseAll image DropDown image

Isolates textual or numeric data that should not be hard-coded into the script component's scripts.

<resource id="resourceID">
     text or number here
</resource>

Expand image Values

ResourceID

A unique identifier for the resource within the script component.

Expand image Remarks

The <resource> element allows you to isolate strings or numbers in your script component that you want to intermingle with script in your script component. For example, resource elements are typically used to maintain strings that might be localized into another language.

To get the value of a resource, call the getResource function, passing it the ID of the resource you want to use.

Expand image Example

The following script component fragment defines a resource (called errNonNumeric) and demonstrates how to use it in script.

Note Note

A CDATA section is required to make the script in the <script> element opaque. For details, see Script Component Files and XML Conformance.
CopyCode image Copy Code
<public>
   <method name="random" internalName="getRandomNumber"/>
</public>
<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>

Expand image See Also

Concepts

Referencing Other Components


<script> Element (Script Component)

Windows Script Components
<script> Element (Script Component)
See Also Example
CollapseAll image DropDown image

Defines the script component's behavior.

<script language="language">
   script here
</script>

Expand image Values

language

The name of the scripting language used in the script component file, such as Microsoft® Visual Basic® Scripting Edition (VBScript) or JScript.

Expand image 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 ?> declaration at the top of the script component 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 make sure that characters in your script element are not treated as XML reserved characters. To do so, enclose the actual script in a <![CDATA[ ... ]]> section. For details about XML validation, see Script Component Files and XML Conformance.

Note Note

Do not include a CDATA section unless you also include the <?XML?> declaration.

Expand image Example

CopyCode image Copy Code
<?XML version="1.0"?>
<component id="ScriptletFactorial">
<registration progid="Component.Factorial"/>
<public>
   <method name="factorial"/>
</public>

<script language="VBScript">
<![CDATA[
Function factorial(n)
   If isNumeric(n) Then
      If n <= 1 Then
         factorial = 1
      Else
         factorial = n * factorial(n-1)
      End If
   Else
      factorial = -2   ' Error code.
   End If
End Function
]]>
</script>
</component>

Expand image See Also

Concepts

Script Component File Contents


createComponent Function

Windows Script Components
createComponent Function
See Also Example
CollapseAll image DropDown image

Returns a reference to another script component in the same package (.wsc file).

value = createComponent(componentID)

Expand image Values

componentID

The unique identifier for the script component to create an instance of.

Expand image Remarks

By calling the createComponent method, you can include the functionality of another script component in the same file. For more details, see Referencing Another Script Component in the Same Package.

Expand image Example

The following example shows two script components in the same package. The first script component calls the second script component when its math method is called.

Note Note

A CDATA section is required to make the script in the <script> element opaque. For details, see Script Component Files and XML Conformance.

CopyCode image Copy Code
<package>
<component id="component1">
<registration progid="component.FrontEnd"/>
<public>
   <method name="math"/>
</public>
<script language="JScript">
<![CDATA[
function math(){
   return createComponent("component2")
}
]]>
</script>
</component>

<component id="component2">
<registration progid="component.Math"/>
<public>
   <method name="add"/>
</public>
<script language="JScript">
<![CDATA[
function add(n1, n2){
   return n1+n2;
}
]]>
</script>
</component>
</package>

After registering this package, you can use it as illustrated in the following commands:

CopyCode image Copy Code
set o1 = CreateObject("component.FrontEnd")
Set o2 = o1.math()
msgbox(o2.add(4,5))

Expand image See Also

Concepts

Referencing Another Script Component in the Same Package


fireEvent Method (Script Component)

Windows Script Components
fireEvent Method (Script Component)
See Also Example
CollapseAll image DropDown image

Sends notification of a custom event from the script component to the host application.

fireEvent(eventName[,...])

Expand image Values

eventName

The name of the event as defined in the <event> element.

Expand image Remarks

You can only fire events if they have been declared in the <public> element.

Note Note

The Behavior handler exposes a fireEvent method that is similar to the Automation handler version, but which includes support for event objects. For details, see Exposing Custom Events in Behavior Script Components.

Expand image Example

The following shows a fragment of a script component that defines the event namechanged and shows how to fire it.

Note Note

A CDATA section is required to make the script in the <script> element opaque. For details, see Script Component Files and XML Conformance.
CopyCode image Copy Code
<public>
   <property name="name">
      <get/>
      <put/>
   </property>
   <event name="namechanged">
</public>

<script language="VBScript">
<![CDATA[
var name
Sub get_lowercaseName()
   get_lowercaseName = name
End Sub

Sub put_lowercaseName(newLCName)
   name = newLCName
   fireEvent("namechanged")
End Sub
]]>
</script>

Expand image See Also

Reference

<event> Element
fireEvent method (Behavior Handler Reference)

Concepts

Exposing Events


getResource Function

Windows Script Components
getResource Function
See Also Example
CollapseAll image DropDown image

Gets the value of a resource defined with the <resource> element.

value = getResource(resourceID)

Expand image Values

resourceID

A unique identifier for the resource within the script component.

Expand image Remarks

The <resource> element allows you to isolate strings or numbers in your script component that you want to intermingle with script in your script component. For example, resource elements are typically used to maintain strings that might be localized into another language. You can use the getResource function in the script component's script to extract the contents of a <resource> element.

Expand image Example

The following script component fragment defines a resource (called errNonNumeric) and how to use it in script.

Note Note

A CDATA section is required to make the script in the <script> element opaque. For details, see Script Component Files and XML Conformance.
CopyCode image Copy Code
<public>
   <method name="random" internalName="getRandomNumber"/>
</public>
<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>

Expand image See Also

Concepts

Referencing Other Components


Behavior Handler Reference

Windows Script Components
Behavior Handler Reference
DropDown image

With the Behavior handler, Microsoft® Internet Explorer provides a means for a Behavior script component to communicate back to its containing page through custom events and to access the containing document's object model.

The following elements, properties, and methods are specific to the Behavior Handler.

  • <attach> Element

  • <layout> Element

  • element Property

  • attachNotification Method

  • createEventObject Method

  • fireEvent Method


<attach> Element

Windows Script Components
<attach> Element
See Also Example
CollapseAll image DropDown image

Binds an event from the containing document to a function in the script component.

<attach event="eventName" handler="functionName" [for="elementName"]/>

Expand image Values

eventName

The event being bound, such as onmouseclick.

functionName

The name of the procedure (function or subroutine) in the script component file that is executed in response to the event. If this attribute is omitted, it is generated.

If the for attribute is not specified, the default value of the handler attribute is the value of the event attribute. If the for attribute is specified, the default handler attribute value is the string generated by concatenating the for attribute value, "_", and the event attribute value.

elementName

The element associated with the event, used for containing elements to which DHTML Behaviors are not explicitly attached. The only possible values for the for attribute are "document," "window," and "element." If the for attribute is not included, "element" is the default and the event is assumed to be fired on the element to which the behavior is attached.

Expand image Example

In the following example, the <attach> element binds three events to functions. For example, the DHTML onmouseover element is bound to the script component's do_onmouseover function. The functions bound to the DHTML onmouseover and onmouseout events are executed only if they are fired on the element in the containing document to which the behavior is attached. The docinit function is explicitly bound to the DHTML document object's onload event.

Note Note

A CDATA section is required to make the script in the <script> element opaque. For details, see Script Component Files and XML Conformance.
CopyCode image Copy Code
<?XML version="1.0"?>
<component id="bvrscript component1">
<registration progID="Behaviorscript component"/>
<implements type="Behavior">
   <attach event="onmouseover" handler="do_onmouseover"/>
   <attach event="onmouseout "handler="do_onmouseout"/>
   <attach for="window" event="onload" handler="docinit"/>
</implements>
<script language="JScript">
<![CDATA[
var normalColor, normalSpacing;
function do_onmouseover(){
   // Save original values.
   normalColor = style.color;
   normalSpacing= style.letterSpacing;
   style.color = "red";
   style.letterSpacing = 2;
}
function do_onmouseout(){
   // Reset to original values.
   style.color = normalColor;
   style.letterSpacing = normalSpacing;
}
function docinit(){
   document.linkColor = "red";
}
]]>
</script>
</component>

Expand image See Also

Concepts

Creating a Behavior Script Component


<layout> Element

Windows Script Components
<layout> Element
Example
CollapseAll image DropDown image

Defines HTML text inserted into the containing document.

<layout>
   <HTMLtag>Inserted text</HTMLtag>
</layout>

Expand image Values

HTMLTag

The name of HTML tag for which the element's text is a replacement.

Expand image Remarks

When the behavior is called, the text in the <layout> element is read into the corresponding element in the containing document. This behavior is equivalent to setting the element's DHTML innerHTML property.

If the script component is not defined to be XML-conformant, the contents of the <layout> element are opaque. However, if the script component is XML-conformant, the contents of the <layout> element must explicitly be made opaque by including them in a CDATA. For more details, see Script Component Files and XML Conformance.

Expand image Example

The following shows an example of a script component with a <layout> element. Because the script component contains the <?XML ?> declaration at the top, the <layout> element contains a CDATA section to make the contents of the <layout> element opaque to the XML parser.
CopyCode image Copy Code
<?XML version="1.0" ?>
<component id="bvrScriptlet1">
<registration progID="BehaviorScriptlet"/>
<implements type="Behavior">
   <layout>
   <![CDATA[
      <h1>This is the HTML to show in the element</h1>
   ]]>
   </layout>
</implements>
</component>


element Property

Windows Script Components
element Property
Example
CollapseAll image DropDown image

Returns the element to which the behavior is being applied.

[oElement = ] Behavior.element

Expand image Values

oElement

Element to which the behavior is being applied.

Behavior

The ID of the <implements> element used to implement the Behavior interface.

Note Note

By default, the properties and methods exposed by the Behavior handler are automatically added to the global script namespace and can be accessed without referencing the Behavior handler ID. In this case, instead of using Behavior.element as shown in the syntax, the property can be used in script simply as element. For more details, see the <implements> element.

Expand image Remarks

The property is read-only.

With this property, a behavior is able to communicate with the containing document. All properties, methods, and events exposed by the DHTML object model are accessible through this property.

Expand image Example

The following script component fragment implements an expanding and collapsing table of contents using a script component. The script component attaches to the element's DHTML onmouseover event. It sets the DHTML cursor property of the element to "hand" to signal the user that the element can be clicked in order to toggle visibility of its children.

Note Note

A CDATA section is required to make the script in the <script> element opaque. For details, see Script Component Files and XML Conformance.
CopyCode image Copy Code
<public>
   <attach event="onmouseover" handler="event_onmouseover");
</public>

<implements type="Behavior"/>
<script language="JScript">
<![CDATA[
   function event_onmouseover()
   {
      oElement = window.event.srcElement;
      if (oElement == element)
         oElement.style.cursor = "hand";
   }
]]>
</script>


attachNotification Method

Windows Script Components
attachNotification Method
See Also Example
CollapseAll image DropDown image

Binds a function in the script component to a notification message sent from the host.

behavior.attachNotification (fpNotify)

Expand image Values

behavior

The ID of the <implements> element used to implement the Behavior interface.

Note Note

By default, the properties and methods exposed by the Behavior handler are automatically added to the global script namespace and can be accessed without referencing the Behavior handler ID. In this case, instead of using Behavior.attachNotification as shown in the syntax, the method can be used in script simply as attachNotification. For more details, see the <implements> element.

fpNotify

The name of the function to bind to the notification.

Expand image Remarks

Currently, the host can call the specified function with the following notifications:

  • "contentReady" There has been a change to the content of the element to which the behavior is attached. This is fired as soon as the closing tag of the element is parsed, as well as when a script sets the DHTML innerHTML property of the element. A behavior can use this notification to retrieve the content of the element it is applied to.

  • "documentReady" The browser has finished parsing the document. Any modifications or initializations that need to be made to the content can take place at this point.

    Note Note

    The attachNotification method does not notify the script component of standard events that occur in the document, window, or any element on the page. The recommended way to receive notifications on this type of event is by using the DHTML achEvent method.

When dealing with changes to an element's DHTML style property, such as setting its visibility, changing colors, or changing fonts, it is recommended that the changes be made inline in the script component's <script> element, as shown in the following script component fragment. Making the change in the documentReady notification clause can cause slight flashing.

Note Note

A CDATA section is required to make the script in the <script> element opaque. For details, see Script Component Files and XML Conformance.

CopyCode image Copy Code
<implements type="Behavior"/>
<script language="JScript">
<![CDATA[
   style.color = "green";
   style.letterSpacing = 5;
]]>
</script>

Expand image Example

The example below demonstrates how a function could be set up to trap notifications and process them as appropriate.

Note Note

A CDATA section is required to make the script in the <script> element opaque. For details, see Script Component Files and XML Conformance.
CopyCode image Copy Code
<?XML version="1.0"?>
<component>
<implements type="Behavior">
   <event name="onResultChange"/>
</implements>

<script language="JScript">
<![CDATA[
   attachNotification (onNotification);
   function onNotification (sNotification){
      if (sNotification == "contentReady"){
         // Contents of element have changed.
      }
      else if (sNotification == "documentReady"){
         // Host has finished parsing element.
      }
      window.status = sNotification;
   }
]]>
</script>
</component>

Expand image See Also

Reference

<event> Element


createEventObject Method

Windows Script Components
createEventObject Method
See Also Example
CollapseAll image DropDown image

Creates a DHTML event object to be used in passing event context information to the containing document when the fireEventmethod is called.

oEvent = behavior.createEventObject()

Expand image Values

behavior

The ID of the <implements> element used to implement the Behavior interface.

Note Note

By default, the createEventObject method has global scope and can be accessed without referencing the Behavior handler ID. For example, instead of using Behavior.createEventObject as shown in the syntax, you can simply call the function as createEventObject. For more details, see the <implements> element.

oEvent

An event object created by the method.

Expand image Remarks

The same event object cannot be reused in multiple fireEvent calls.

Expand image Example

The following partial script component is derived from a hypothetical calculator script component. Whenever the result changes, the script component fires a custom onResultChange event back to the page, passing the result as an expando property of the event object.

Note Note

A CDATA section is required to make the script in the <script> element opaque. For details, see Script Component Files and XML Conformance.

CopyCode image Copy Code
<component>
<implements type="Behavior">
   <event name="onResultChange"/>
</implements>

<script language="JScript">
<![CDATA[
attachEvent("onclick", doCalc);

function doCalc()
{
   // Code here to perform calculation. Results are placed into
   // the variable sResult.
   oEvent = createEventObject();
   oEvent.result = sResult;
   fireEvent("onResultChange",oEvent);
}
]]>
</script>
</component>

The following shows what the containing DHTML page might look like. When the onResultChange event fires, the results of the calculation are extracted from expando property result of the DHTML window.event object and displayed in the resultWindow <DIV> element.

CopyCode image Copy Code
<HTML>
<HEAD>
<xml:namespace prefix="LK" />
<style>
   LK\:CALC {behavior:url(engine.wsc)}
</style>
<script language="JScript">
function showResults(){
   resultWindow.innerText=window.event.result;
}
</script>
</HEAD>

<LK:CALC id="myCalc" onResultChange="showResults()">
<TABLE>
<TR>
   <DIV ID=resultWindow
      STYLE="border: '.025cm solid gray'"
         ALIGN=RIGHT>0.</DIV>
</TR>
<TR>
   <TD><INPUT TYPE=BUTTON VALUE=" 0 "></TD>
   <TD><INPUT TYPE=BUTTON VALUE="+/-"></TD>
   <TD><INPUT TYPE=BUTTON VALUE=" . "></TD>
   <TD><INPUT TYPE=BUTTON VALUE=" + "></TD>
   <TD><INPUT TYPE=BUTTON VALUE=" = "></TD>
<TR>
</TABLE>
</LK:CALC>
</HTML>

Expand image See Also

Concepts

Exposing Custom Events in Behavior Script Components


fireEvent method (Behavior Handler Reference)

Windows Script Components
fireEvent method (Behavior Handler Reference)
See Also Example
CollapseAll image DropDown image

Fires a custom event.

Behavior.fireEvent(sEvent[, oEvent])

Expand image Values

Behavior

The ID of the <implements> element used to implement the Behavior interface.

Note Note

By default, the properties and methods exposed by the Behavior handler are automatically added to the global script namespace and can be accessed without referencing the Behavior handler ID. In this case, instead of using Behavior.fireEvent as shown in the syntax, the property can be used in script simply as fireEvent. For more details, see the <implements> element.

sEvent

The name of the custom event as declared in the <implements> element.

oEvent

(Optional) Specifies an event object containing context information. The event object is created using the createEventObject method.

Expand image Remarks

The same event object cannot be reused in multiple calls to the fireEvent method.

Expand image Example

The following partial script component is derived from a calculator script component sample. Whenever the result changes, the script component fires a custom onResultChange event back to the page, passing the result as an expando property of the event object.

Note Note

A CDATA section is required to make the script in the <script> element opaque. For details, see Script Component Files and XML Conformance.

CopyCode image Copy Code
<component>
<public>
   <event name="onResultChange" />
</public>

<implements type="Behavior">
   <attach event="onclick" handler="doCalc");
</implements>

<script language="JScript">
<![CDATA[
function doCalc(){
   // Code here to perform calculation. Results are placed into
   // the variable sResult.

   oEvent = createObjectEvent();
   oEvent.result = sResult;
   fireEvent("onResultChange",oEvent);
}
]]>
</script>
</component>

The following shows what the containing DHTML page might look like. When the onResultChange event fires, the results of the calculation are extracted from expando property result of the window.event object and displayed in the resultWindow <DIV> element.

CopyCode image Copy Code
<HTML>
<HEAD>
<xml:namespace prefix="LK" />
<style>
   LK\:CALC {behavior:url(engine.wsc)}
</style>
<script language="JScript">
function showResults(){
   resultWindow.innerText=window.event.result;
}
</script>
</HEAD>

<LK:CALC id="myCalc" onResultChange="showResults()">
<TABLE>
<TR>
   <DIV ID=resultWindow
      STYLE="border: '.025cm solid gray'"
      ALIGN=RIGHT>0.</DIV>
</TR>
<TR>
   <TD><INPUT TYPE=BUTTON VALUE=" 0 "></TD>
   <TD><INPUT TYPE=BUTTON VALUE="+/-"></TD>
   <TD><INPUT TYPE=BUTTON VALUE=" . "></TD>
   <TD><INPUT TYPE=BUTTON VALUE=" + "></TD>
   <TD><INPUT TYPE=BUTTON VALUE=" = "></TD>
<TR>
</TABLE>
</LK:CALC>
</HTML>

Expand image See Also

Concepts

Exposing Custom Events in Behavior Script Components


Windows Script Host
Windows Script Host
DropDown image

The following sections provide information about Windows Script Host along with a reference section that documents the object model.

In This Section

Getting Started

Information about new features, upgrading of Windows Script Host, and tips for getting started.

Windows Script Host Basics

General overview of Windows Script Host and the Windows Script Host object model.

Running Your Scripts

How to run scripts and set Windows Script Host properties.

Setting up Remote WSH

Information on using Remote Windows Script Host.

Basic Windows Script Host Tasks

Common tasks that you can do with Windows Script Host.

Security and Windows Script Host

Security model for Windows Script Host.

Reference

The Windows Script Host object-model documentation.


Getting Started (Windows Script Host)

Windows Script Host
Getting Started (Windows Script Host)
DropDown image

The following sections provide introductory material that forms the foundation for understanding Windows Script Host.

In This Section

What's New in WSH 5.6

Description of the new features in WSH 5.6.

Upgrading Windows Script Host

Information on upgrading from version 2 to version 5.6 of Windows Script Host.

Document Conventions

Description of the syntax and conventions used in WSH 5.6 help documentation.

WSH Version Information

List of Windows Script Host versions by host application and list of features by version.

Related Sections

WSH Reference

List of elements that make up WSH Reference.

Windows Script Host Basics

Learn the basics of WSH.


What's New In WSH 5.6

Windows Script Host
What's New In WSH 5.6
DropDown image

Several areas of functionality have been addressed in this latest version of the Windows Script Host (version 5.6).

Improved Argument Handling

  • 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 spawned process.

    Exec Method

    Accessing the standard streams programmatically.

    Exec Method

    WshScriptExec Object

    Accessing environment variables programmatically.

    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 object.

    Exists Method

    Determining the number of switches in the WshNamed or WshUnnamed objects.

    Count Method

Running 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

Treating New Process 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)

Accessing 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

  • A new security model makes distributing and running scripts safer.

    To Learn About See

    Script signing and verification.

    Security and Windows Script Host


Upgrading Windows Script Host

Windows Script Host
Upgrading Windows Script Host
See Also
DropDown image

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 upgrade to WSH 5.6, visit Microsoft Windows Script TechnologiesMicrosoft Windows Script Technologies at (http://msdn.microsoft.com/scripting/).

Note Note

The latest version of WSH is version 5.6. The previous version was version 2.

See Also

Concepts

WSH Version Information


Document Conventions (Windows Script Host)

Windows Script Host
Document Conventions (Windows Script Host)
DropDown image

Windows Script Host documentation uses the following typographic and code conventions.

Conventions

Description Convention

This font is used for code, variables, and error message text.
CopyCode image Copy Code
WScript.Echo "Hello from VBScript"

Featured elements in code examples appear bold.
CopyCode image Copy Code
WScript.Echo "Hello from VBScript"

Words in bold with initial letter capitalized indicate language-specific keywords or named elements of the user interface.

in the Script tab within the Properties dialog

Links appear underlined

WshNetwork Object

In syntax, underlined items are arguments or parameters.

<?job error="flag" debug="flag" ?>


WSH Version Information

Windows Script Host
WSH Version Information
DropDown image

The following table lists the version of Windows Script Host implemented by Microsoft host applications.

Host Application Table

Host Application | 1.0 | 2.0 | 5.6
Microsoft Windows 98 | X |  |
Microsoft Windows NT 4 Option Pack | X |  |
Microsoft Windows 2000 |  | X |
Microsoft Windows XP |  |  | X

Language Element Table

The following table lists the version of Windows Script Host implemented by Microsoft host applications.

Language Element | 1.0 | 2.0 | 5.6
<?job?> Element |  | X |
<?XML?> Element |  | X |
AddPrinterConnection Method | X |  |
AddWindowsPrinterConnection Method |  | X |
AppActivate Method |  | X |
arguments Property (JScript 5.6) | X |  |
AtEndOfLine Property (Windows Script Host) |  | X |
AtEndOfStream Property (Windows Script Host) |  | X |
Character Property |  |  | X
Close Method (Windows Script Host) |  | X |
Column Property (Windows Script Host) |  | X |
ComputerName Property | X |  |
ConnectObject Method |  | X |
Count Method (Windows Script Host) | X |  |
CreateObject Method | X |  |
CreateScript Method |  |  | X
CreateShortcut Method | X |  |
Description Property (Windows Script Host) | X |  |
Description Property (WshRemoteError) |  |  | X
DisconnectObject Method | X |  |
Echo Method | X |  |
EnumNetworkDrives Method | X |  |
EnumPrinterConnections Method | X |  |
Environment Property | X |  |
Error Property (WshRemote) |  |  | X
<example> Element |  |  | X
Exec Method (Windows Script Host) |  |  | X
Execute Method (Windows Script Host) |  |  | X
Exists Method (Windows Script Host) |  |  | X
ExitCode Property |  |  | X
ExpandEnvironmentStrings Method | X |  |
FullName Property (WScript Object) | X |  |
GetObject Method | X |  |
getResource Method |  | X |
Hotkey Property | X |  |
IconLocation Property | X |  |
Item Property (Windows Script Host) | X |  |
Item Property (WshNamed) |  |  | X
Item Property (WshUnnamed) |  |  | X
<job> Element |  | X |
length Property (WSHArguments Object) | X |  |
Line Property (WScript) |  | X |
Line Property (WshRemoteError) |  |  | X
LogEvent Method |  | X |
MapNetworkDrive Method | X |  |
Name Property (WScript Object) | X |  |
<named> Element |  |  | X
Number Property (Windows Script Host) |  |  | X
<object> Element (Windows Script Host) |  | X |
<package> Element (Windows Script Host) |  | X |
Path Property (Windows Script Host) | X |  |
Popup Method | X |  |
ProcessID Property (Windows Script Host) |  |  | X
Quit Method (Windows Script Host) | X |  |
Read Method (Windows Script Host) |  | X |
ReadAll Method (Windows Script Host) |  | X |
ReadLine Method (Windows Script Host) |  | X |
<reference> Element (Windows Script Host) |  | X |
RegDelete Method | X |  |
RegRead Method | X |  |
RegWrite Method | X |  |
Remove Method (Windows Script Host) | X |  |
RemoveNetworkDrive Method | X |  |
RemovePrinterConnection Method | X |  |
<resource> Element (Windows Script Host) |  |  |
Run Method (Windows Script Host) | X |  |
<runtime> Element (Windows Script Host) |  |  | X
Save Method (Windows Script Host) | X |  |
<script> Element (Windows Script Host) |  | X |
ScriptFullName Property | X |  |
ScriptName Property | X |  |
SendKeys Method |  | X |
SetDefaultPrinter Method | X |  |
ShowUsage Method |  |  | X
Skip Method (Windows Script Host) |  | X |
SkipLine Method (Windows Script Host) |  | X |
Sleep Method |  | X |
Source Property (Windows Script Host) |  |  | X
SourceText Property |  |  | X
SpecialFolders Property | X |  |
SpecialFolders Property |  |  | X
Status Property (WshScriptExec) |  |  | X
StdErr Property (WScript) |  | X |
StdErr Property (WshScriptExec) |  |  | X
StdIn Property (WScript) |  | X |
StdIn Property (WshScriptExec) |  |  | X
StdOut Property (WScript) |  | X |
StdOut Property (WshScriptExec) |  |  | X
TargetPath Property | X |  |
Terminate Method (WshScriptExec) |  |  | X
<usage> Element |  |  | X
UserDomain Property | X |  |
UserName Property | X |  |
Version Property (Windows Script Host) | X |  |
WindowStyle Property | X |  |
WorkingDirectory Property (Windows Script Host) | X |  |
Write Method (Windows Script Host) |  | X |
WriteBlankLines Method (Windows Script Host) |  | X |
WriteLine Method (Windows Script Host) |  | X |
WScript Object | X |  |
WshArguments Object | X |  |
WshController Object |  |  | X
WshEnvironment Object | X |  |
WshNamed Object |  |  | X
WshNetwork Object | X |  |
WshRemote Object |  |  | X
WshRemoteError Object |  |  | X
WshScriptExec Object |  |  | X
WshShell Object | X |  |
WshShortcut Object | X |  |
WshSpecialFolders Object | X |  |
WshUnnamed Object |  |  | X
WshUrlShortcut Object | X |  |


Windows Script Host Basics

Windows Script Host
Windows Script Host Basics
DropDown image

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 This Section

What Is WSH?

General overview of Windows Script Host

Creating Scripts that Can Be Used by WSH

How to create a WSH-compatible script

Windows Script Host Object Model

A roadmap to the architecture

Related Sections

WSH Language

List of elements that make up WSH Reference.


What Is WSH?

Windows Script Host
What Is WSH?
See Also
DropDown image

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 Note

You can also go to the web site 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

Reference

CreateObject Method
GetObject Method

Concepts

Windows Script Host Object Model


Scripts and Automating Windows

Windows Script Host
Scripts and Automating Windows
See Also
DropDown image

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

Concepts

Types of Script Files


Types of Script Files

Windows Script Host
Types of Script Files
See Also
DropDown image

Stand-alone scripts come in several varieties, and each has its own extension. The following table is a list of some common types.

Common Script Types

Extension | Script Type | Description
.bat | MS-DOS batch file | MS-DOS operating system batch file
.asp | ASP page | Active Server Page file
.html | HTML file | Web page
.js | JScript file | Windows script
.vbs | VBScript file | Windows script
.wsf | Windows Script Host file | Container or project file for a Windows script; supported by WSH 2.0 and later.
.wsh | Windows Script Host files | 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

Concepts

Windows Script Host Object Model


Hosting Environments and Script Engines

Windows Script Host
Hosting Environments and Script Engines
DropDown image

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 Note

For more information, see Microsoft Developer Network (MSDN) (http://msdn.microsoft.com/library/default.asp?URL=/library/en-us/dnclinic/html/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 Note

If you need to run another engine, that engine must be registered properly.


Creating Scripts that Can Be Used by WSH

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. Start Notepad.

  2. Write your script. For example purposes, type WScript.Echo("Hello World!");

  3. Save this text file with a .js extension (instead of the default .txt extension). For example, Hello.js.

  4. Navigate to the file you just saved, and double-click it.

  5. Windows Script Host invokes the JScript engine and runs your script. In the example, a message box is displayed with the message "Hello World!"


Dividing Scripts into Reusable Parts

Windows Script Host
Dividing Scripts into Reusable Parts
DropDown image

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.

Robust Code

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.


Windows Script Host Object Model

Windows Script Host
Windows Script Host Object Model
DropDown image

The Windows Script Host object model consists of 14 objects. The root object is the WScript object.

Object Model Illustration

The illustration that follows represents the Windows Script Host Object Model hierarchy.

The Windows Script Host Object Model Hierarchy

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 What you can do with this object

Wscript

  • 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)

WshArguments

Access the entire set of command-line arguments

WshNamed

Access the set of named command-line arguments

WshUnnamed

Access the set of unnamed command-line arguments

WshNetwork

  • Connect to and disconnect from network shares and network printers

  • Map and unmap network shares

  • Access information about the currently logged-on user

WshController

Create a remote script process using the Controller method CreateScript()

WshRemote

  • Remotely administer computer systems on a computer network

  • Programmatically manipulate other programs/scripts

WshRemote Error

Access the error information available when a remote script (a WshRemote object) terminates as a result of a script error

WshShell

  • 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)

WshShortcut

Programmatically create a shortcut

WshSpecialfolders

Access any of the Windows Special Folders

WshURLShortcut

Programmatically create a shortcut to an Internet resource

WshEnvironment

Access any of the environment variables (such as WINDIR, PATH, or PROMPT)

WshScriptExec

Determine status and error information about a script run with Exec()

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).


Running Your Scripts

Windows Script Host
Running Your Scripts
See Also
DropDown image

There are three ways to run your scripts.

How to Run 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

Concepts

Running Scripts from Windows
Running Scripts from the Command Prompt
What to Include to Run a Script
WSH Drag and Drop Support


Using Windows Script Files (.wsf)

Windows Script Host
Using Windows Script Files (.wsf)
DropDown image

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 engine-specific, they can contain script from any Windows Script compatible scripting engine. They act as a container.

Additional Features

.wsf files support | You can
Include statements | Incorporate functions from VBScript or JScript files into your Windows Script Host project.
Multiple engines | Use more than one scripting language per file.
Type libraries | Add constants to your code.
Tools | Edit files with any XML editor.
Multiple jobs in one file | 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.

CopyCode image Copy Code
<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
   <script>
</job>

The fso.js file contains the following:

CopyCode image Copy Code
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:

CopyCode image Copy 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.

CopyCode image Copy Code
Public Const MyError = "You are not using MyComponent correctly"

The type library is contained in mycomponent.lib, which is installed in C:\MyComponent.

CopyCode image Copy Code
<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.

CopyCode image Copy Code
CScript //Job:MyFirstJob MyScripts.wsf


WSH Drag and Drop Support

Windows Script Host
WSH Drag and Drop Support
DropDown image

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.

Procedures

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:

    CopyCode image Copy Code
    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 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.


Setting and Customizing Script Properties (.wsh)

Windows Script Host
Setting and Customizing Script Properties (.wsh)
DropDown image

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.

Procedures

To create a .wsh file for a given script

  1. Right-click the script file in Windows Explorer.

  2. Click Properties on the shortcut menu.

  3. Choose the settings you want for the script.

  4. 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:

CopyCode image Copy Code
[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 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.


Running Scripts from the Command Prompt

Windows Script Host
Running Scripts from the Command Prompt
See Also
DropDown image

Windows Script Host enables you to run scripts from the command prompt. CScript.exe provides command-line switches for setting script properties.

Procedures

To run scripts using CScript.exe

  • Type a command at the command prompt using the following syntax:

    CopyCode image Copy Code
    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:

CopyCode image Copy Code
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):

    CopyCode image Copy Code
    cscript //logo c:\"sample scripts"\chart.vbs
cscript //nologo c:\"sample scripts"\chart.VBScript

See Also

Concepts

Running Scripts from Windows
What to Include to Run a Script
WScript.exe and CScript.exe Options


Running Scripts from Windows

Windows Script Host
Running Scripts from Windows
See Also
DropDown image

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.

To Change to CScript

On initial installation, the default host is WScript. To change it to CScript, type the following at the command line:

CopyCode image Copy Code
cscript //h:cscript

Or, to change it from CScript to WScript:

CopyCode image Copy Code
wscript //h:cscript

Procedures

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 Note

    On Windows NT 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.

-or-

  1. 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 | Description
Stop script after specified number of seconds. | Specifies the maximum number of seconds that a script can run. The default is no limit. CScript.exe equivalent: //T:nn
Display logo when script is executed in command console. | 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

Concepts

Running Scripts from the Command Prompt
What to Include to Run a Script
WScript.exe and CScript.exe Options


WScript.exe and CScript.exe Options

Windows Script Host
WScript.exe and CScript.exe Options
DropDown image

For the most part, options listed in the following table are applicable to both WScript.exe and CScript.exe. Exceptions are noted.

Options

Parameter | Description
/B | Batch mode; suppresses command-line display of user prompts and script errors. Default is Interactive mode.
/D | Turns on the debugger.
/E:engine | Executes the script with the specified script engine.
/H:CScript or /H:WScript | Registers CScript.exe or WScript.exe as the default application for running scripts. If neither is specified, WScript.exe is assumed as the default.
/I | Default. Interactive mode; allows display of user prompts and script errors Opposite of Batch mode.
/Job:<JobID> | Runs the specified JobID from the .wsf file.
/logo | Default. Displays a banner. Opposite of nologo.
/nologo | Prevents display of an execution banner at run time. Default is logo.
/S | Saves the current command-line options for this user.
/T:nn | 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.
/U | 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.
/X | Launches the program in the debugger.
/? | Displays a brief description of and usage information for command parameters (the usage information).


What to Include to Run a Script

Windows Script Host
What to Include to Run a Script
See Also
DropDown image

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.

Windows Version Information

WSH Executable File | Windows Version | Include
Command prompt | Windows NT or 2000 | 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.
Command prompt | Windows 9x or Millennium | Specify the script's file extension and precede the script name with the WSH executable filename. Example: cscript myScript.wsf
Run command from Open box | Windows NT, 2000, 9x, or Millennium | Specify the script's file extension.

See Also

Concepts

Running Scripts from Windows
Running Scripts from the Command Prompt
WSH Drag and Drop Support


Setting up Remote WSH

Windows Script Host
Setting up Remote WSH
See Also
DropDown image

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 Note

Both the remote and local machines must be running Windows NT 4 SP3 or greater in order to use Remote WSH.

Procedures

To enable a machine to run remote scripts

  1. Install WSH V5.6 on the machine. If you are using Windows XP or have installed Internet Explorer 6 or greater, WSH 5.6 has already been installed.

    Note Note

    WSH 5.6 is available for download from the Web at http://msdn.microsoft.com/scripting

  2. Add yourself to the remote machine's Local Administrators group.

  3. To enable Remote WSH, use the System Policy Editor (Poledit.exe) on the server.

    Note Note

    An administrator who wants to enable Remote WSH should add a subkey entry named Remote of type REG_SZ to the registry key HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows Script Host\Settings. To enable Remote WSH, set the value of Remote to 1; to disable Remote WSH, set the value to 0. If the value of the Remote value is not set, by default Remote WSH is disabled.

    Note Note

    For more information on the System Policy Editor, see the Microsoft Windows online help system.

  4. WSH is enabled on the machine. To test it, see Running Scripts Remotely.

See Also

Concepts

Running Scripts Remotely

Other Resources

Security and Windows Script Host


Basic Windows Script Host Tasks

Windows Script Host
Basic Windows Script Host Tasks
DropDown image

This section contains several commonly used Windows Scripting Host 5.6 scripts, which demonstrate basic functions.

Note Note

The scripts presented in the 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)

WSH Walkthrough

WSH Network Administrator Sample Script

Related Sections

WSH Language


Accessing Networks

Windows Script Host
Accessing Networks
See Also
DropDown image

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

Other Resources

Basic Windows Script Host Tasks


Accessing Network Connections

Windows Script Host
Accessing Network Connections
See Also
DropDown image

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.

Arguments for MapNetworkDrive Method

  • 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

    CopyCode image Copy Code
    // JScript.
var net;
net = new ActiveXObject("WScript.Network");
net.MapNetworkDrive("I:", "\\\\computer2\\public","True");

' VBScript.
Dim net
Set net = CreateObject("WScript.Network")
net.MapNetworkDrive "I:", "\\computer2\public","True"

See Also

Other Resources

Accessing Networks


Controlling Networked Printers

Windows Script Host
Controlling Networked Printers
See Also
DropDown image

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.

CopyCode image Copy Code
// 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.

CopyCode image Copy Code
// 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

Reference

AddWindowsPrinterConnection Method
SetDefaultPrinter Method
RemovePrinterConnection Method

Other Resources

Accessing Networks


Creating an Automated Login Script

Windows Script Host
Creating an Automated Login Script
See Also
DropDown image

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.

Example

Note Note

In Windows 9x, include a delay so user logon takes affect.

CopyCode image Copy Code
// JScript.
var oNet, sUser, cInitial, startTime;
oNet = new ActiveXObject("WScript.Network");
// Get the user name. On Windows 98 and Windows ME, the user 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 user 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

Other Resources

Basic Windows Script Host Tasks


Driving Applications

Windows Script Host
Driving Applications
See Also
DropDown image

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.

CopyCode image Copy Code
// 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:

CopyCode image Copy Code
' 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.

CopyCode image Copy Code
' 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:

CopyCode image Copy Code
// 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

Reference

Exec Method (Windows Script Host)
Run Method (Windows Script Host)

Other Resources

Basic Windows Script Host Tasks


Executing File Management Operations

Windows Script Host
Executing File Management Operations
See Also
DropDown image

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 Folder

See Also

Other Resources

Basic Windows Script Host Tasks


Copying Files and Folders

Windows Script Host
Copying Files and Folders
See Also
DropDown image

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.

CopyCode image Copy Code
// 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 Note

The destination folder must already exist for 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.

CopyCode image Copy Code
// 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

Reference

FileSystemObject Object
CopyFile Method
CopyFolder Method
MoveFolder Method

Other Resources

Executing File Management Operations


Mapping to a Special Folder

Windows Script Host
Mapping to a Special Folder
See Also
DropDown image

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.

Example

CopyCode image Copy Code
// 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

Other Resources

Executing File Management Operations


Managing Shortcuts

Windows Script Host
Managing Shortcuts
See Also
DropDown image

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

Other Resources

Basic Windows Script Host Tasks


Copying a Shortcut

Windows Script Host
Copying a Shortcut
See Also
DropDown image

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.

Example

CopyCode image Copy Code
// 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

Other Resources

Managing Shortcuts


Creating a Shortcut

Windows Script Host
Creating a Shortcut
See Also
DropDown image

Creating shortcuts requires the use of the File Shell object. The following scripts demonstrate the use of the File Shell object to create shortcuts.

Example

CopyCode image Copy Code
// 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 = "app.exe,1";
link.TargetPath = "c:\\blah\\app.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 = "app.exe,1"
link.TargetPath = "c:\blah\app.exe"
link.WindowStyle = 3
link.WorkingDirectory = "c:\blah"
link.Save

See Also

Other Resources

Managing Shortcuts


Deleting a Shortcut

Windows Script Host
Deleting a Shortcut
See Also
DropDown image

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.

Example

CopyCode image Copy Code
// 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

Other Resources

Managing Shortcuts


Moving a Shortcut

Windows Script Host
Moving a Shortcut
See Also
DropDown image

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.

Example

CopyCode image Copy Code
// 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

Other Resources

Managing Shortcuts


Manipulating the System Registry

Windows Script Host
Manipulating the System Registry
See Also
DropDown image

With WSH you can manage the system registry. The following scripts demonstrate some of these capabilities.

Example

CopyCode image Copy Code
// 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

Other Resources

Basic Windows Script Host Tasks


Running Scripts Remotely

Windows Script Host
Running Scripts Remotely
See Also
DropDown image

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).

Example

CopyCode image Copy Code
// 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

Reference

WshRemote Object

Concepts

Setting up Remote WSH

Other Resources

Basic Windows Script Host Tasks


Signing a Script

Windows Script Host
Signing a Script
See Also
DropDown image

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.

Example

CopyCode image Copy Code
// 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

Concepts

Verifying a Script

Other Resources

Basic Windows Script Host Tasks


WSH and Windows Management Instrumentation (WMI)

Windows Script Host
WSH and Windows Management Instrumentation (WMI)
See Also
DropDown image

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.

Example

CopyCode image Copy Code
// 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
Note Note

For more information on WMI, see the WMI SDK at http://msdn.microsoft.comhttp://msdn.microsoft.com.

See Also

Other Resources

Basic Windows Script Host Tasks


WSH Walkthrough

Windows Script Host
WSH Walkthrough
See Also
CollapseAll image DropDown image

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 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 Note

The following code is from the sample included in this documentation. To view the entire sample, see WSH Network Administrator Sample Script.

Expand image Create Variables and Constants

To create the necessary variables and constants

  1. In your text-scripting editor, enter the variables.`

    CopyCode image Copy Code
    Dim FSO
Dim Services
Dim SecDescClass
Dim SecDesc
Dim Trustee
Dim ACE
Dim Share
Dim InParam
Dim 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.

    CopyCode image Copy Code
    Const FolderName = "C:\Public"
Const AdminServer = "\\AdminMachine"
Const ShareName = "Pubs"
Const PrinterShare = "\\CorpPrinters\PrinterShare"

Expand image 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.

    CopyCode image Copy Code
    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.

    CopyCode image Copy Code
    Network.SetDefaultPrinter PrinterShare

Expand image 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.

    CopyCode image Copy Code
    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.

    CopyCode image Copy Code
    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 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, search for WMI overview on MSDN Online.

    CopyCode image Copy Code
    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)

Expand image Next Steps

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.

Expand image See Also

Concepts

Setting up Remote WSH
Running Scripts Remotely

Other Resources

Accessing Networks


WSH Network Administrator Sample Script

Windows Script Host
WSH Network Administrator Sample Script
See Also
DropDown image

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 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 the WMI SDK at (http://msdn.microsoft.com).

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. Establish the necessary security settings on the remote machines.

  2. Copy the AdminScript.vbs script below into your scripting text editor.

  3. Change the constants to reflect your network paths and machine names.

  4. Replace remmachine with the applicable remote machine name and run the script:

    CopyCode image Copy Code
    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

CopyCode image Copy Code
' Remote WSH Admin Sample  AdminScript.vbs
'
' 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.

' 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.

Option Explicit

Dim FSO
Dim Services
Dim SecDescClass
Dim SecDesc
Dim Trustee
Dim ACE
Dim Share
Dim InParam
Dim Network

Const FolderName = "C:\Public"
Const AdminServer = "\\AdminMachine"
Const ShareName = "Pubs"
Const 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

Tasks

WSH Walkthrough

Concepts

Setting up Remote WSH
Running Scripts Remotely

Other Resources

Accessing Networks


Security and Windows Script Host

Windows Script Host
Security and Windows Script Host
DropDown image

Windows Script Host, which is a flexible tool for automating Windows, can also be misused by malicious developers.

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 (Windows Script Host)

Software Restriction Policies

Signature Verification Policy

Verifying a Script

Related Sections

Reference (Windows Script Host)


CryptoAPI Tools

Windows Script Host
CryptoAPI Tools
See Also
DropDown image

The CryptoAPI Tools are used to create and verify digital signatures in *.exe, *.cab, *.dll, *.ocx, and script (*js, *.vbs, and *.wsf) files.

Digital Signatures

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 CryptoAPI Tools, see the CryptoAPI SDK at (http://msdn.microsoft.com).

See Also

Concepts

Signing a Script (Windows Script Host)
Verifying a Script
Signature Verification Policy

Other Resources

Security and Windows Script Host


Signing a Script (Windows Script Host)

Windows Script Host
Signing a Script (Windows Script Host)
See Also
DropDown image

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.

Example

Script signing is programmatically accomplished with the Scripting.Signer object's SignFile method.

CopyCode image Copy Code
<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 Note

In order to sign a script, you must have a valid certificate. Ask your Administrator about your certification policy or contact a commercial certification authority.

See Also

Concepts

Verifying a Script
Signature Verification Policy
CryptoAPI Tools
Signing a Script

Other Resources

Security and Windows Script Host


Software Restriction Policies

Windows Script Host
Software Restriction Policies
See Also
DropDown image

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.

Criteria that Software Restriction Policies Use to Determine Trust Level

  • Any signature information in the script

  • The path from which the script is running

  • File content

See Also

Other Resources

Security and Windows Script Host


Signature Verification Policy

Windows Script Host
Signature Verification Policy
See Also
DropDown image

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:

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

Concepts

Signing a Script (Windows Script Host)
Verifying a Script
CryptoAPI Tools

Other Resources

Security and Windows Script Host


Verifying a Script

Windows Script Host
Verifying a Script
See Also
DropDown image

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.

VerifyFile Method

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 Note

    Although the VerifyFile method programmatically confirms the digital signature, you should always ensure that you really trust the trusted roots in the Trusted Publishers List.

See Also

Concepts

Signing a Script (Windows Script Host)
Signature Verification Policy
CryptoAPI Tools

Other Resources

Security and Windows Script Host


Reference (Windows Script Host)

Windows Script Host
Reference (Windows Script Host)
DropDown image

The following sections provide information about the elements that comprise Window Script Host.

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

Windows Script Host Basics

Learn the basics of WSH.


XML Elements

Windows Script Host
XML Elements
DropDown image

The following sections include information about the 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.

<unnamed> Element

Describes an unnamed argument for the script.

<usage> Element

Allows user to override default usage display.

Related Sections

WSH Reference

List of elements that make up WSH Reference.

WSH Basics

Learn the basics of WSH.


<?job?> Element

Windows Script Host
<?job?> Element
See Also Example
CollapseAll image DropDown image

Specifies attributes for error handling.

<?job error="flag" debug="flag" ?>

Expand image 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.

Expand image 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.

Expand image Example

The following example incorporates two jobs into one .wsf file that uses two different scripting languages.
CopyCode image Copy Code
<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>

Expand image See Also

Reference

<runtime> Element (Windows Script Host)
<named> Element
<description> Element (Windows Script Host)
<example> Element
<object> Element (Windows Script Host)
<package> Element (Windows Script Host)
<resource> Element (Windows Script Host)
<?XML?> Element


<?XML?> Element

Windows Script Host
<?XML?> Element
See Also Example
CollapseAll image DropDown image

Indicates that a file should be parsed as XML.

<?XML version="version" [standalone="DTDflag"] ?>

Expand image 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."

Expand image 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.

Expand image Example

The following example demonstrates the use of the <?XML?> Element:
CopyCode image Copy Code
      <?XML version="1.0" standalone="yes" ?>

Expand image See Also

Reference

<runtime> Element (Windows Script Host)
<named> Element
<description> Element (Windows Script Host)
<example> Element
<object> Element (Windows Script Host)
<package> Element (Windows Script Host)
<resource> Element (Windows Script Host)
<?job?> Element


<description> Element (Windows Script Host)

Windows Script Host
<description> Element (Windows Script Host)
See Also Example
CollapseAll image DropDown image

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>

Expand image 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.

Expand image Example

The following script demonstrates the use of the <description> Element:
CopyCode image Copy Code
<runtime>
    <description>
        This script reboots a server
    </description>
    <!--...etc...-->
</runtime>

Expand image See Also

Reference

ShowUsage Method
<runtime> Element (Windows Script Host)
<named> Element
<unnamed> Element
<example> Element


<example> Element

Windows Script Host
<example> Element
See Also Example
CollapseAll image DropDown image

Provides an example of usage for the job.

<example>
   Example text
</example>

Expand image Remarks

The <example> element is enclosed within the <runtime> element.

Expand image Example

The following script demonstrates the use of the <example> Element:

CopyCode image Copy Code
<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:

CopyCode image Copy Code
This script reboots a server
Usage: reboot.wsf /server:value

Options:
server : Server to run the script on

Example:
reboot.wsf /server:scripting

Expand image See Also

Reference

ShowUsage Method


<job> Element

Windows Script Host
<job> Element
See Also Example
CollapseAll image DropDown image

Marks the beginning and the end of a job within a Windows Script file (*.wsf).

<job [id=JobID]>
    job code
</job>

Expand image Arguments

JobID

Optional. Uniquely identifies the job within the scope of the Windows Script file.

Expand image 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.

Expand image 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.

CopyCode image Copy Code
<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.

CopyCode image Copy Code
cscript myScript.wsf //job:DoneInJS

To run both jobs in myScript.wsf, type the following at the command prompt.

CopyCode image Copy Code
cscript myScript.wsf //job:DoneInVBS //job:DoneInJS

Expand image See Also

Reference

ShowUsage Method
<runtime> Element (Windows Script Host)
<named> Element
<unnamed> Element
<description> Element (Windows Script Host)
<example> Element


<named> Element

Windows Script Host
<named> Element
See Also Example
CollapseAll image DropDown image

Describes a named argument for the script.

<named
      name = namedname
      helpstring = helpstring
      type = "string|boolean|simple"
      required = boolean
/>

Expand image 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.

Expand image 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.

Expand image Example

The following script demonstrates the use of the <named> Element:

CopyCode image Copy Code
<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:

CopyCode image Copy Code
Usage: example.wsf /server:value [/user:value] /enable[+|-] [/verbose]

Options:

server    : Server to access
user      : User account to use on server. Default is current account.
enable    : If true (+), enables the action. A minus(-) disables.
verbose   : If specified, output will be verbose.

Expand image See Also

Reference

ShowUsage Method
<runtime> Element (Windows Script Host)
<unnamed> Element
<description> Element (Windows Script Host)
<example> Element


<object> Element (Windows Script Host)

Windows Script Host
<object> Element (Windows Script Host)
See Also Example
CollapseAll image DropDown image

Defines objects in Windows Script (.wsf) files that can be referenced by a script.

<object id="objID" {classid="clsid:GUID" | progid="progID"} [events="hookevents"] />

Expand image 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

Required unless progID is defined. The class ID (GUID) of the object.

progID

Required unless GUID is defined. Program ID of the object, which can be specified as an alternative to the class ID.

hookevents

Optional. A value (either "true" or "false") that determines if you can hook events from the object. By default, hookevents is false. If the attribute is true, you can connect to any events the object may fire. You must add an event handler for each event that is to be handled.

Expand image 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.

Expand image Example

CopyCode image Copy Code
<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>

Expand image See Also

Reference

<runtime> Element (Windows Script Host)
<named> Element
<description> Element (Windows Script Host)
<example> Element
<package> Element (Windows Script Host)


<package> Element (Windows Script Host)

Windows Script Host
<package> Element (Windows Script Host)
See Also Example
CollapseAll image DropDown image

Encloses multiple job definitions in a Windows Script (.wsf) file.

<package>
      code for one or more jobs
</package>

Expand image Remarks

The <package> element is optional when a .wsf file contains only one job.

Expand image Example

The following example incorporates two jobs into one .wsf file that uses two different scripting languages:
CopyCode image Copy Code
<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>

Expand image See Also

Reference

<runtime> Element (Windows Script Host)
<named> Element
<description> Element (Windows Script Host)
<example> Element
<object> Element (Windows Script Host)


<reference> Element (Windows Script Host)

Windows Script Host
<reference> Element (Windows Script Host)
See Also
CollapseAll image DropDown image

Includes a reference to an external type library.

<reference [object="progID"|guid="typelibGUID"] [version="version"] />

Expand image 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.

Expand image 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.

Expand image See Also

Reference

<runtime> Element (Windows Script Host)
<named> Element
<description> Element (Windows Script Host)
<example> Element
<object> Element (Windows Script Host)
<package> Element (Windows Script Host)


<resource> Element (Windows Script Host)

Windows Script Host
<resource> Element (Windows Script Host)
See Also Example
CollapseAll image DropDown image

Isolates textual or numeric data that should not be hard-coded into a script.

<resource id="resourceID">
      text or number
</resource>

Expand image Arguments

resourceID

Unique identifier for the resource within the script.

Expand image 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.).

Expand image Example

The following code defines a resource (errNonNumeric) and returns its value if the variable upperBound is not numeric.
CopyCode image Copy Code
<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>

Expand image See Also

Reference

<runtime> Element (Windows Script Host)
<named> Element
<description> Element (Windows Script Host)
<example> Element
<object> Element (Windows Script Host)
<package> Element (Windows Script Host)
getResource Method


<runtime> Element (Windows Script Host)

Windows Script Host
<runtime> Element (Windows Script Host)
See Also Example
CollapseAll image DropDown image

Groups together the set of run-time arguments for a script.

<runtime>
        <named attributes etc. />
        <unnamed attributes etc. />
        <example>Example Text</example>

</runtime>

Expand image 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 Note

With version 5.6, the data enclosed 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.

Expand image Example

The following script demonstrates the use of the <runtime> Element:
CopyCode image Copy Code
<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>

Expand image See Also

Reference

ShowUsage Method
<named> Element
<unnamed> Element
<description> Element (Windows Script Host)
<example> Element


<script> Element (Windows Script Host)

Windows Script Host
<script> Element (Windows Script Host)
See Also Example
CollapseAll image DropDown image

Contains script that defines the behavior of a Windows Script (.wsf) file.

<script language="language" [src="strFile"]>
          script here
</script>

Expand image 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.

Expand image 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 Note

Do not include a CDATA section unless you also include the <?XML?> declaration.

Expand image Example

The following example incorporates two jobs into one .wsf file, using two different scripting languages:
CopyCode image Copy Code
<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>

Expand image See Also

Reference

<runtime> Element (Windows Script Host)
<named> Element
<description> Element (Windows Script Host)
<example> Element
<object> Element (Windows Script Host)
<package> Element (Windows Script Host)
<resource> Element (Windows Script Host)
<?XML?> Element


<unnamed> Element

Windows Script Host
<unnamed> Element
See Also Example
CollapseAll image DropDown image

Describes an unnamed argument for the script.

<unnamed
      name       = unnamedname
      helpstring = helpstring
      many       = boolean
      required   = boolean or integer
/>

Expand image 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.

Expand image 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 Note

The name attribute of the unnamed element is just for display purposes.

When setting the required attribute, a Boolean value is converted to an integer; "true" becomes 1 and "false" becomes 0.

Expand image Example

Here are a couple of examples of how the various attributes affect the usage with unnamed elements. First, a simple case:

CopyCode image Copy Code
<job>
<runtime>
<unnamed
  name="filename"
  helpstring="The file to process"
  many="false"
  required="true"
/>
</runtime>
<script language="JScript">
  WScript.Arguments.ShowUsage();
</script>
</job>

This produces the following:

CopyCode image Copy Code
Usage: example.wsf filename

Options:
filename : The file to process

In the next example, change the code as follows, changing required to 3:

CopyCode image Copy Code
<runtime>
<unnamed
  name="filename"
  helpstring="The files to process"
  many="false"
  required="3"
/>
</runtime>

Your output changes to:

CopyCode image Copy Code
Usage: example.wsf filename1 filename2 filename3

Options:
filename : The files to process

The many argument displays ellipses to indicate you can enter more files than indicated. In this final code example, change your code as follows:

CopyCode image Copy Code
<runtime>
<unnamed
  name="filename"
  helpstring="The file(s) to process"
  many="true"
  required="1"
/>
</runtime>

The output changes to:

CopyCode image Copy Code
Usage: example.wsf filename1 [filename2...]

Options:
filename: The file to process.

Expand image See Also

Reference

ShowUsage Method
<runtime> Element (Windows Script Host)
<named> Element
<description> Element (Windows Script Host)
<example> Element


<usage> Element

Windows Script Host
<usage> Element
See Also Example
CollapseAll image DropDown image

Allows user to override default usage display.

<usage>
    This section describes the script
</usage>

Expand image 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 Note

The <usage> element should always be enclosed by a <runtime> element.

Expand image Example

The following script demonstrates the use of the <usage> element:

CopyCode image Copy Code
<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>

When this script is run, it produces the following:

CopyCode image Copy Code
Your usage text goes here.

Expand image See Also

Reference

<runtime> Element (Windows Script Host)
<named> Element
<description> Element (Windows Script Host)
<example> Element
<package> Element (Windows Script Host)
<resource> Element (Windows Script Host)
<?XML?> Element


Objects (Windows Script Host)

Windows Script Host
Objects (Windows Script Host)
DropDown image

The following sections include information about the Windows Script Host objects.

In This Section

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.

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.

Windows Script Host Basics

Learn the basics of WSH.


Scripting.Signer Object

Windows Script Host
Scripting.Signer Object
See Also Example
CollapseAll image DropDown image

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.

Expand image Remarks

The Scripting.Signer object requires a valid certificate.

Expand image Example

The following JScript code shows the Scripting.Signer object digitally signing a script.
CopyCode image Copy Code
<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>

Expand image Methods

Sign Method | SignFile Method | Verify Method | VerifyFile Method

Expand image See Also

Concepts

Signing a Script


Scripting.Signer Object Methods

Windows Script Host
Scripting.Signer Object Methods
DropDown image

The following sections include information about the methods of the Scripting.Signer object.

In This Section

Sign Method

SignFile Method

Verify Method

VerifyFile Method


WScript Object

Windows Script Host
WScript Object
See Also Example
CollapseAll image DropDown image

Provides access to root object for the Windows Script Host object model.

Expand image 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).

Expand image 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.

Expand image Properties

Arguments Property | BuildVersion Property | FullName Property (WScript Object) | Interactive Property | Name Property | Path Property | ScriptFullName Property | ScriptName Property | StdErr Property | StdIn Property | StdOut Property | Version Property

Expand image Methods

ConnectObject Method | CreateObject Method | DisconnectObject Method | Echo Method | GetObject Method | Quit Method | Sleep Method

Expand image See Also

Reference

WshShell Object
WshNetwork Object

Concepts

Running Your Scripts


WScript Object Properties and Methods

Windows Script Host
WScript Object Properties and Methods
DropDown image

The following sections include information about the properties and methods of the WScript object.

In This Section

Arguments Property

BuildVersion Property

FullName Property

Interactive Property

Name Property

Path Property

ScriptFullName Property

ScriptName Property

StdErr Property

StdIn Property

StdOut Property

Version Property

ConnectObject Method

CreateObject Method

DisconnectObject Method

Echo Method

GetObject Method

Quit Method

Sleep Method


WshArguments Object

Windows Script Host
WshArguments Object
See Also Example
CollapseAll image DropDown image

Provides access to the entire collection of command-line parameters — in the order in which they were originally entered.

Expand image Remarks

Wsh Arguments Object graphic

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.

Expand image Example

The following code displays the command-line parameters in the WshArguments object.

Visual Basic Script CopyCode image Copy Code
Set objArgs = WScript.Arguments
For I = 0 to objArgs.Count - 1
   WScript.Echo objArgs(I)
Next
JScript CopyCode image Copy Code
objArgs = WScript.Arguments;
for (i = 0; i < objArgs.length; i++)
{
   WScript.Echo(objArgs(i));
}

Expand image Properties

Item Property | Length Property | Named Property | Unnamed Property

Expand image Methods

Count Method | ShowUsage Method

Expand image See Also

Reference

Arguments Property (WScript Object)
WshNamed Object
WshUnnamed Object


WshArguments Object Properties and Methods

Windows Script Host
WshArguments Object Properties and Methods
DropDown image

The following sections include information about the properties and methods of the WshArguments object.

In This Section

Item Property

Length Property

Named Property

Unnamed Property

Count Method

ShowUsage Method


WshController Object

Windows Script Host
WshController Object
See Also Example
CollapseAll image DropDown image

Provides access to the CreateScript() method (for creating a remote script process).

Expand image Example

Child Wsh Controller Object graphic

The following example uses a controller object to create a WshRemote object.

Expand image Code

Visual Basic Script CopyCode image Copy Code
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 CopyCode image Copy Code
var Controller = WScript.CreateObject("WSHController");
var RemoteScript = Controller.CreateScript("test.js", "remoteserver");
RemoteScript.Execute();

while (RemoteScript.Status != 2) {
    WScript.Sleep(100);
}

Expand image Methods

CreateScript Method

Expand image See Also

Reference

CreateObject Method


WshController Object Methods

Windows Script Host
WshController Object Methods
DropDown image

The following sections include information about the methods of the WshController object.

In This Section

CreateScript Method


WshEnvironment Object

Windows Script Host
WshEnvironment Object
See Also Example
CollapseAll image DropDown image

Provides access to the collection of Windows environment variables.

Expand image Remarks

Wsh Environment Object graphic

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.

Expand image Example

The following code displays an environment variable.

Visual Basic Script CopyCode image Copy Code
Set WshShell = WScript.CreateObject("WScript.Shell")
Set WshSysEnv = WshShell.Environment("SYSTEM")
WScript.Echo WshSysEnv("NUMBER_OF_PROCESSORS")
JScript CopyCode image Copy Code
var WshShell = WScript.CreateObject("WScript.Shell");
var WshSysEnv = WshShell.Environment("SYSTEM");
WScript.Echo(WshSysEnv("NUMBER_OF_PROCESSORS"));

Expand image Properties

Item Property | Length Property (WshEnvironment object)

Expand image Methods

Count Method | Remove Method

Expand image See Also

Reference

Environment Property


WshEnvironment Object Properties and Methods

Windows Script Host
WshEnvironment Object Properties and Methods
DropDown image

The following sections include information about the properties methods of the WshEnvironment object.

In This Section

Item Property

Length Property

Count Method

Remove Method


WshNamed Object

Windows Script Host
WshNamed Object
See Also Example
CollapseAll image DropDown image

Provides access to the named arguments from the command line.

Expand image Remarks

Wsh Named Object graphic

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.

Expand image Example

The following code displays the number of named and unnamed command-line arguments.
CopyCode image Copy Code
<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>

Expand image Properties

Item Property | Length Property

Expand image Methods

Count Method | Exists Method

Expand image See Also

Reference

WshArguments Object
WshUnnamed Object


WshNamed Object Properties and Methods

Windows Script Host
WshNamed Object Properties and Methods
DropDown image

The following sections include information about the properties and methods of the WshNamed object.

In This Section

Item Property

Length Property

Count Method

Exists Method


WshNetwork Object

Windows Script Host
WshNetwork Object
See Also Example
CollapseAll image DropDown image

Provides access to the shared resources on the network to which your computer is connected.

Expand image Remarks

Wsh Network Object graphic

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.

Expand image Example

The following example demonstrates displaying the domain name, computer name, and user name for the current computer system using the WshNetwork object.
CopyCode image Copy Code
<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>

Expand image Properties

ComputerName Property | UserDomain Property | UserName Property

Expand image Methods

AddWindowsPrinterConnection Method | AddPrinterConnection Method | EnumNetworkDrives Method | EnumPrinterConnections Method | MapNetworkDrive Method | RemoveNetworkDrive Method | RemovePrinterConnection Method | SetDefaultPrinter Method

Expand image See Also

Reference

WScript Object

Concepts

Running Your Scripts


WshNetwork Object Properties and Methods

Windows Script Host
WshNetwork Object Properties and Methods
DropDown image

The following sections include information about the properties methods of the WshNetwork object.

In This Section

ComputerName Property

UserDomain Property

UserName Property

AddPrinterConnection Method

AddWindowsPrinterConnection Method

EnumNetworkDrives Method

EnumPrinterConnections Method

MapNetworkDrive Method

RemoveNetworkDrive Method

RemovePrinterConnection Method

SetDefaultPrinter Method


WshRemote Object

Windows Script Host
WshRemote Object
See Also Example
CollapseAll image DropDown image

Provides access to the remote script process.

Expand image Remarks

Wsh Remote Object graphic

The WshRemote object allows you to remotely administer computer systems on a computer network. It represents an instance of a WSH script, that is, 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.

Note Note

In WSH version 5.6.6626, which ships with Internet Explorer 6 and Windows XP, a remote script is copied to memory in the remote machine and run from there. In later versions of WSH, such as the one provided by Windows Server 2003, a remote script is copied to the temporary directory of the account that accesses the remote machine. The script is run with the security settings for the remote machine and the temporary directory.

Expand image Example

The following example demonstrates how the WshRemote object is used to start a remote script.

Expand image Code

Visual Basic Script CopyCode image Copy Code
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 CopyCode image Copy Code
var Controller = WScript.CreateObject("WSHController");
var RemoteScript = Controller.CreateScript("test.js", "remoteserver");
RemoteScript.Execute();

while (RemoteScript.Status != 2) {
    WScript.Sleep(100);
}

Expand image Properties

Error Property | Status Property

Expand image Methods

Execute Method | Terminate Method

Expand image Events

End Event | Error Event | Start Event

Expand image See Also

Reference

WshController Object


WshRemote Object Properties, Methods, and Events

Windows Script Host
WshRemote Object Properties, Methods, and Events
DropDown image

The following sections include information about the properties, methods, and events of the WshRemote object.

In This Section

Error Property

Status Property

Execute Method

Terminate Method

End Event

Error Event

Start Event


WshRemoteError Object

Windows Script Host
WshRemoteError Object
See Also Example
CollapseAll image DropDown image

Provides access to the error information available when a remote script (a WshRemote object) terminates as a result of a script error.

Expand image Remarks

Wsh Remote Error Object graphic

The WshRemoteError object is returned by the Error property of the WshRemote object.

Expand image 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.

Visual Basic Script CopyCode image Copy Code
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 CopyCode image Copy Code
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);
}

Expand image Properties

Description Property | Line Property | Character Property | Number Property | SourceText Property | Source Property

Expand image See Also

Reference

WshRemote Object


WshRemoteError Object Properties

Windows Script Host
WshRemoteError Object Properties
DropDown image

The following sections include information about the properties of the WshRemoteError object.

In This Section

Character Property

Description Property

Line Property

Number Property

SourceText Property

Source Property


WshScriptExec Object

Windows Script Host
WshScriptExec Object
See Also Example
CollapseAll image DropDown image

Provides status information about a script run with Exec along with access to the StdIn, StdOut, and StdErr streams.

Expand image Remarks

Wsh ScriptExecObject graphic

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.

Expand image Example

The following code runs calc.exe and echoes the final status to the screen.

Visual Basic Script CopyCode image Copy Code
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 CopyCode image Copy Code
var WshShell = new ActiveXObject("WScript.Shell");
var oExec = WshShell.Exec("calc");

while (oExec.Status == 0)
{
     WScript.Sleep(100);
}

WScript.Echo(oExec.Status);

Expand image Properties

ExitCode Property | ProcessID Property | Status Property | StdErr Property | StdIn Property | StdOut Property

Expand image Methods

Terminate Method

Expand image See Also

Reference

WScript Object
Exec Method (Windows Script Host)


WshScriptExec Object Properties and Methods

Windows Script Host
WshScriptExec Object Properties and Methods
DropDown image

The following sections include information about the properties and methods of the WshScriptExec object.

In This Section

ExitCode Property

ProcessID Property

Status Property

StdErr Property

StdIn Property

StdOut Property

Terminate Method


WshShell Object

Windows Script Host
WshShell Object
See Also Example
CollapseAll image DropDown image

Provides access to the native Windows shell.

Expand image Remarks

Wsh Shell Object graphic

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).

Expand image Example

The following example demonstrates the creation of a shortcut to the script being run and a URL shortcut to www.microsoft.com:
CopyCode image Copy Code
<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>

Expand image Properties

CurrentDirectory Property | Environment Property | SpecialFolders Property

Expand image Methods

AppActivate Method | CreateShortcut Method | Exec Method | ExpandEnvironmentStrings Method | LogEvent Method | Popup Method | RegDelete Method | RegRead Method | RegWrite Method | Run Method | SendKeys Method

Expand image See Also

Concepts

Running Your Scripts


WshShellObject Properties and Methods

Windows Script Host
WshShellObject Properties and Methods
DropDown image

The following sections include information about the properties and methods of the WshShellObject object.

In This Section

CurrentDirectory Property

Environment Property

SpecialFolders Property

AppActivate Method

CreateShortcut Method

Exec Method

ExpandEnvironmentStrings Method

LogEvent Method

Popup Method

RegDelete Method

RegRead Method

RegWrite Method

Run Method

SendKeys Method


WshShortcut Object

Windows Script Host
WshShortcut Object
See Also Example
CollapseAll image DropDown image

Allows you to create a shortcut programmatically.

Expand image Example

Wsh Shortcut Object graphic

The following example demonstrates the creation of a shortcut to the script being run:
CopyCode image Copy Code
<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>

Expand image Properties

Arguments Property | Description Property | FullName Property (WshShortcut Object) | Hotkey Property | IconLocation Property | RelativePath Property | TargetPath Property | WindowStyle Property | WorkingDirectory Property

Expand image Methods

Save Method

Expand image See Also

Reference

CreateShortcut Method

Concepts

Running Your Scripts


WshShortcut Object Properties and Methods

Windows Script Host
WshShortcut Object Properties and Methods
DropDown image

The following sections include information about the properties and methods of the WshShortcut object.

In This Section

Arguments Property

Description Property

FullName Property

Hotkey Property

IconLocation Property

RelativePath Property

TargetPath Property

WindowStyle Property

WorkingDirectory Property

Save Method


WshSpecialFolders Object

Windows Script Host
WshSpecialFolders Object
See Also Example
CollapseAll image DropDown image

Provides access to the collection of Windows special folders.

Expand image Remarks

Wsh Special Folders Object graphic

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

Expand image Example

The following script demonstrates the use of the WshSpecialFolders Object:
CopyCode image Copy Code
<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>

Expand image Properties

Item Property | Length Property

Expand image Methods

Count Method

Expand image See Also

Reference

SpecialFolders Property

Concepts

Running Your Scripts


WshSpecialFolders Object Properties and Methods

Windows Script Host
WshSpecialFolders Object Properties and Methods
DropDown image

The following sections include information about the properties and methods of the WshSpecialFolders object.

In This Section

Item Property

Length Property

Count Method


WshUnnamed Object

Windows Script Host
WshUnnamed Object
See Also Example
CollapseAll image DropDown image

Provides access to the unnamed arguments from the command line.

Expand image Remarks

Wsh Unnamed Object graphic

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.

Expand image Example

The following code displays the number of named and unnamed command-line arguments.
CopyCode image Copy Code
<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>

Expand image Properties

Item Property | Length Property

Expand image Methods

Count Method

Expand image See Also

Reference

WshArguments Object
WshNamed Object


WshUnnamed Object Properties and Methods

Windows Script Host
WshUnnamed Object Properties and Methods
DropDown image

The following sections include information about the properties and methods of the WshUnnamed object.

In This Section

Item Property

Length Property

Count Method


WshUrlShortcut Object

Windows Script Host
WshUrlShortcut Object
See Also Example
CollapseAll image DropDown image

Allows you to create a shortcut to an Internet resource programmatically.

Expand image Remarks

Wsh URL shortcut Object graphic

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")).

Expand image Example

The following example demonstrates the creation of a URL shortcut to www.microsoft.com.
CopyCode image Copy Code
<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>

Expand image Properties

FullName Property (WshUrlShortcut Object) | TargetPath Property

Expand image Methods

Save Method

Expand image See Also

Reference

CreateShortcut Method

Concepts

Running Your Scripts


WshUrlShortcut Object Properties and Methods

Windows Script Host
WshUrlShortcut Object Properties and Methods
DropDown image

The following sections include information about the properties and methods of the WshUrlShortcut object.

In This Section

FullName Property

TargetPath Property

Save Method


Properties (Windows Script Host)

Windows Script Host
Properties (Windows Script Host)
DropDown image

The following sections include information about the properties of Windows Script Host.

In This Section

Arguments Property (WScript Object)

Returns the WshArguments object.

Arguments Property (Shortcut Object)

Sets the arguments for a shortcut, or identifies a shortcut's arguments.

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.

BuildVersion Property

Returns the Windows Script Host build version number.

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.

Description Property (WshRemoteError)

Contains a brief description of the error that caused the remote script to terminate.

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(WScript Object)

Returns a fully qualified path name.

FullName Property (WshShortcut Object)

Returns the fully qualified path of the shortcut object's target.

FullName Property (WshUrlShortcut Object)

Returns the fully qualified path of the shortcut object's target.

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 (WshArguments Object)

Returns the number of items in a collection.

length Property (WshEnvironment Object)

Returns the number of Windows environment variables on the local computer system (the number of items in an Environment collection).

length Property (WshSpecialFolders Object)

Returns the number of Windows special folders on the local computer system (the number of items in a SpecialFolders collection).

Line Property (WScript)

Returns the current line number in an input stream.

Line Property (WshRemoteError)

Identifies the line in a script that contains an error-causing statement.

Name Property (WScript Object)

Returns the friendly name of the WScript object (the host executable file).

Named Property

Returns the WshNamed object (a collection of named arguments).

Number Property

Reports the error number representing a script error.

Path Property

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.

RelativePath Property

Assigns a relative path to a shortcut, or identifies the relative path of a shortcut.

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 determine the path to the executable file pointed to by a shortcut.

Unnamed Property

Returns the WshUnnamed object (a collection of unnamed arguments).

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.

Windows Script Host Basics

Learn the basics of WSH.


Arguments Property (WScript Object)

Windows Script Host
Arguments Property (WScript Object)
See Also Example
CollapseAll image DropDown image

Returns the WshArguments object (a collection of arguments).

object.Arguments

Expand image Arguments

object

WScript object.

Expand image Remarks

The Arguments property contains the WshArguments object (a collection of arguments). Use a zero-based index to retrieve individual arguments from this collection.

Expand image Example

The following code samples display the entire set of command-line parameters associated with a script.

Visual Basic Script CopyCode image Copy Code
Set objArgs = WScript.Arguments
For I = 0 to objArgs.Count - 1
   WScript.Echo objArgs(I)
Next
JScript CopyCode image Copy Code
objArgs = WScript.Arguments;
for (i = 0; i < objArgs.length; i++)
{
   WScript.Echo(objArgs(i));
}

Applies To:

WScript Object

Expand image See Also

Reference

WshArguments Object
WshNamed Object
WshUnnamed Object


Arguments Property (Shortcut Object)

Windows Script Host
Arguments Property (Shortcut Object)
See Also Example
CollapseAll image DropDown image

Sets the arguments for a shortcut, or identifies a shortcut's arguments.

object.Arguments

Expand image Arguments

object

WshShortcut object.

Expand image Remarks

The Arguments property returns a string.

Expand image Example

The following code sets the Arguments property.

Visual Basic Script CopyCode image Copy Code
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 CopyCode image Copy Code
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();

Applies To:

WshShortcut Object

Expand image See Also

Reference

WshShell Object
CreateShortcut Method


AtEndOfLine Property (Windows Script Host)

Windows Script Host
AtEndOfLine Property (Windows Script Host)
See Also Example
CollapseAll image DropDown image

Returns a Boolean value indicating whether the end of a line in an input stream has been reached.

object.AtEndOfLine

Expand image Arguments

object

StdIn text stream object.

Expand image 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.

Expand image 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.

Visual Basic Script CopyCode image Copy Code
Dim Input
Input = ""

Do While Not WScript.StdIn.AtEndOfLine
   Input = Input & WScript.StdIn.Read(1)
Loop
WScript.Echo Input
JScript CopyCode image Copy Code
var input = "";
while (!WScript.StdIn.AtEndOfLine)
{
   input += WScript.StdIn.Read(1);
}
WScript.Echo(input);

Applies To:

StdIn Property (WScript)

Expand image See Also

Reference

TextStream Object

Other Resources

Error Messages (Windows Script Host)


AtEndOfStream Property (Windows Script Host)

Windows Script Host
AtEndOfStream Property (Windows Script Host)
See Also Example
CollapseAll image DropDown image

Returns a Boolean value indicating whether the end of an input stream has been reached.

object.AtEndOfStream

Expand image Arguments

object

StdIn text stream object.

Expand image 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.

Expand image 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.

Visual Basic Script CopyCode image Copy Code
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 CopyCode image Copy Code
var stdin = WScript.StdIn;
var stdout = WScript.StdOut;
var str1, str2 = "";
var i;
for (i = 0; i < 5; i++)
     stdin.SkipLine();
i = 0;
while (!stdin.AtEndOfStream)
{
     if (i++ >= 2)
     {
          stdout.WriteLine(str1);
     }
     str1 = str2;
     str2 = stdin.ReadLine();
}

Applies To:

StdIn Property (WScript)

Expand image See Also

Reference

TextStream Object

Other Resources

Error Messages (Windows Script Host)


BuildVersion Property

Windows Script Host
BuildVersion Property
See Also Example
CollapseAll image DropDown image

Returns the Windows Script Host build version number.

Object.BuildVersion

Parameters

Object

WScript object.

Expand image 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.

Applies To: WScript Object

Expand image 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.
CopyCode image Copy Code
WScript.Echo WScript.Version & "." & WScript.BuildVersion;

Expand image See Also

Reference

Version Property (Windows Script Host)


Character Property

Windows Script Host
Character Property
See Also Example
CollapseAll image DropDown image

Reports the specific character in a line of code that contains an error.

Object.Character

Expand image Arguments

Object

WshRemoteError object.

Expand image 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).

Expand image Example

The following JScript code demonstrates how the WshRemoteError object exposes the character in the line of code that contained the error.

Visual Basic Script CopyCode image Copy Code
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 CopyCode image Copy Code
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);
}

Applies To:

WshRemoteError Object

Expand image See Also

Reference

WshRemote Object
Line Property (WshRemoteError)
Description Property (WshRemoteError)
SourceText Property
Number Property (Windows Script Host)
Source Property (Windows Script Host)


Column Property (Windows Script Host)

Windows Script Host
Column Property (Windows Script Host)
See Also Example
CollapseAll image DropDown image

Returns the column number of the current character position in an input stream.

object.Column

Expand image Arguments

object

StdIn text stream object.

Expand image 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.

Expand image 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.

Visual Basic Script CopyCode image Copy Code
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 CopyCode image Copy Code
var input = "";
while (!WScript.StdIn.AtEndOfLine)
{
   input += WScript.StdIn.Read(1);
   if ((WScript.StdIn.Column - 1) % 20 == 0)
   input += "\n";
}
WScript.Echo(input);

Applies To:

StdIn Property (WScript)

Expand image See Also

Reference

TextStream Object

Other Resources

Error Messages (Windows Script Host)


ComputerName Property

Windows Script Host
ComputerName Property
See Also Example
CollapseAll image DropDown image

Returns the name of the computer system.

object.ComputerName

Expand image Arguments

object

WshNetwork object.

Expand image Remarks

The ComputerName property contains a string value indicating the name of the computer system.

Applies To:

WshNetwork Object

Expand image Example

The following example demonstrates the use of the ComputerName property.
CopyCode image Copy Code
<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>

Expand image See Also

Concepts

Running Your Scripts


CurrentDirectory Property

Windows Script Host
CurrentDirectory Property
See Also Example
CollapseAll image DropDown image

Retrieves or changes the current active directory.

object.CurrentDirectory

Expand image Arguments

object

WshShell object.

Expand image Remarks

The CurrentDirectory returns a string that contains the fully qualified path of the current working directory of the active process.

Expand image Example

The following code displays the current active directory.

Visual Basic Script CopyCode image Copy Code
Dim WshShell
Set WshShell = WScript.CreateObject("WScript.Shell")
WScript.Echo WshShell.CurrentDirectory
JScript CopyCode image Copy Code
var WshShell = WScript.CreateObject ("WScript.Shell");
WScript.Echo (WshShell.CurrentDirectory);

Applies To:

WshShell Object

Expand image See Also

Reference

Environment Property


Description Property (Windows Script Host)

Windows Script Host
Description Property (Windows Script Host)
See Also Example
CollapseAll image DropDown image

Returns a shortcut's description.

object.Description

Expand image Arguments

object

WshShortcut object.

Expand image Remarks

The Description property contains a string value describing a shortcut.

Applies To:

WshShortcut Object

Expand image Example

The following example demonstrates the use of the Description Property.
CopyCode image Copy Code
<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>

Expand image See Also

Concepts

Running Your Scripts


Description Property (WshRemoteError)

Windows Script Host
Description Property (WshRemoteError)
See Also Example
CollapseAll image DropDown image

Contains a brief description of the error that caused the remote script to terminate.

Object.Description

Expand image Arguments

Object

WshRemoteError object.

Expand image Remarks

The Description property returns a string.

If an error description is not available, the Description property returns an empty string.

Expand image Example

The following JScript code demonstrates how the WshRemoteError object exposes the description of the error.

Visual Basic Script CopyCode image Copy Code
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 CopyCode image Copy Code
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);
}

Applies To:

WshRemoteError Object

Expand image See Also

Reference

WshRemote Object
Line Property (WshRemoteError)
Character Property
SourceText Property
Number Property (Windows Script Host)
Source Property (Windows Script Host)


Environment Property

Windows Script Host
Environment Property
See Also Example
CollapseAll image DropDown image

Returns the WshEnvironment object (a collection of environment variables).

object.Environment ([strType])

Expand image Arguments

object

WshShell object.

strType

Optional. Specifies the location of the environment variable.

Expand image 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 Note

For Windows95/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 Note

None of the following variables are available from the Volatile type.

Name | Description | System | User | Process (NT/ 2000) | Process (98/ME)
NUMBER_OF_PROCESSORS | Number of processors running on the machine. | X | - | X | -
PROCESSOR_ARCHITECTURE | Processor type of the user's workstation. | X | - | X | -
PROCESSOR_IDENTIFIER | Processor ID of the user's workstation. | X | - | X | -
PROCESSOR_LEVEL | Processor level of the user's workstation. | X | - | X | -
PROCESSOR_REVISION | Processor version of the user's workstation. | X | - | X | -
OS | Operating system on the user's workstation. | X | - | X | -
COMSPEC | Executable file for the command prompt (typically cmd.exe). | X | - | X | X
HOMEDRIVE | Primary local drive (typically the C drive). | - | - | X | -
HOMEPATH | Default directory for users (typically \users\default in Windows 2000). | - | - | X | -
PATH | PATH environment variable. | X | X | X | X
PATHEXT | Extensions for executable files (typically .com, .exe, .bat, or .cmd). | X | - | X | -
PROMPT | Command prompt (typically $P$G). | - | - | X | X
SYSTEMDRIVE | Local drive on which the system directory resides (typically c:\). | - | - | X | -
SYSTEMROOT | System directory (for example, c:\winnt). This is the same as WINDIR. | - | - | X | -
WINDIR | System directory (for example, c:\winnt). This is the same as SYSTEMROOT. | X | - | X | X
TEMP | Directory for storing temporary files (for example, c:\temp). | - | X | X | X
TMP | Directory for storing temporary files (for example, c:\temp). | - | X | X | X

Expand image Example

The following code retrieves the system environment variable NUMBER_OF_PROCESSORS.

Visual Basic Script CopyCode image Copy Code
Set WshShell = WScript.CreateObject("WScript.Shell")
Set WshSysEnv = WshShell.Environment("SYSTEM")
WScript.Echo WshSysEnv("NUMBER_OF_PROCESSORS")
JScript CopyCode image Copy Code
var WshShell = WScript.CreateObject("WScript.Shell");
var WshSysEnv = WshShell.Environment("SYSTEM");
WScript.Echo(WshSysEnv("NUMBER_OF_PROCESSORS"));

Applies To:

WshShell Object

Expand image See Also

Reference

WshEnvironment Object


Error Property (WshRemote)

Windows Script Host
Error Property (WshRemote)
See Also Example
CollapseAll image DropDown image

Exposes the WshRemoteError object, which holds information about the error that caused the remote script to terminate prematurely.

Object.Error

Expand image Arguments

Object

WshRemote object.

Expand image Remarks

The Error property returns a WshRemoteError object.

Expand image 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.

Visual Basic Script CopyCode image Copy Code
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 CopyCode image Copy Code
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);
}

Applies To:

WshRemote Object

Expand image See Also

Reference

WshController Object
WshRemoteError Object
Status Property (WshRemote)
Execute Method (Windows Script Host)
Terminate Method (WshScriptExec)
Start Event
End Event
Error Event


ExitCode Property

Windows Script Host
ExitCode Property
See Also Example
CollapseAll image DropDown image

Returns the exit code set by a script or program run using the Exec() method.

Object.ExitCode

Parameters

Object

WshScriptExec Object

Expand image 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.

Expand image Example

The following code shows an example of the ExitCode property.

Visual Basic Script CopyCode image Copy Code
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 CopyCode image Copy Code
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);

Applies To:

WshScriptExec Object

Expand image See Also

Reference

Exec Method (Windows Script Host)


FullName Property (WScript Object)

Windows Script Host
FullName Property (WScript Object)
See Also Example
CollapseAll image DropDown image

Returns the fully qualified path of the host executable (CScript.exe or WScript.exe).

object.FullName

Expand image Arguments

object

WScript object.

Expand image Remarks

The FullName property is a read-only string representing the fully qualified path of the host executable.

Expand image Example

The following JScript code uses the FullName property:

CopyCode image Copy Code
WScript.Echo (WScript.FullName);

produces the following output.

CopyCode image Copy Code
C:\WINNT\System32\cscript.exe

Applies To:

WScript Object

Expand image See Also

Reference

Path Property (Windows Script Host)
WshShortcut Object
WshUrlShortcut Object


FullName Property (WshShortcut Object)

Windows Script Host
FullName Property (WshShortcut Object)
See Also Example
CollapseAll image DropDown image

Returns the fully qualified path of the shortcut object's target.

object.FullName

Expand image Arguments

object

WshShortcut object.

Expand image Remarks

The FullName property contains a read-only string value indicating the fully qualified path to the shortcut's target.

Expand image Example

The following code retrieves the fully qualified path of a shortcut.

Visual Basic Script CopyCode image Copy Code
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 CopyCode image Copy Code
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);

Applies To:

WshShortcut Object

Expand image See Also

Reference

Path Property (Windows Script Host)
WScript Object
WshShortcut Object
WshUrlShortcut Object


FullName Property (WshUrlShortcut Object)

Windows Script Host
FullName Property (WshUrlShortcut Object)
See Also Example
CollapseAll image DropDown image

Returns the fully qualified path of the shortcut object's target.

object.FullName

Expand image Arguments

object

WshUrlShortcut object.

Expand image Remarks

String. Read-only.

The FullName property is a read-only string representing the fully qualified path to the shortcut's target.

Expand image Example

The following code retrieves the fully qualified path of a URL shortcut.

Visual Basic Script CopyCode image Copy Code
set oUrlLink = WshShell.CreateShortcut(strDesktop & "\Microsoft Web Site.url")
oUrlLink.TargetPath = "http://www.microsoft.com"
oUrlLink.Save
WScript.Echo oUrlLink.FullName
JScript CopyCode image Copy Code
var oUrlLink = WshShell.CreateShortcut(strDesktop + "\\Microsoft Web Site.url");
oUrlLink.TargetPath = "http://www.microsoft.com";
oUrlLink.Save();
WScript.Echo (oUrlLink.FullName);

Applies To:

WshUrlShortcut Object

Expand image See Also

Reference

Path Property (Windows Script Host)
WScript Object
WshShortcut Object


Hotkey Property

Windows Script Host
Hotkey Property
See Also Example
CollapseAll image DropDown image

Assigns a key-combination to a shortcut, or identifies the key-combination assigned to a shortcut.

object.Hotkey = strHotkey

Expand image Arguments

object

WshShortcut object.

strHotkey

A string representing the key-combination to assign to the shortcut.

The syntax of strHotkey is:

CopyCode image Copy Code
[KeyModifier]KeyName
KeyModifier

Can be any one of the following: ALT+, CTRL+, SHIFT+, EXT+.

Note 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.

Expand image 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 Note

    Another name for a hotkey is a Keyboard Shortcut.

In Windows 2000, valid Hotkeys always begin with CTRL + ALT.

Applies To:

WshShortcut Object

Expand image Example

The following example demonstrates the use of the HotKey property.
CopyCode image Copy Code
<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>

Expand image See Also

Reference

WshSpecialFolders Object

Concepts

Running Your Scripts
Running Your Scripts


IconLocation Property

Windows Script Host
IconLocation Property
See Also Example
CollapseAll image DropDown image

Assigns an icon to a shortcut, or identifies the icon assigned to a shortcut.

object.IconLocation = strIconLocation

Expand image 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.

Expand image Remarks

String.

Applies To:

WshShortcut Object

Expand image Example

The following example demonstrates the use of the IconLocation property.
CopyCode image Copy Code
<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>

Expand image See Also

Concepts

Running Your Scripts


Interactive Property

Windows Script Host
Interactive Property
See Also Example
CollapseAll image DropDown image

Sets the script mode, or identifies the script mode.

object.Interactive

Expand image Arguments

object

WScript object.

Expand image 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).

Expand image Example

The following JScript code displays the script mode.

CopyCode image Copy Code
WScript.Echo WScript.Interactive;

The following JScript code sets the script mode to batch.

CopyCode image Copy Code
WScript.Interactive = false;

Applies To:

WScript Object

Expand image See Also

Reference

Arguments Property (WScript Object)


Item Property (Windows Script Host)

Windows Script Host
Item Property (Windows Script Host)
See Also Example
CollapseAll image DropDown image

Exposes a specified item from a collection.

Object.Item(natIndex)

Expand image Arguments

Object

The result of the EnumNetworkDrive or EnumPrinterConnections methods, or the object returned by the Environment or SpecialFolders properties.

natIndex

Item to retrieve.

Expand image 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.

Applies To:

WshArguments Object| WshEnvironment Object| WshSpecialFolders Object

Folder | Windows version
AllUsersDesktop | Windows 2000
AllUsersStartMenu | Windows 2000
AllUsersPrograms | Windows 2000
AllUsersStartup | Windows 2000
Desktop | Windows 98/ME, Windows 2000
Favorites | Windows 98/ME, Windows 2000
Fonts | Windows 98/ME, Windows 2000
My Documents | Windows 98/ME, Windows 2000
NetHood | Windows 98/ME, Windows 2000
PrintHood | Windows 98/ME, Windows 2000
Programs | Windows 98/ME, Windows 2000
Recent | Windows 98/ME, Windows 2000
SendTo | Windows 98/ME, Windows 2000
Start Menu | Windows 98/ME, Windows 2000
StartupB | Windows 2000
Templates | Windows 2000

Expand image Example

The following code displays network mapping information for the drives and printers.
CopyCode image Copy Code
<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>

Expand image See Also

Reference

EnumNetworkDrives Method
EnumPrinterConnections Method
Environment Property
SpecialFolders Property


Item Property (WshNamed)

Windows Script Host
Item Property (WshNamed)
See Also Example
CollapseAll image DropDown image

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.

Expand image 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.

Applies To:

WshNamed Object

Expand image Example

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.
CopyCode image Copy Code
myScript.vbs /c:arg1 /d:arg2

If the following code is executed inside the script, then the output is:

arg1

arg2
CopyCode image Copy Code
WScript.Echo WScript.Arguments.Named.Item("c")
WScript.Echo WScript.Arguments.Named.Item("d")

Expand image See Also

Reference

WshUnnamed Object
Count Method (Windows Script Host)
Item Property
Exists Method (Windows Script Host)


Item Property (WshUnnamed)

Windows Script Host
Item Property (WshUnnamed)
See Also Example
CollapseAll image DropDown image

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.

Expand image 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.

Expand image 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.

CopyCode image Copy Code
myScript.vbs arg1 arg2

When the following code is executed inside the script:

CopyCode image Copy Code
WScript.Echo WScript.Arguments.Unnamed.Item(0)
WScript.Echo WScript.Arguments.Unnamed.Item(1)

the following output is produced:

CopyCode image Copy Code
arg1
arg2

Applies To:

WshUnnamed Object

Expand image See Also

Reference

Arguments Property (WScript Object)
WshUnnamed Object
Count Method (Windows Script Host)
Item Property (WshNamed)
Exists Method (Windows Script Host)


length Property (WSHArguments Object)

Windows Script Host
length Property (WSHArguments Object)
See Also
CollapseAll image DropDown image

Returns the number of command-line parameters belonging to a script (the number of items in an argument's collection).

object.length

Expand image Arguments

object

An argument collection object.

Expand image 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.

Applies To:

WshArguments Object| WshNamed Object| WshUnnamed Object

Expand image See Also

Reference

Arguments Property (WScript Object)
Count Method (Windows Script Host)


length Property (WshEnvironment Object)

Windows Script Host
length Property (WshEnvironment Object)
See Also
CollapseAll image DropDown image

Returns the number of Windows environment variables on the local computer system (the number of items in an Environment collection).

object.length

Expand image Arguments

object

WshEnvironment object.

Expand image 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.

Applies To:

WshEnvironment Object

Expand image See Also

Reference

Count Method (Windows Script Host)


length Property (WshSpecialFolders Object)

Windows Script Host
length Property (WshSpecialFolders Object)
See Also
CollapseAll image DropDown image

Returns the number of Windows special folders on the local computer system (the number of items in a SpecialFolders collection).

object.length

Expand image Arguments

object

WshSpecialFolders object.

Expand image 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.

Applies To:

WshSpecialFolders Object

Expand image See Also

Reference

Count Method (Windows Script Host)


Line Property (WScript)

Windows Script Host
Line Property (WScript)
See Also Example
CollapseAll image DropDown image

Returns the current line number in an input stream.

object.strStream.Line

Expand image Arguments

object

WScript object.

strStream

StdIn property.

Expand image 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.

Expand image Example

The following code demonstrates the use of the Line property.

Visual Basic Script CopyCode image Copy Code
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 CopyCode image Copy Code
var stdin = WScript.StdIn;
var stdout = WScript.StdOut;

while (!stdin.AtEndOfStream)
{
     var str = stdin.ReadLine();
     stdout.WriteLine("Line " + (stdin.Line - 1) + ": " + str);
}

Applies To:

StdIn Property (WScript)

Expand image See Also

Reference

TextStream Object

Other Resources

Error Messages (Windows Script Host)


Line Property (WshRemoteError)

Windows Script Host
Line Property (WshRemoteError)
See Also Example
CollapseAll image DropDown image

Identifies the line in a script that contains an error.

Object.Line

Expand image Arguments

Object

WshRemoteError object.

Expand image 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).

Expand image Example

The following JScript code demonstrates how the WshRemoteError object exposes the line in which the error occurred.

Visual Basic Script CopyCode image Copy Code
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 CopyCode image Copy Code
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);
}

Applies To:

WshRemoteError Object

Expand image See Also

Reference

WshRemote Object
Character Property
Description Property (WshRemoteError)
Line Property
SourceText Property
Number Property (Windows Script Host)
Source Property (Windows Script Host)


Name Property (WScript Object)

Windows Script Host
Name Property (WScript Object)
See Also Example
CollapseAll image DropDown image

Returns the name of the WScript object (the host executable file).

object.Name

Expand image Arguments

object

WScript object.

Expand image Remarks

The Name property is a read-only string.

Applies To:

WScript Object

Expand image Example

The following JScript code shows how to use the Name property.
CopyCode image Copy Code
WScript.Echo (WScript.Name);

Expand image See Also

Reference

Path Property (Windows Script Host)


Named Property

Windows Script Host
Named Property
See Also Example
CollapseAll image DropDown image

Returns the WshNamed object (a collection of named arguments).

Object.Named

Parameters

Object

WshArguments object.

Expand image 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.

Applies To:

WshArguments Object

Expand image Example

The following code displays the number of named and unnamed command-line arguments.
CopyCode image Copy Code
<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>

Expand image See Also

Reference

WshNamed Object
Unnamed Property


Number Property (Windows Script Host)

Windows Script Host
Number Property (Windows Script Host)
See Also Example
CollapseAll image DropDown image

Reports the error number representing a script error.

Object.Number

Expand image Arguments

Object

WshRemoteError object.

Expand image Remarks

That Number property returns an unsigned long integer.

Expand image Example

The following JScript code demonstrates how the WshRemoteError object exposes the error number.

Visual Basic Script CopyCode image Copy Code
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 CopyCode image Copy Code
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);
}

Applies To:

WshRemoteError Object

Expand image See Also

Reference

WshRemote Object
Description Property (WshRemoteError)
Line Property (WshRemoteError)
Character Property
SourceText Property
Source Property (Windows Script Host)


Path Property (Windows Script Host)

Windows Script Host
Path Property (Windows Script Host)
See Also Example
CollapseAll image DropDown image

Returns the name of the directory containing the host executable (CScript.exe or WScript.exe).

object.Path

Expand image Arguments

object

WScript object.

Expand image Remarks

The Path property is a read-only string.

Expand image Example

Expand image Description

The following VBScript code echoes the directory where the executable file resides.

CopyCode image Copy Code
WScript.Echo (WScript.Path);

Applies To:

WScript Object

Expand image See Also

Reference

FullName Property (WScript Object)


ProcessID Property (Windows Script Host)

Windows Script Host
ProcessID Property (Windows Script Host)
See Also Example
CollapseAll image DropDown image

The process ID (PID) for a process started with the WshScriptExec object.

Object.ProcessID

Parameters

Object

WshScriptExec object.

Expand image Remarks

You can use the ProcessID property to activate an application (as an argument to the AppActivate method).

Expand image Example

The following code uses the ProcessID property to activate the calculator and notepad applications.

Visual Basic Script CopyCode image Copy Code
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 CopyCode image Copy Code
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");

Applies To:

WshScriptExec Object

Expand image See Also

Reference

AppActivate Method


RelativePath Property

Windows Script Host
RelativePath Property
See Also Example
CollapseAll image DropDown image

Assigns a relative path to a shortcut, or identifies the relative path of a shortcut.

object.RelativePath

Expand image Arguments

object

WshShortcut object.

Expand image Remarks

String.

Expand image Example

The following code sets the relative path of a shortcut.

Visual Basic Script CopyCode image Copy Code
Dim WshShell, WshShortcut
Set WshShell = WScript.CreateObject ("WScript.Shell")
Set WshShortcut = WshShell.CreateShortcut("MyScript.lnk")
WshShortcut.RelativePath = "C:\Scripts\"
JScript CopyCode image Copy Code
var WshShell = WScript.CreateObject ("WScript.Shell");
var WshShortcut = WshShell.CreateShortcut("MyScript.lnk");
WshShortcut.RelativePath = "C:\\Scripts\\";

Applies To:

WshShortcut Object

Expand image See Also

Reference

TargetPath Property


ScriptFullName Property

Windows Script Host
ScriptFullName Property
See Also
CollapseAll image DropDown image

Returns the full path of the currently running script.

object.ScriptFullName

Expand image Arguments

object

WScript object.

Expand image Remarks

The ScriptFullName property is a read-only string.

Expand image Legacy Example

The following example demonstrates the use of the ScriptFullName property.

CopyCode image Copy Code
<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>

Applies To:

WScript Object

Expand image See Also

Reference

ScriptName Property

Concepts

Running Your Scripts


ScriptName Property

Windows Script Host
ScriptName Property
See Also Example
CollapseAll image DropDown image

Returns the file name of the currently running script.

object.ScriptName

Expand image Arguments

object

WScript object.

Expand image Remarks

The ScriptName property is a read-only string.

Expand image Example

The following VBScript code echoes the name of the script being run.
CopyCode image Copy Code
WScript.Echo WScript.ScriptName

Expand image See Also

Reference

ScriptFullName Property
WScript Object


Source Property (Windows Script Host)

Windows Script Host
Source Property (Windows Script Host)
See Also Example
CollapseAll image DropDown image

Identifies the COM object responsible for causing the script error.

Object.Source

Expand image Arguments

Object

WshRemoteError object.

Expand image Remarks

The Source property returns a string.

Expand image Example

The following JScript code demonstrates how the WshRemoteError object exposes the COM object responsible for causing the script error.

Visual Basic Script CopyCode image Copy Code
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 CopyCode image Copy Code
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);
}

Applies To:

WshRemoteError Object

Expand image See Also

Reference

WshRemote Object
Description Property (Windows Script Host)
Line Property (WshRemoteError)
Character Property
SourceText Property
Number Property (Windows Script Host)


SourceText Property

Windows Script Host
SourceText Property
See Also Example
CollapseAll image DropDown image

Contains the line of source code that caused an error.

Object.SourceText

Expand image Arguments

Object

WshRemoteError object.

Expand image 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.

Expand image Example

The following JScript code demonstrates how the WshRemoteError object exposes the line of source code that caused an error.

Visual Basic Script CopyCode image Copy Code
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 CopyCode image Copy Code
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);
}

Applies To:

WshRemoteError Object

Expand image See Also

Reference

WshRemote Object
Description Property (WshRemoteError)
Line Property (WScript)
Character Property
Number Property (Windows Script Host)
Source Property (Windows Script Host)


SpecialFolders Property

Windows Script Host
SpecialFolders Property
See Also
CollapseAll image DropDown image

Returns a SpecialFolders object (a collection of special folders).

object.SpecialFolders(objWshSpecialFolders)

Expand image Arguments

object

WshShell object.

objWshSpecialFolders

The name of the special folder.

Expand image 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

Expand image Legacy Example

The following example demonstrates the use of the SpecialFolders property:

CopyCode image Copy Code
<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>

Applies To:

WshShell Object

Expand image See Also

Reference

WshSpecialFolders Object

Concepts

Running Your Scripts


Status Property (WshRemote)

Windows Script Host
Status Property (WshRemote)
See Also Example
CollapseAll image DropDown image

Reports the current status of the remote script.

Object.Status

Expand image Arguments

Object

WshRemote object.

Expand image Remarks

The Status property returns a read-only enumerated data type.

Expand image Values

The Status property returns one of three possible values.

Return Value | Numeric value | Description
NoTask | 0 | The remote script object has been created but has not yet executed.
Running | 1 | The remote script object is currently running.
Finished | 2 | The remote script object has finished running.

Expand image 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.

Visual Basic Script CopyCode image Copy Code
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 CopyCode image Copy Code
var Controller = WScript.CreateObject("WSHController");
var RemoteScript = Controller.CreateScript("test.js", "remoteserver");
RemoteScript.Execute();

while (RemoteScript.Status != 2) {
    WScript.Sleep(100);
}

Applies To:

WshRemote Object

Expand image See Also

Reference

WshController Object
Error Property (WshRemote)
Execute Method (Windows Script Host)
Terminate Method (WshScriptExec)
Start Event
End Event
Error Event


Status Property (WshScriptExec)

Windows Script Host
Status Property (WshScriptExec)
See Also Example
CollapseAll image DropDown image

Provides status information about a script run with the Exec() method.

Object.Status

Expand image Arguments

Object

WshScriptExec object.

Expand image Remarks

The Status property is used when a program is run asynchronously.

Expand image Return Value

The Status property returns a value from an enumerated type.

WshRunning ( = 0)

The job is still running.

WshFinished ( = 1)

The job has completed.

Expand image Example

The following code runs calc.exe and echoes the final status to the screen.

Visual Basic Script CopyCode image Copy Code
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 CopyCode image Copy Code
var WshShell = new ActiveXObject("WScript.Shell");
var oExec = WshShell.Exec("calc");

while (oExec.Status == 0)
{
     WScript.Sleep(100);
}

WScript.Echo(oExec.Status);

Applies To:

WshScriptExec Object

Expand image See Also

Reference

Exec Method (Windows Script Host)


StdErr Property (WScript)

Windows Script Host
StdErr Property (WScript)
See Also
CollapseAll image DropDown image

Exposes the write-only error output stream for the current script.

object.StdErr

Expand image Arguments

object

WScript object.

Expand image 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.

Applies To:

WScript Object

Expand image See Also

Reference

TextStream Object

Other Resources

Error Messages (Windows Script Host)


StdErr Property (WshScriptExec)

Windows Script Host
StdErr Property (WshScriptExec)
See Also Example
CollapseAll image DropDown image

Provides access to the stderr output stream of the Exec object.

Object.StdErr

Expand image Arguments

Object

WshScriptExec object.

Expand image Remarks

Use the StdErr property to retrieve data sent to the stderr stream from a process started with Exec.

Expand image Example

The following code demonstrates the StdErr object by attempting to execute a non-existent command and displaying the results.

Visual Basic Script CopyCode image Copy Code
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 CopyCode image Copy Code
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);

Applies To:

WshScriptExec Object

Expand image See Also

Reference

StdIn Property (WshScriptExec)
StdOut Property (WshScriptExec)
TextStream Object


StdIn Property (WScript)

Windows Script Host
StdIn Property (WScript)
See Also
CollapseAll image DropDown image

Exposes the read-only input stream for the current script.

object.StdIn

Expand image Arguments

object

WScript object.

Expand image 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.

Applies To:

WScript Object

Expand image See Also

Reference

Read Method (Windows Script Host)
ReadAll Method (Windows Script Host)
ReadLine Method (Windows Script Host)
Skip Method (Windows Script Host)
SkipLine Method (Windows Script Host)
AtEndOfLine Property (Windows Script Host)
Close Method (Windows Script Host)
Column Property (Windows Script Host)
Line Property (WScript)
TextStream Object

Other Resources

Error Messages (Windows Script Host)


StdIn Property (WshScriptExec)

Windows Script Host
StdIn Property (WshScriptExec)
See Also Example
CollapseAll image DropDown image

Exposes the stdin input stream of the Exec object.

Object.StdIn

Expand image Arguments

Object

WshScriptExec object.

Expand image Remarks

Use the StdIn property to pass data to a process started using Exec.

Expand image 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.

Visual Basic Script CopyCode image Copy Code
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 CopyCode image Copy Code
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);

Applies To:

WshScriptExec Object

Expand image See Also

Reference

StdErr Property (WshScriptExec)
TextStream Object


StdOut Property (WScript)

Windows Script Host
StdOut Property (WScript)
See Also
CollapseAll image DropDown image

Exposes the write-only output stream for the current script.

object.StdOut

Expand image Arguments

object

WScript object.

Expand image 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.

Applies To:

WScript Object

Expand image See Also

Reference

Write Method (Windows Script Host)
WriteBlankLines Method (Windows Script Host)
WriteLine Method (Windows Script Host)
Close Method (Windows Script Host)
Column Property (Windows Script Host)
Line Property (WScript)
TextStream Object

Other Resources

Error Messages (Windows Script Host)


StdOut Property (WshScriptExec)

Windows Script Host
StdOut Property (WshScriptExec)
See Also Example
CollapseAll image DropDown image

Exposes the write-only stdout output stream of the Exec object.

Object.StdOut

Expand image Arguments

Object

WshScriptExec object.

Expand image Remarks

The StdOut property contains a read-only copy of any information the script may have sent to the standard output.

Expand image 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.

Visual Basic Script CopyCode image Copy Code
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 CopyCode image Copy Code
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);

Applies To:

WshScriptExec Object

Expand image See Also

Reference

StdIn Property (WshScriptExec)
StdErr Property (WshScriptExec)
TextStream Object


TargetPath Property

Windows Script Host
TargetPath Property
See Also Example
CollapseAll image DropDown image

The path to the shortcut's executable.

object.TargetPath

Expand image Arguments

object

WshShortcut or WshUrlShortcut object.

Expand image 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.

Expand image Example

Expand image Description

The following example demonstrates the use of the TargetPath property:

CopyCode image Copy Code
<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>

Applies To:

WshShortcut Object| WshUrlShortcut Object

Expand image See Also

Concepts

Running Your Scripts


Unnamed Property

Windows Script Host
Unnamed Property
See Also Example
CollapseAll image DropDown image

Returns the WshUnnamed object (a collection of unnamed arguments).

Object.Unnamed

Parameters

Object

WshArguments object.

Expand image 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.

Expand image Example

Expand image Description

The following code displays the number of named and unnamed command-line arguments.

CopyCode image Copy Code
<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>

Applies To:

WshArguments Object

Expand image See Also

Reference

WshUnnamed Object
Named Property


UserDomain Property

Windows Script Host
UserDomain Property
See Also Example
CollapseAll image DropDown image

Returns a user's domain name.

object.UserDomain

Expand image Arguments

object

WshNetwork object.

Expand image Remarks

String.

The UserDomain property does not work on Windows 98 and Windows Millennium Edition unless the USERDOMAIN environment variable is set. The variable is not set by default.

Expand image Example

Expand image Description

The following example demonstrates the use of the UserDomain property:

CopyCode image Copy Code
<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>

Applies To:

WshNetwork Object

Expand image See Also

Concepts

Running Your Scripts


UserName Property

Windows Script Host
UserName Property
See Also Example
CollapseAll image DropDown image

Returns the name of a user.

object.UserName

Expand image Arguments

object

WshNetwork object.

Expand image Remarks

String.

If you are using this property in a login script, see Creating an Automated Login Script.

Expand image Example

Expand image Description

The following example demonstrates the use of the UserName property:

CopyCode image Copy Code
<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>

Applies To:

WshNetwork Object

Expand image See Also

Concepts

Running Your Scripts


Version Property (Windows Script Host)

Windows Script Host
Version Property (Windows Script Host)
See Also Example
CollapseAll image DropDown image

Returns the version of Windows Script Host.

object.Version

Expand image Arguments

object

WScript object.

Expand image Remarks

String.

Expand image Example

Expand image Description

The following VBScript code echoes the current version of Windows Script Host.

CopyCode image Copy Code
WScript.Echo WScript.Version

Applies To:

WScript Object

Expand image See Also

Reference

Name Property (WScript Object)


WindowStyle Property

Windows Script Host
WindowStyle Property
See Also Example
CollapseAll image DropDown image

Assigns a window style to a shortcut, or identifies the type of window style used by a shortcut.

object.WindowStyle = intWindowStyle

Expand image Arguments

object

WshShortcut object.

intWindowStyle

Sets the window style for the program being run.

Expand image Remarks

The WindowStyle property returns an integer.

The following table lists the available settings for intWindowStyle.

intWindowStyle | Description
1 | Activates and displays a window. If the window is minimized or maximized, the system restores it to its original size and position.
3 | Activates the window and displays it as a maximized window.
7 | Minimizes the window and activates the next top-level window.

Expand image Example

Expand image Description

The following example demonstrates the use of the WindowStyle property:

CopyCode image Copy Code
<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>

Applies To:

WshShortcut Object

Expand image See Also

Concepts

Running Your Scripts


WorkingDirectory Property (Windows Script Host)

Windows Script Host
WorkingDirectory Property (Windows Script Host)
See Also Example
CollapseAll image DropDown image

Assign a working directory to a shortcut, or identifies the working directory used by a shortcut.

object.WorkingDirectory = strWorkingDirectory

Expand image Arguments

object

WshShortcut object.

strWorkingDirectory

String. Directory in which the shortcut starts.

Expand image Remarks

String.

Expand image Example

Expand image Description

The following example demonstrates the use of the WorkingDirectory property:

CopyCode image Copy Code
<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>

Applies To:

WshShortcut Object

Expand image See Also

Concepts

Running Your Scripts


Methods (Windows Script Host)

Windows Script Host
Methods (Windows Script Host)
DropDown image

The following sections include information about the methods of Windows Script Host.

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.

Sign Method

Signs a script stored in a string.

SignFile Method

Signs a script using a digital signature.

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.

Verify Method

Verifies a digital signature retrieved as a string.

VerifyFile Method

Verifies the digital signature encapsulated in a script.

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.

Windows Script Host Basics

Learn the basics of WSH.


AddPrinterConnection Method

Windows Script Host
AddPrinterConnection Method
See Also Example
CollapseAll image DropDown image

Adds a remote MS-DOS-based printer connection to your computer system.

object.AddPrinterConnection(strLocalName, strRemoteName[,bUpdateProfile][,strUser][,strPassword])

Expand image 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.

Expand image 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.

Expand image Example

The following code uses the AddPrinterConnection method to connect a network printer to LPT1.

Visual Basic Script CopyCode image Copy Code
Set WshNetwork = WScript.CreateObject("WScript.Network")
WshNetwork.AddPrinterConnection "LPT1", "\\Server\Print1"
JScript CopyCode image Copy Code
var WshNetwork = WScript.CreateObject("WScript.Network");
WshNetwork.AddPrinterConnection ("LPT1", "\\\\Server\\Print1");

Applies To:

WshNetwork Object

Expand image See Also

Reference

AddWindowsPrinterConnection Method
EnumPrinterConnections Method
RemovePrinterConnection Method
SetDefaultPrinter Method


AddWindowsPrinterConnection Method

Windows Script Host
AddWindowsPrinterConnection Method
See Also
CollapseAll image DropDown image

Adds a Windows-based printer connection to your computer system.

Windows NT/2000:
object.AddWindowsPrinterConnection(
      strPrinterPath
)
Windows 9x/Me:
object.AddWindowsPrinterConnection(
      strPrinterPath,
      strDriverName[,strPort]
)

Expand image 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).

Expand image 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.

Expand image Example 1

The following code uses the AddWindowsPrinterConnection method to connect a network printer to a Windows NT/2000 computer system.

Visual Basic Script CopyCode image Copy Code
Set WshNetwork = WScript.CreateObject("WScript.Network")
PrinterPath = "\\printserv\DefaultPrinter"
WshNetwork.AddWindowsPrinterConnection PrinterPath
JScript CopyCode image Copy Code
var WshNetwork = WScript.CreateObject("WScript.Network");
var PrinterPath = "\\\\printserv\\DefaultPrinter";
WshNetwork.AddWindowsPrinterConnection(PrinterPath);

Expand image Example 2

The following code uses the AddWindowsPrinterConnection method to connect a network printer to a Windows 9x/Me computer system.

Visual Basic Script CopyCode image Copy Code
Set WshNetwork = WScript.CreateObject("WScript.Network")
PrinterPath = "\\printserv\DefaultPrinter"
PrinterDriver = "Lexmark Optra S 1650"
WshNetwork.AddWindowsPrinterConnection PrinterPath, PrinterDriver
JScript CopyCode image Copy Code
var WshNetwork = WScript.CreateObject("WScript.Network");
var PrinterPath = "\\\\printserv\\DefaultPrinter";
var PrinterDriver = "Lexmark Optra S 1650";
WshNetwork.AddWindowsPrinterConnection(PrinterPath, PrinterDriver);

Applies To:

WshNetwork Object

Expand image See Also

Reference

AddPrinterConnection Method
EnumPrinterConnections Method
RemovePrinterConnection Method
SetDefaultPrinter Method


AppActivate Method

Windows Script Host
AppActivate Method
See Also Example
CollapseAll image DropDown image

Activates an application window.

object.AppActivate title

Expand image 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.

Expand image 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.

Expand image Example

Expand image Description

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.

CopyCode image Copy Code
<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>

Applies To:

WshShell Object

Expand image See Also

Reference

SendKeys Method

Concepts

Running Your Scripts


Close Method (Windows Script Host)

Windows Script Host
Close Method (Windows Script Host)
See Also
CollapseAll image DropDown image

Closes a text stream.

object.Close

Expand image Arguments

object

StdIn, StdOut, or StdErr text stream objects.

Expand image 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.

Applies To:

StdErr Property (WScript)| StdIn Property (WScript)| StdOut Property (WScript)

Expand image See Also

Reference

TextStream Object

Other Resources

Error Messages (Windows Script Host)


ConnectObject Method

Windows Script Host
ConnectObject Method
See Also Example
CollapseAll image DropDown image

Connects the object's event sources to functions with a given prefix.

object.ConnectObject(objEventSource, strPrefix)

Expand image Arguments

object

WScript object.

objEventSource

Required. Object you want to connect.

strPrefix

Required. String value indicating the function prefix.

Expand image 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.

Expand image Example

The following example demonstrates using the ConnectObject method to connect to the WshRemote object's Error event.

Visual Basic Script CopyCode image Copy Code
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 CopyCode image Copy Code
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);
}

Applies To:

WScript Object

Expand image See Also

Reference

DisconnectObject Method
CreateObject Method
GetObject Method


Count Method (Windows Script Host)

Windows Script Host
Count Method (Windows Script Host)
See Also
CollapseAll image DropDown image

Returns the number of members in an object.

object.Count

Expand image Arguments

object

A WshArguments, WshEnvironment, WshNamed, WshSpecialFolders, or WshUnnamed object, or the WScriptArguments property.

Expand image 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.

Expand image Example (WshNamed)

The following example demonstrates the Count method using the WshNamed object. Begin by typing the following text at the Command Prompt.

CopyCode image Copy Code
myScript.vbs /c:"WSH is a wonderful thing" /s:"scripts are wonderful"

Next, add the following VBScript code.

CopyCode image Copy Code
        For i = 0 to WScript.Arguments.Count-1
    WScript.Echo WScript.Arguments.Named(i)
next i

Following is the result.

CopyCode image Copy Code
WSH is a wonderful thing
scripts are wonderful

Expand image Example (WshUnnamed)

The following example demonstrates the Count method using the WshUnnamed object. Begin by typing the following text at the command line.

CopyCode image Copy Code
myscript.vbs "WSH is a wonderful thing" "scripts are wonderful"

Next, add the following VBScript code.

CopyCode image Copy Code
        For i = 0 to WScript.Arguments.Count-1
    WScript.Echo WScript.Arguments.Unnamed(i)
next i

Following is the result.

CopyCode image Copy Code
WSH is a wonderful thing
scripts are wonderful

Applies To:

Arguments Property (WScript Object)| WshArguments Object| WshEnvironment Object| WshNamed Object| WshSpecialFolders Object| WshUnnamed Object

Expand image See Also

Reference

Item Property (WshNamed)
Exists Method (Windows Script Host)
Length Property


CreateObject Method

Windows Script Host
CreateObject Method
See Also Example
CollapseAll image DropDown image

Creates a COM object.

object.CreateObject(strProgID[,strPrefix])

Expand image 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.

Expand image 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.

Expand image Example

Expand image Description

The following VBScript code uses the CreateObject method to create a WshNetwork object:

CopyCode image Copy Code
Set WshNetwork = WScript.CreateObject("WScript.Network")

Applies To:

WScript Object

Expand image See Also

Reference

GetObject Method
ConnectObject Method
DisconnectObject Method


CreateScript Method

Windows Script Host
CreateScript Method
See Also Example
CollapseAll image DropDown image

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).

Expand image 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.

Expand image 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).

Visual Basic Script CopyCode image Copy Code
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 CopyCode image Copy Code
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);
}

Applies To:

WshController Object

Expand image See Also

Reference

CreateObject Method
CreateScript Method
WshRemote Object
Execute Method (Windows Script Host)


CreateShortcut Method

Windows Script Host
CreateShortcut Method
See Also Example
CollapseAll image DropDown image

Creates a new shortcut, or opens an existing shortcut.

object.CreateShortcut(strPathname)

Expand image Arguments

object

WshShell object.

strPathname

String value indicating the pathname of the shortcut to create.

Expand image 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 Note

    A common problem is putting arguments in the TargetPath property of the shortcut object, which doesn't work. All arguments to the shortcut must be put in the Arguments property.

Expand image Example

Expand image Description

The following example creates a WshShell object and uses the CreateShortcut method to create two shortcuts.

CopyCode image Copy Code
<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>

Applies To:

WshShell Object

Expand image See Also

Reference

WshShortcut Object
WshUrlShortcut Object

Concepts

Running Your Scripts


DisconnectObject Method

Windows Script Host
DisconnectObject Method
See Also Example
CollapseAll image DropDown image

Disconnects a connected object's event sources.

object.DisconnectObject(obj)

Expand image Arguments

object

WScript object.

obj

String value indicating the name of the object to disconnect.

Expand image 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.

Expand image Example

The following example demonstrates using the DisconnectObject method to disconnect to the WshRemote object's Error event after a remote script has completed.

Visual Basic Script CopyCode image Copy Code
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 CopyCode image Copy Code
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);
}

Applies To:

WScript Object

Expand image See Also

Reference

ConnectObject Method
CreateObject Method
GetObject Method


Echo Method

Windows Script Host
Echo Method
See Also Example
CollapseAll image DropDown image

Outputs text to either a message box or the command console window.

object.Echo [Arg1] [,Arg2] [,Arg3] ...

Expand image Arguments

object

WScript object.

Arg1, Arg2, Arg3 ...

Optional. String value indicating the list of items to be displayed.

Expand image 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.

Expand image Example

Expand image Description

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.

CopyCode image Copy Code
<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>

Applies To:

WScript Object

Expand image See Also

Concepts

Running Your Scripts


EnumNetworkDrives Method

Windows Script Host
EnumNetworkDrives Method
See Also Example
CollapseAll image DropDown image

Returns the current network drive mapping information.

objDrives = object.EnumNetworkDrives

Expand image Arguments

object

WshNetwork object.

objDrives

Variable that holds the network drive mapping information.

Expand image 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).

Expand image Example

Expand image Description

The following example uses EnumNetworkDrives to generate a list of the networked drives and displays the mapping information.

CopyCode image Copy Code
<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>

Applies To:

WshNetwork Object

Expand image See Also

Reference

MapNetworkDrive Method
RemoveNetworkDrive Method

Concepts

Running Your Scripts


EnumPrinterConnections Method

Windows Script Host
EnumPrinterConnections Method
See Also Example
CollapseAll image DropDown image

Returns the current network printer mapping information.

objPrinters = object.EnumPrinterConnections

Expand image Arguments

object

WshNetwork object.

objPrinters

Variable that holds the network printer mapping information.

Expand image 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).

Expand image Example

Expand image Description

The following example uses the EnumPrinterConnections method to generate a list of networked printers and displays this mapping information.

CopyCode image Copy Code
<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>

Applies To:

WshNetwork Object

Expand image See Also

Reference

AddPrinterConnection Method
AddWindowsPrinterConnection Method
RemovePrinterConnection Method
SetDefaultPrinter Method

Concepts

Running Your Scripts


Exec Method (Windows Script Host)

Windows Script Host
Exec Method (Windows Script Host)
See Also Example
CollapseAll image DropDown image

Runs an application in a child command-shell, providing access to the StdIn/StdOut/StdErr streams.

object.Exec(strCommand)

Expand image 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.

Expand image 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).

Expand image Example

The following example demonstrates the basics of the Exec method.

Visual Basic Script CopyCode image Copy Code
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 CopyCode image Copy Code
var WshShell = new ActiveXObject("WScript.Shell");
var oExec = WshShell.Exec("calc");

while (oExec.Status == 0)
{
     WScript.Sleep(100);
}

WScript.Echo(oExec.Status);

Applies To:

WshShell Object

Expand image See Also

Reference

WshScriptExec Object


Execute Method (Windows Script Host)

Windows Script Host
Execute Method (Windows Script Host)
See Also Example
CollapseAll image DropDown image

Starts execution of a remote script object.

object.Execute

Parameters

object

WshRemote Object

Expand image 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).

Expand image Example

The following example demonstrates how the Execute method is used to create a WshRemote object (start an instance of a remote script).

Visual Basic Script CopyCode image Copy Code
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 CopyCode image Copy Code
var Controller = WScript.CreateObject("WSHController");
var RemoteScript = Controller.CreateScript("remote1.js");
RemoteScript.Execute();

while (RemoteScript.Status != 2) {
    WScript.Sleep(100);
}

Applies To:

WshRemote Object

Expand image See Also

Reference

WshController Object
Status Property (WshRemote)
Error Property (WshRemote)
Terminate Method (WshScriptExec)
Start Event
End Event


Exists Method (Windows Script Host)

Windows Script Host
Exists Method (Windows Script Host)
See Also Example
CollapseAll image DropDown image

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.

Expand image 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).

Expand image Example

Consider the following information typed at the command line.

CopyCode image Copy Code
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.

CopyCode image Copy Code
WScript.Echo(WScript.Arguments.Named.Exists("C"));
WScript.Echo(WScript.Arguments.Named.Exists("D"));

Applies To:

WshNamed Object

Expand image See Also

Reference

Arguments Property (WScript Object)
WshUnnamed Object
Count Method (Windows Script Host)
Item Property (WshNamed)


ExpandEnvironmentStrings Method

Windows Script Host
ExpandEnvironmentStrings Method
See Also Example
CollapseAll image DropDown image

Returns an environment variable's expanded value.

object.ExpandEnvironmentStrings(strString)

Expand image Arguments

object

WshShell object.

strString

String value indicating the name of the environment variable you want to expand.

Expand image 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.

Expand image Example

The following code expands the Windows Directory environment variable and displays it:

Visual Basic Script CopyCode image Copy Code
set WshShell = WScript.CreateObject("WScript.Shell")
WScript.Echo "WinDir is " & WshShell.ExpandEnvironmentStrings("%WinDir%")
JScript CopyCode image Copy Code
var WshShell = WScript.CreateObject("WScript.Shell");
WScript.Echo("WinDir is " + WshShell.ExpandEnvironmentStrings("%WinDir%"));

Applies To:

WshShell Object

Expand image See Also

Reference

RegRead Method


GetObject Method

Windows Script Host
GetObject Method
See Also Example
CollapseAll image DropDown image

Retrieves an existing object with the specified ProgID, or creates a new one from a file.

object.GetObject(strPathname [,strProgID], [strPrefix])

Expand image 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.

Expand image 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.

Expand image Example

The following VBScript code starts the application associated with the specified file (strPathname):

CopyCode image Copy Code
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:

CopyCode image Copy Code
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.

CopyCode image Copy Code
Dim MyObject As Object
Set MyObject = GetObject("C:\DRAWINGS\SAMPLE.DRW", "FIGMENT.DRAWING")

Applies To:

WScript Object

Expand image See Also

Reference

CreateObject Method
DisconnectObject Method


getResource Method

Windows Script Host
getResource Method
See Also Example
CollapseAll image DropDown image

Returns the value of a resource defined with the <resource> element.

getResource(resourceID)

Expand image Arguments

resourceID

A string that uniquely identifies the resource information contained within a set of resource tags in a *.WSF script file.

Expand image 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.

Expand image Example

The following WSH script defines a resource called errNonNumeric. The value of errNonNumeric is displayed if the parameter upperBound is not a number.
CopyCode image Copy Code
<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>

Expand image See Also

Reference

<resource> Element (Windows Script Host)


LogEvent Method

Windows Script Host
LogEvent Method
See Also Example
CollapseAll image DropDown image

Adds an event entry to a log file.

object.LogEvent(intType, strMessage [,strTarget])

Expand image 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.

Expand image 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 | Value
0 | SUCCESS
1 | ERROR
2 | WARNING
4 | INFORMATION
8 | AUDIT_SUCCESS
16 | AUDIT_FAILURE

Expand image Example

The following code logs SUCCESS or ERROR depending on the outcome of the function runLoginScript().

Visual Basic Script CopyCode image Copy Code
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 CopyCode image Copy Code
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");

Applies To:

WshShell Object

Expand image See Also

Reference

Popup Method


MapNetworkDrive Method

Windows Script Host
MapNetworkDrive Method
See Also Example
CollapseAll image DropDown image

Adds a shared network drive to your computer system.

object.MapNetworkDrive(strLocalName, strRemoteName, [bUpdateProfile], [strUser], [strPassword])

Expand image 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.

Expand image Remarks

An attempt to map a non-shared network drive results in an error.

Expand image Example

The following code maps the logical drive "E" to a network share with the UNC name "\\Server\Public."

Visual Basic Script CopyCode image Copy Code
Dim WshNetwork
Set WshNetwork = WScript.CreateObject("WScript.Network")
WshNetwork.MapNetworkDrive "E:", "\\Server\Public"
JScript CopyCode image Copy Code
var WshNetwork = WScript.CreateObject("WScript.Network");
WshNetwork.MapNetworkDrive ("E:", "\\\\Server\\Public");

Applies To:

WshNetwork Object

Expand image See Also

Reference

EnumNetworkDrives Method
RemoveNetworkDrive Method


Popup Method

Windows Script Host
Popup Method
See Also Example
CollapseAll image DropDown image

Displays text in a pop-up message box.

intButton = object.Popup(strText,[nSecondsToWait],[strTitle],[nType])

Expand image 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.

Expand image 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 Note

To display text properly in RTL languages such as Hebrew or Arabic, add hex &h00100000 (decimal 1048576) to the nType parameter.

Button Types

Value | Description
0 | Show OK button.
1 | Show OK and Cancel buttons.
2 | Show Abort, Retry, and Ignore buttons.
3 | Show Yes, No, and Cancel buttons.
4 | Show Yes and No buttons.
5 | Show Retry and Cancel buttons.
Icon Types
Value | Description
16 | Show "Stop Mark" icon.
32 | Show "Question Mark" icon.
48 | Show "Exclamation Mark" icon.
64 | 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

Expand image Example

The following code generates a simple pop-up window.

Visual Basic Script CopyCode image Copy Code
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 CopyCode image Copy Code
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;
}

Applies To:

WshShell Object

Expand image See Also

Reference

Echo Method


Quit Method (Windows Script Host)

Windows Script Host
Quit Method (Windows Script Host)
See Also Example
CollapseAll image DropDown image

Forces script execution to stop at any time.

object.Quit([intErrorCode])

Expand image 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.

Expand image 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.

Expand image Example

Expand image Description

The following JScript code snippet quits execution and returns an error code of 1:

CopyCode image Copy Code
WScript.Quit (1);

// This line of code is never executed.
var i = 0;

Applies To:

WScript Object

Expand image See Also

Reference

Sleep Method


Read Method (Windows Script Host)

Windows Script Host
Read Method (Windows Script Host)
See Also Example
CollapseAll image DropDown image

Returns a specified number of characters from an input stream.

object.Read(characters)

Expand image Arguments

object

StdIn text stream object.

characters

Integer value indicating the number of characters you want to read.

Expand image 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.

Expand image Example

The following code uses the Read method to get a character from the keyboard and display it on the console.

Visual Basic Script CopyCode image Copy Code
Dim Input
Input = ""

Do While Not WScript.StdIn.AtEndOfLine
   Input = Input & WScript.StdIn.Read(1)
Loop
WScript.Echo Input
JScript CopyCode image Copy Code
var input = "";
while (!WScript.StdIn.AtEndOfLine)
{
   input += WScript.StdIn.Read(1);
}
WScript.Echo(input);

Applies To:

StdIn Property (WScript)

Expand image See Also

Reference

Write Method (Windows Script Host)
TextStream Object


ReadAll Method (Windows Script Host)

Windows Script Host
ReadAll Method (Windows Script Host)
See Also Example
CollapseAll image DropDown image

Returns all characters from an input stream.

object.ReadAll

Expand image Arguments

object

StdIn text stream object.

Expand image 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.

Expand image Example

The following code demonstrates the use of ReadAll.

Visual Basic Script CopyCode image Copy Code
Dim Input
Input = ""

Do While Not WScript.StdIn.AtEndOfStream
   Input = Input & WScript.StdIn.ReadAll
Loop
WScript.Echo Input
JScript CopyCode image Copy Code
var input = "";
while (!WScript.StdIn.AtEndOfStream)
{
   input += WScript.StdIn.ReadAll();
}
WScript.Echo(input);

Applies To:

StdIn Property (WScript)

Expand image See Also

Reference

FileSystemObject Object
TextStream Object


ReadLine Method (Windows Script Host)

Windows Script Host
ReadLine Method (Windows Script Host)
See Also Example
CollapseAll image DropDown image

Returns an entire line from an input stream.

object.ReadLine

Expand image Arguments

object

StdIn text stream object.

Expand image 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 Note

Although this method extracts the newline character, it does not add it to the string.

Expand image Example

The following code demonstrates the use of the ReadLine method.

Visual Basic Script CopyCode image Copy Code
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 CopyCode image Copy Code
var stdin = WScript.StdIn;
var stdout = WScript.StdOut;

while (!stdin.AtEndOfStream)
{
     var str = stdin.ReadLine();
     stdout.WriteLine("Line " + (stdin.Line - 1) + ": " + str);
}

Applies To:

StdIn Property (WScript)

Expand image See Also

Reference

FileSystemObject Object
TextStream Object


RegDelete Method

Windows Script Host
RegDelete Method
See Also Example
CollapseAll image DropDown image

Deletes a key or one of its values from the registry.

object.RegDelete(strName)

Expand image Arguments

object

WshShell object.

strName

String value indicating the name of the registry key or key value you want to delete.

Expand image 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

Expand image Example

The following code creates a key and two values, reads them, and deletes them.

Visual Basic Script CopyCode image Copy Code
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 CopyCode image Copy Code
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\\");

Applies To:

WshShell Object

Expand image See Also

Reference

RegRead Method
RegWrite Method


RegRead Method

Windows Script Host
RegRead Method
See Also Example
CollapseAll image DropDown image

Returns the value of a key or value-name from the registry.

object.RegRead(strName)

Expand image Arguments

object

WshShell object.

strName

String value indicating the key or value-name whose value you want.

Expand image Remarks

The RegRead method returns values of the following five types.

Type | Description | In the Form of
REG_SZ | A string | A string
REG_DWORD | A number | An integer
REG_BINARY | A binary value | A VBArray of integers
REG_EXPAND_SZ | An expandable string (e.g., "%windir%\\calc.exe") | A string
REG_MULTI_SZ | An array of strings | 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

Expand image Example

The following code creates a key and two values, reads them, and deletes them.

Visual Basic Script CopyCode image Copy Code
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 CopyCode image Copy Code
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\\");

Applies To:

WshShell Object

Expand image See Also

Reference

RegDelete Method
RegWrite Method


RegWrite Method

Windows Script Host
RegWrite Method
See Also Example
CollapseAll image DropDown image

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])

Expand image 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.

Expand image 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 Note

The REG_MULTI_SZ type is not supported for the RegWrite method.

Note 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 | In the Form of
REG_SZ | A string | A string
REG_DWORD | A number | An integer
REG_BINARY | A binary value | An integer
REG_EXPAND_SZ | An expandable string (e.g., "%windir%\\calc.exe") | A string

Expand image Example

The following code creates a key and two values, reads them, and deletes them.

Visual Basic Script CopyCode image Copy Code
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 CopyCode image Copy Code
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\\");

Applies To:

WshShell Object

Expand image See Also

Reference

RegDelete Method
RegRead Method


Remove Method (Windows Script Host)

Windows Script Host
Remove Method (Windows Script Host)
See Also Example
CollapseAll image DropDown image

Removes an existing environment variable.

object.Remove(strName)

Expand image Arguments

object

WshEnvironment object.

strName

String value indicating the name of the environment variable you want to remove.

Expand image 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.

Expand image Example

The following code removes the Process environment variable TestVar.

Visual Basic Script CopyCode image Copy Code
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 CopyCode image Copy Code
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%'"));

Applies To:

WshEnvironment Object

Expand image See Also

Reference

Environment Property


RemoveNetworkDrive Method

Windows Script Host
RemoveNetworkDrive Method
See Also Example
CollapseAll image DropDown image

Removes a shared network drive from your computer system.

object.RemoveNetworkDrive(strName, [bForce], [bUpdateProfile])

Expand image 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.

Expand image 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.

Expand image Example

The following code removes the logical drive "E."

Visual Basic Script CopyCode image Copy Code
Dim WshNetwork
Set WshNetwork = WScript.CreateObject("WScript.Network")
WshNetwork. RemoveNetworkDrive"E:"
JScript CopyCode image Copy Code
var WshNetwork = WScript.CreateObject("WScript.Network");
WshNetwork.RemoveNetworkDrive ("E:");

Applies To:

WshNetwork Object

Expand image See Also

Reference

EnumNetworkDrives Method
MapNetworkDrive Method


RemovePrinterConnection Method

Windows Script Host
RemovePrinterConnection Method
See Also Example
CollapseAll image DropDown image

Removes a shared network printer connection from your computer system.

object.RemovePrinterConnection(strName, [bForce], [bUpdateProfile])

Expand image 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.

Expand image 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.

Expand image Example

The following code disconnects a network printer.

Visual Basic Script CopyCode image Copy Code
Set WshNetwork = WScript.CreateObject("WScript.Network")
PrinterPath = "\\printserv\DefaultPrinter"
WshNetwork.RemovePrinterConnection PrinterPath, true, true
JScript CopyCode image Copy Code
var WshNetwork = WScript.CreateObject("WScript.Network");
var PrinterPath = "\\\\PRN-CORP1\\B41-4523-A";
WshNetwork.RemovePrinterConnection(PrinterPath, true, true);

Applies To:

WshNetwork Object

Expand image See Also

Reference

AddPrinterConnection Method
AddWindowsPrinterConnection Method
EnumPrinterConnections Method
SetDefaultPrinter Method


Run Method (Windows Script Host)

Windows Script Host
Run Method (Windows Script Host)
See Also
CollapseAll image DropDown image

Runs a program in a new process.

object.Run(strCommand, [intWindowStyle], [bWaitOnReturn])

Expand image 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).

Expand image 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 | Description
0 | Hides the window and activates another window.
1 | 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.
2 | Activates the window and displays it as a minimized window.
3 | Activates the window and displays it as a maximized window.
4 | Displays a window in its most recent size and position. The active window remains active.
5 | Activates the window and displays it in its current size and position.
6 | Minimizes the specified window and activates the next top-level window in the Z order.
7 | Displays the window as a minimized window. The active window remains active.
8 | Displays the window in its current state. The active window remains active.
9 | 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.
10 | Sets the show-state based on the state of the program that started the application.

Expand image Example 1

The following VBScript code opens a copy of the currently running script with Notepad.

CopyCode image Copy Code
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.

CopyCode image Copy Code
Set WshShell = WScript.CreateObject("WScript.Shell")
Return = WshShell.Run("notepad " & WScript.ScriptFullName, 1, true)

Expand image Example 2

The following VBScript code opens a command window, changes to the path to C:\ , and executes the DIR command.

CopyCode image Copy Code
Dim oShell
Set oShell = WScript.CreateObject ("WSCript.shell")
oShell.run "cmd /K CD C:\ & Dir"
Set oShell = Nothing

Applies To:

WshShell Object

Expand image See Also

Reference

Exec Method (Windows Script Host)


Save Method (Windows Script Host)

Windows Script Host
Save Method (Windows Script Host)
See Also Example
CollapseAll image DropDown image

Saves a shortcut object to disk.

object.Save

Expand image Arguments

object

WshShortcut or WshUrlShortcut object.

Expand image 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).

Expand image Example

Expand image Description

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.

CopyCode image Copy Code
<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>

Applies To:

WshShortcut Object| WshUrlShortcut Object

Expand image See Also

Reference

FullName Property (WScript Object)
TargetPath Property
WindowStyle Property
Hotkey Property
IconLocation Property
Description Property (Windows Script Host)
WorkingDirectory Property (Windows Script Host)

Concepts

Running Your Scripts


SendKeys Method

Windows Script Host
SendKeys Method
See Also Example
CollapseAll image DropDown image

Sends one or more keystrokes to the active window (as if typed on the keyboard).

object.SendKeys(string)

Expand image Arguments

object

WshShell object.

string

String value indicating the keystroke(s) you want to send.

Expand image 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 Note

To send 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 | Argument
BACKSPACE | {BACKSPACE}, {BS}, or {BKSP}
BREAK | {BREAK}
CAPS LOCK | {CAPSLOCK}
DEL or DELETE | {DELETE} or {DEL}
DOWN ARROW | {DOWN}
END | {END}
ENTER | {ENTER} or ~
ESC | {ESC}
HELP | {HELP}
HOME | {HOME}
INS or INSERT | {INSERT} or {INS}
LEFT ARROW | {LEFT}
NUM LOCK | {NUMLOCK}
PAGE DOWN | {PGDN}
PAGE UP | {PGUP}
PRINT SCREEN | {PRTSC}
RIGHT ARROW | {RIGHT}
SCROLL LOCK | {SCROLLLOCK}
TAB | {TAB}
UP ARROW | {UP}
F1 | {F1}
F2 | {F2}
F3 | {F3}
F4 | {F4}
F5 | {F5}
F6 | {F6}
F7 | {F7}
F8 | {F8}
F9 | {F9}
F10 | {F10}
F11 | {F11}
F12 | {F12}
F13 | {F13}
F14 | {F14}
F15 | {F15}
F16 | {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 | Special Character
SHIFT | +
CTRL | ^
ALT | %
Note 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 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 Note

You cannot send the PRINT SCREEN key {PRTSC} to an application.

Expand image Example

Expand image Description

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.

CopyCode image Copy Code
<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>

Applies To:

WshShell Object

Expand image See Also

Reference

Run Method (Windows Script Host)


SetDefaultPrinter Method

Windows Script Host
SetDefaultPrinter Method
See Also Example
CollapseAll image DropDown image

Assigns a remote printer the role Default Printer.

object.SetDefaultPrinter(strPrinterName)

Expand image Arguments

object

WshNetwork object.

strPrinterName

String value indicating the remote printer's UNC name.

Expand image 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.

Expand image Example

The following code uses the AddWindowsPrinterConnection method to connect a network printer and set it as the default printer.

Visual Basic Script CopyCode image Copy Code
Set WshNetwork = WScript.CreateObject("WScript.Network")
PrinterPath = "\\research\library1"
WshNetwork.AddWindowsPrinterConnection PrinterPath
WshNetwork.SetDefaultPrinter PrinterPath
JScript CopyCode image Copy Code
var WshNetwork = WScript.CreateObject("WScript.Network");
var PrinterPath = "\\\\research\\library1";
WshNetwork.AddWindowsPrinterConnection(PrinterPath);
WshNetwork.SetDefaultPrinter(PrinterPath);

Applies To:

WshNetwork Object

Expand image See Also

Reference

AddPrinterConnection Method
AddWindowsPrinterConnection Method
EnumPrinterConnections Method
RemovePrinterConnection Method


ShowUsage Method

Windows Script Host
ShowUsage Method
See Also Example
CollapseAll image DropDown image

Makes a script self-documenting by displaying information about how it should be used.

object.ShowUsage

Parameters

object

WScript Object.

Expand image 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 Note

The usage can also be displayed using the /? switch.

Expand image Example

The following example demonstrates how to set up usage information in a *.WSF script file.

CopyCode image Copy Code
<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:

CopyCode image Copy Code
if (WScript.Arguments.length != 1)
{
   WScript.Arguments.ShowUsage();
   WScript.Quit();
}

Calling the ShowUsage method from this script results in the following output:

CopyCode image Copy Code
This script reboots a server
Usage: reboot.wsf /server:value

Options:

server : Server to run the script onExample:
reboot.wsf /server:scripting

Applies To:

Arguments Property (WScript Object)

Expand image See Also

Reference

WScript Object


Sign Method

Windows Script Host
Sign Method
See Also Example
CollapseAll image DropDown image

Signs a script stored in a string.

Object.Sign (FileExtension, Text, Certificate, Store)

Expand image 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".

Expand image 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.

Expand image Example

CopyCode image Copy Code
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")

Applies To:

Scripting.Signer Object

Expand image See Also

Reference

SignFile Method
Verify Method
VerifyFile Method

Concepts

Signing a Script (Windows Script Host)


SignFile Method

Windows Script Host
SignFile Method
See Also Example
CollapseAll image DropDown image

Signs a script using a digital signature.

Object.SignFile (FileName, Certificate, Store)

Expand image 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".

Expand image Remarks

In order to sign a digital signature, the author must have a valid certificate.

Expand image Example

Expand image Description

The following example demonstrates not only signature checking but also the command-line argument.

CopyCode image Copy Code
<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>

Applies To:

Scripting.Signer Object

Expand image See Also

Reference

Sign Method
Verify Method
VerifyFile Method

Concepts

Signing a Script (Windows Script Host)


Skip Method (Windows Script Host)

Windows Script Host
Skip Method (Windows Script Host)
See Also Example
CollapseAll image DropDown image

Skips a specified number of characters when reading from an input text stream.

object.Skip(characters)

Expand image Arguments

object

StdIn text stream object.

characters

Integer value indicating the number of characters you want to skip.

Expand image 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).

Expand image 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.

Visual Basic Script CopyCode image Copy Code
WScript.StdIn.Skip 1
Input = WScript.StdIn.ReadLine
WScript.StdOut.Write Input
JScript CopyCode image Copy Code
WScript.StdIn.Skip(1);
Input = WScript.StdIn.ReadLine();
WScript.StdOut.Write(Input);

Applies To:

StdIn Property (WScript)

Expand image See Also

Reference

TextStream Object


SkipLine Method (Windows Script Host)

Windows Script Host
SkipLine Method (Windows Script Host)
See Also Example
CollapseAll image DropDown image

Skips the next line when reading from an input text stream.

object.SkipLine

Expand image Arguments

object

StdIn text stream object.

Expand image 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).

Expand image Example

The following code demonstrates the SkipLine method.

Visual Basic Script CopyCode image Copy Code
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 CopyCode image Copy Code
var stdin = WScript.StdIn;
var stdout = WScript.StdOut;
var str1, str2 = "";
var i;
for (i = 0; i < 5; i++)
     stdin.SkipLine();
i = 0;
while (!stdin.AtEndOfStream)
{
     if (i++ >= 2)
     {
          stdout.WriteLine(str1);
     }
     str1 = str2;
     str2 = stdin.ReadLine();
}

Applies To:

StdIn Property (WScript)

Expand image See Also

Reference

TextStream Object


Sleep Method

Windows Script Host
Sleep Method
See Also Example
CollapseAll image DropDown image

Suspends script execution for a specified length of time, then continues execution.

object.Sleep(intTime)

Expand image Arguments

object

WScript object.

intTime

Integer value indicating the interval (in milliseconds) you want the script process to be inactive.

Expand image 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 Note

Passing the Sleep method a 0 or –1 does not cause the script to suspend indefinitely.

Expand image Example

Expand image Description

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.

CopyCode image Copy Code
<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>

Applies To:

WScript Object

Expand image See Also

Concepts

Running Your Scripts


Terminate Method (WshScriptExec)

Windows Script Host
Terminate Method (WshScriptExec)
See Also Example
CollapseAll image DropDown image

Instructs the script engine to end the process started by the Exec method.

object.Terminate

Expand image Arguments

object

WshScriptExec object.

Expand image 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.

Expand image Example

Expand image Description

The following JScript example demonstrates how to use the Terminate method to stop a running script.

CopyCode image Copy Code
var aScript = WScript.Exec("%comspec% /c myScript.js");
aScript.Terminate();

Applies To:

WshScriptExec Object

Expand image See Also

Reference

Quit Method (Windows Script Host)


Verify Method

Windows Script Host
Verify Method
See Also Example
CollapseAll image DropDown image

Verifies a digital signature retrieved as a string.

object.Verify (FileExtension, Text, ShowUI)

Expand image 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 Note

On some operating systems, 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.

Expand image Remarks

The Verify method is used to verify a digital signed script stored in a string.

Expand image Example

Expand image Description

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.)

CopyCode image Copy Code
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)

Applies To:

Scripting.Signer Object

Expand image See Also

Reference

VerifyFile Method
Sign Method
SignFile Method

Concepts

Verifying a Script


VerifyFile Method

Windows Script Host
VerifyFile Method
See Also Example
CollapseAll image DropDown image

Verifies the digital signature encapsulated in a script.

Object.VerifyFile (FileName, ShowUI)

Expand image 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 Note

On some operating systems, 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.

Expand image Example

Expand image Description

The following example demonstrates signature checking using the command-line argument processing features.

CopyCode image Copy Code
<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>

Applies To:

Scripting.Signer Object

Expand image See Also

Reference

Verify Method
Sign Method
SignFile Method

Concepts

Verifying a Script


Write Method (Windows Script Host)

Windows Script Host
Write Method (Windows Script Host)
See Also Example
CollapseAll image DropDown image

Sends a string to an output stream.

object.Write(strText)

Expand image Arguments

object

StdOut or StdErr text stream objects.

strText

String value indicating the text you want to write to the stream.

Expand image 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.

Expand image Example

The following code demonstrates the use of the Write method.

Visual Basic Script CopyCode image Copy Code
Dim strInput
strInput = WScript.StdIn.ReadAll
WScript.StdOut.Write strInput
JScript CopyCode image Copy Code
var strInput = WScript.StdIn.ReadAll();
WScript.StdOut.Write(strInput);

Applies To:

StdErr Property (WScript)| StdOut Property (WScript)

Expand image See Also

Reference

TextStream Object


WriteBlankLines Method (Windows Script Host)

Windows Script Host
WriteBlankLines Method (Windows Script Host)
See Also Example
CollapseAll image DropDown image

Sends a specified number of blank lines (newline characters) to an output stream.

object.WriteBlankLines(intLines)

Expand image Arguments

object

StdOut or StdErr text stream objects.

intLines

Integer value indicating the number of blank lines you want to write to the stream.

Expand image 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.

Expand image Example

The following code demonstrates the WriteBlankLines method.

Visual Basic Script CopyCode image Copy Code
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 CopyCode image Copy Code
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);
}

Applies To:

StdErr Property (WScript)| StdOut Property (WScript)

Expand image See Also

Reference

WriteLine Method (Windows Script Host)
TextStream Object


WriteLine Method (Windows Script Host)

Windows Script Host
WriteLine Method (Windows Script Host)
See Also Example
CollapseAll image DropDown image

Sends a string with a newline character to an output stream.

object.WriteLine([strText])

Expand image 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.

Expand image 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.

Expand image Example

The following code demonstrates the WriteLine method.

Visual Basic Script CopyCode image Copy Code
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 CopyCode image Copy Code
var stdin = WScript.StdIn;
var stdout = WScript.StdOut;

while (!stdin.AtEndOfStream)
{
     var str = stdin.ReadLine();
     stdout.WriteLine("Line " + (stdin.Line - 1) + ": " + str);
}

Applies To:

StdErr Property (WScript)| StdOut Property (WScript)

Expand image See Also

Reference

WriteBlankLines Method (Windows Script Host)
TextStream Object


Events

Windows Script Host
Events
DropDown image

The following sections include information about the events of Windows Script Host.

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.

Windows Script Host Basics

Learn the basics of WSH.


End Event

Windows Script Host
End Event
See Also Example
CollapseAll image DropDown image

Event that is fired when the remote script completes.

Object_end

Parameters

object

WshRemote object.

Expand image 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.

Expand image Example

CopyCode image Copy Code
var WshController = new ActiveXObject("WSHController");
var RemoteProc = WshController.CreateScript("app.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");
}

Applies To:

WshRemote Object

Expand image See Also

Reference

WshController Object
Status Property (WshRemote)
Error Property (WshRemote)
Execute Method (Windows Script Host)
Terminate Method (WshScriptExec)
Start Event
Error Event


Error Event

Windows Script Host
Error Event
See Also Example
CollapseAll image DropDown image

Event that is fired when an error occurs in the remote script.

Object_Error

Parameters

object

WshRemote object.

Expand image 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).

Expand image Example

CopyCode image Copy Code
var WshController = new ActiveXObject("WSHController");
var RemoteProc = WshController.CreateScript("app.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");
}

Applies To:

WshRemote Object

Expand image See Also

Reference

WshController Object
WshRemoteError Object
Status Property (WshRemote)
Error Property (WshRemote)
Execute Method (Windows Script Host)
Terminate Method (WshScriptExec)
Start Event
End Event


Start Event

Windows Script Host
Start Event
See Also Example
CollapseAll image DropDown image

Event that is fired when the remote script begins executing.

Object_Start

Parameters

object

WshRemote object.

Expand image Remarks

The Start event is fired when the Execute method is called.

Expand image Example

CopyCode image Copy Code
var WshController = new ActiveXObject("WSHController");
var RemoteProc = WshController.CreateScript("app.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");
}

Applies To:

WshRemote Object

Expand image See Also

Reference

WshController Object
Status Property (WshRemote)
Error Property (WshRemote)
Execute Method (Windows Script Host)
Terminate Method (WshScriptExec)
End Event
Error Event


Error Messages (Windows Script Host)

Windows Script Host
Error Messages (Windows Script Host)
DropDown image

Here is a list of the errors messages you may encounter when running scripts in the Windows Script Host 5.6 environment.

In This Section

//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 execute remote script.

Unable to find job <job identifier>.

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 wait for process.

Unable to write to wsh.log. Please check with your administrator.

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.

Windows Script Host Basics

Learn the basics of WSH.


//E option requires name of script engine.

Windows Script Host
//E option requires name of script engine.
See Also

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

Reference

There is no script engine for file extension <file extension>.


//H option requires host name.

Windows Script Host
//H option requires host name.
See Also

You failed to specify the default host name.

To correct this error

  • Specify the default host name when using the //H option.

See Also

Reference

Host name for //H option must be "cscript" or "wscript".


//T option requires timeout value.

Windows Script Host
//T option requires timeout value.
See Also

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

Reference

Invalid timeout value for //T option.
Script execution time was exceeded on script <script name>. <script name> execution was terminated.


A duplicate name for a named or unnamed element was encountered.

Windows Script Host
A duplicate name for a named or unnamed element was encountered.
See Also

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

Reference

WshArguments Object
WshNamed Object
WshUnnamed Object
<named> Element


An attempt at saving your settings via the //S option failed.

Windows Script Host
An attempt at saving your settings via the //S option failed.
See Also

Again this is usually a systems permissions issue.

To correct this error

  • Consult your Administrator about potential network or security problems.

See Also

Reference

Can't change default script host <host name>.

Concepts

Setting and Customizing Script Properties (.wsh)


Can't change default script host <host name>.

Windows Script Host
Can't change default script host <host name>.
See Also

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

Reference

An attempt at saving your settings via the //S option failed.


Can't find script engine <engine name> for script.

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

  1. Consult your Administrator about potential network or security problems.

  2. Make sure that the particular script engine is installed or that you are specifying the correct script engine.

  3. Check your spelling.


Can't find script file <script file name>.

Windows Script Host
Can't find script file <script file name>.
See Also

You have given an incorrect path or the script file is not there.

To correct this error

  1. Check the path given and correct it.

  2. Make sure that the file is actually there

See Also

Reference

Invalid pathname.


Can't read script from stdin.

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.


Can't save settings.

Windows Script Host
Can't save settings.
See Also

Unable to save the control file (*.wsh) for this script.

To correct this error

  1. 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.

  2. Consult your Administrator about potential network or security problems.

See Also

Concepts

Setting and Customizing Script Properties (.wsh)


Command line option mismatch.

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.


Could not connect object <object name>.

Windows Script Host
Could not connect object <object name>.
See Also

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

Reference

<object> Element (Windows Script Host)
WScript Object


Could not locate automation class name <automation class name>.

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

  1. Make sure the automation class that you created is installed.

  2. Consult your Administrator about potential network or security problems.


Execution of the Windows Script Host failed.

Windows Script Host
Execution of the Windows Script Host failed.
See Also

Usually, this is a systems permissions issue.

To correct this error

  • Consult your Administrator about potentially serious network or security problems.

See Also

Reference

Loading script <script name> failed.


Host name for //H option must be "cscript" or "wscript".

Windows Script Host
Host name for //H option must be "cscript" or "wscript".
See Also

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

Reference

//H option requires host name.


Initialization of the Windows Script Host failed.

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.


Invalid attempt to call Exec without a command.

Windows Script Host
Invalid attempt to call Exec without a command.
See Also

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

Reference

Exec Method (Windows Script Host)


Invalid pathname.

Windows Script Host
Invalid pathname.
See Also

You have given an incorrect path.

To correct this error

  • Check the path given and correct it.

See Also

Reference

Can't find script file <script file name>.


Invalid root in registry key <name> for reading.

Windows Script Host
Invalid root in registry key <name> for reading.
See Also

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

Reference

RegRead Method
RegWrite Method
RegDelete Method


Invalid syntax in URL<name>.

Windows Script Host
Invalid syntax in URL<name>.
See Also

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

Reference

WshUrlShortcut Object


Invalid timeout value for //T option.

Windows Script Host
Invalid timeout value for //T option.
See Also

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

Reference

//T option requires timeout value.
Script execution time was exceeded on script <script name>. <script name> execution was terminated.


Loading script <script name> failed.

Windows Script Host
Loading script <script name> failed.
See Also

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

Reference

Loading your settings failed.


Loading your settings failed.

Windows Script Host
Loading your settings failed.
See Also

Usually, this is a systems permissions issue.

To correct this error

  • Consult your Administrator about potentially serious network or security problems.

See Also

Reference

Loading script <script name> failed.


Missing job name.

Windows Script Host
Missing job name.
See Also

You have failed to specify the job name.

To correct this error

  • Specify the job name.

See Also

Reference

Unable to find job <job identifier>.


Protocol handler for <name> not found.

Windows Script Host
Protocol handler for <name> not found.
See Also

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

Reference

WshUrlShortcut Object


Remote script object can only be executed once.

Windows Script Host
Remote script object can only be executed once.
See Also

You are attempting to rerun a remote script object.

To correct this error

  • Create another remote script object and run it instead.

See Also

Reference

WshRemote Object


Script execution time was exceeded on script <script name>. <script name> execution was terminated.

Windows Script Host
Script execution time was exceeded on script <script name>. <script name> execution was terminated.
See Also

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

Reference

//T option requires timeout value.
Invalid timeout value for //T option.


Script setting file <settings filename>is invalid.

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.


The shortcut pathname must end with .lnk or .url

Windows Script Host
The shortcut pathname must end with .lnk or .url
See Also

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

Reference

WshShortcut Object
WshUrlShortcut Object


There is no file extension in <file name>.

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 to include a correct file extension that is appropriate to the scripting language you wish to use, along with the file name.


There is no printer called <name>.

Windows Script Host
There is no printer called <name>.
See Also

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

  1. Check the names of the currently installed printers and make sure the specified printer is installed.

  2. Check the spelling of the printer path for typing errors.

  3. Make sure the networked printer is online.

See Also

Reference

SetDefaultPrinter Method
EnumPrinterConnections Method
AddWindowsPrinterConnection Method


There is no script engine for file extension <file extension>.

Windows Script Host
There is no script engine for file extension <file extension>.
See Also

This file extension is not mapped to a script engine.

To correct this error

  1. Check your file extension and also the spelling of your scripting language designation.

  2. Use //E to designate a script engine.

See Also

Reference

//E option requires name of script engine.


There is no script file specified.

Windows Script Host
There is no script file specified.
See Also

You have failed to specify a script file.

To correct this error

  • Specify the appropriate script file.

See Also

Reference

Unknown option <option designation> specified.


Unable to execute - arguments list too long.

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 Note

The maximum command-line length that your system allows determines the number of files you can drag onto a script.


Unable to execute remote script.

Windows Script Host
Unable to execute remote script.
See Also

The script failed to initialize.

To correct this error

  • Consult your Administrator about potential network or security problems.

See Also

Reference

WshRemote Object


Unable to find job <job identifier>.

Windows Script Host
Unable to find job <job identifier>.
See Also

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

Reference

<job> Element

Concepts

Using Windows Script Files (.wsf)


Unable to open registry key <name> for reading.

Windows Script Host
Unable to open registry key <name> for reading.
See Also

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

Reference

RegRead Method


Unable to remove environment variable <name>.

Windows Script Host
Unable to remove environment variable <name>.
See Also

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

Reference

Remove Method (Windows Script Host)
WshEnvironment Object


Unable to remove registry key <name>.

Windows Script Host
Unable to remove registry key <name>.
See Also

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

Reference

RegDelete Method
RegRead Method
RegWrite Method


Unable to save shortcut <name>.

Windows Script Host
Unable to save shortcut <name>.
See Also

This error generally occurs when the name of the shortcut already exists or is a read-only file.

To correct this error

  1. Change the read-only attribute to read/write.

  2. Rename your shortcut to something unique.

  3. Change the name of the existing shortcut.

See Also

Reference

WshShortcut Object
WshUrlShortcut Object


Unable to set shortcut target to <name>.

Windows Script Host
Unable to set shortcut target to <name>.
See Also

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

  1. Use a valid protocol handler.

  2. Check the spelling of the protocol handler being used.

  3. Contact your system administrator to make sure the protocol handler is properly installed.

  4. Consult your Administrator about potential network or security problems.

See Also

Reference

WshUrlShortcut Object


Unable to wait for process.

Windows Script Host
Unable to wait for process.
See Also

This error generally occurs when the script is held 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

  1. Execute the program directly instead of using a shortcut.

  2. Check the shortcut link to be sure it is still current.

See Also

Reference

Run Method (Windows Script Host)


Unable to write to wsh.log. Please check with your administrator.

Windows Script Host
Unable to write to wsh.log. Please check with your administrator.
See Also

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

Reference

LogEvent Method


Unicode is not supported on this platform.

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.


Unknown option <option designation> specified.

Windows Script Host
Unknown option <option designation> specified.
See Also

You have specified an option that is invalid for Windows script host.

To correct this error

  1. Use the Windows script host option appropriate to the script language you are using or specify another supported script language.

  2. Also check your spelling.

See Also

Reference

There is no script file specified.


Windows Script Host access is disabled on this machine. Contact your administrator for details.

Windows Script Host
Windows Script Host access is disabled on this machine. Contact your administrator for details.
See Also

Usually, this is a systems permissions issue.

To correct this error

  • Consult your Administrator about potential network or security problems.

See Also

Reference

Execution of the Windows Script Host failed.


Windows Script Interfaces

Microsoft Windows Script Interfaces
Windows Script Interfaces
DropDown image

The following are the Windows Script interface introductions.

In This Section

Microsoft Windows Script Interfaces-Introduction

Explains how Windows script interfaces are used in Windows script technologies.

Windows Script Interfaces Reference

Describes the interfaces available when creating script hosts and script engines.


Microsoft Windows Script Interfaces-Introduction

Microsoft Windows Script Interfaces
Microsoft Windows Script Interfaces-Introduction
See Also
DropDown image

Microsoft® Windows® Script Interfaces introduce a new way for an application to add scripting and OLE Automation capabilities. With the advent of the interfaces, hosts can call upon disparate scripting engines from multiple sources and vendors to perform scripting between components. The implementation of the script itself—language, syntax, persistent format, execution model, and so on—is left to the script vendor. The designers have taken care to allow hosts that rely on Windows Script to use arbitrary language back ends.

Windows Script Hosts

Windows Script Engines

Active Script Debugging Overview

Windows Script Terms

This list contains definitions of the scripting-related terms used in this document.

Term | Definition
Code object | An instance created by the scripting engine that is associated with a named item, such as the module behind a form in Visual Basic®, or a C++ class associated with a named item. Preferably, this is an OLE Component Object Model (COM) object that supports OLE Automation so the host or other nonscript entity can manipulate the code object.
Named item | An OLE COM object (preferably one that supports OLE Automation) that the host deems interesting to the script. Examples include the HTML Page and Browser in a Web browser, and the Document and Dialogs in Microsoft Word.
Script | The data that makes up the program that the scripting engine runs. A script can be any contiguous executable data, including pieces of text, blocks of pcode, or even machine-specific executable byte codes. A host loads a script into the scripting engine through one of the IPersist* interfaces or through the IActiveScriptParse interface.
Scripting engine | The OLE object that processes scripts. A scripting engine implements the IActiveScript and, optionally, IActiveScriptParse interfaces.
Scripting host | The application or program that owns the Windows Script engine. The host implements the IActiveScriptSite and, optionally, IActiveScriptSiteWindow interfaces.
Scriptlet | A portion of a script that gets attached to an object through the IActiveScriptParse interface. The aggregate collection of scriptlets is the script.
Script language | The language in which a script is written (VBScript, for example) and the semantics of that language.

Windows Script Background

Windows Script components fall into two categories: Windows Script hosts and Windows Script engines. A host creates a scripting engine and calls on the engine to run the scripts. Examples of Windows Script hosts include:

  • Microsoft Internet Explorer

  • Internet authoring tools

  • Shell

Windows Script engines can be developed for any language or run-time environment, including:

  • Microsoft Visual Basic Scripting Edition (VBScript)

  • Perl

  • Lisp

To make implementation of the host as flexible as possible, an OLE Automation wrapper for Windows Script is provided. However, a host that uses this wrapper object to instantiate the scripting engine does not have the degree of control over the run-time name space, the persistence model, and so on, that it would if it used Windows Script directly.

The Windows Script design isolates the interface elements required only in an authoring environment so that nonauthoring hosts (such as browsers and viewers) and script engines (for example, VBScript) can be kept lightweight.

Windows Script Basic Architecture

The following illustration shows the interaction between an Windows Script host and an Windows Script engine.

Following is a description of the steps involved in the interaction between the host and engine. The actual nesting of the function calls is omitted for clarity.

  1. Create a Project. The host loads a project or document. (This step is not particular to Windows Script, but is included here for completeness.)

  2. Create the Windows Script Engine. The host calls CoCreateInstance to create a new Windows Script engine, specifying the class identifier (CLSID) of the specific scripting engine to use. For example, the HTML browsing component of Internet Explorer receives the scripting engine's class identifier through the CLSID= attribute of the HTML <OBJECT> tag.

  3. Load the Script. If the script contents have been persisted, the host calls the script engine's IPersist*::Load method to feed it the script storage, stream, or property bag. Otherwise, the host uses either the IPersist*::InitNew or IActiveScriptParse::InitNew method to create a null script. A host that maintains a script as text can use IActiveScriptParse::ParseScriptText to feed the scripting engine the text of the script, after calling IActiveScriptParse::InitNew.

  4. Add Named Items. For each top-level named item (such as pages and forms) imported into the scripting engine's name space, the host calls the IActiveScript::AddNamedItem method to create an entry in the engine's name space. This step is not necessary if top-level named items are already part of the persistent state of the script loaded in step 3. A host does not use IActiveScript::AddNamedItem to add sublevel named items (such as controls on an HTML page); rather, the engine indirectly obtains sublevel items from top-level items by using the host's ITypeInfo and IDispatch interfaces.

  5. Run the Script. The host causes the engine to start running the script by setting the SCRIPTSTATE_CONNECTED flag in the IActiveScript::SetScriptState method. This call would likely perform any scripting engine construction work, including static binding, hooking up to events (see below), and executing code, in a way similar to a scripted main() function.

  6. Get Item Information. Each time the script engine needs to associate a symbol with a top-level item, it calls the IActiveScriptSite::GetItemInfo method, which returns information about the given item.

  7. Hook Up Event Advise. Before starting the actual script, the scripting engine connects to the events of all the relevant objects through the IConnectionPoint interface.

  8. Invoke Properties and Methods. As the script runs, the scripting engine realizes references to methods and properties on named objects through IDispatch::Invoke or other standard OLE binding mechanisms.

See Also

Other Resources

Windows Script Interfaces


Windows Script Hosts

Microsoft Windows Script Interfaces
Windows Script Hosts
See Also
DropDown image

When implementing Microsoft® Windows® Script host, you can safely assume that a scripting engine only calls the IActiveScriptSite interface in the context of the base thread as long as the host does the following:

  • Chooses a base thread (generally the thread that contains the message loop).

  • Instantiates the scripting engine in the base thread.

  • Calls scripting engine methods only from the base thread, except where specifically allowed, as in the cases of IActiveScript::InterruptScriptThread and IActiveScript::Clone.

  • Calls the scripting engine's dispatch object only from the base thread.

  • Ensures that the message loop runs in the base thread if a window handle is provided.

  • Ensures that objects in the host's object model only source events in the base thread.

These rules are automatically followed by all single-threaded hosts. The restricted model described above is intentionally loose enough to allow a host to abort a stuck script by calling IActiveScript::InterruptScriptThread from another thread (initiated by a CTRL+BREAK handler or the like), or to duplicate a script in a new thread using IActiveScript::Clone.

Remarks

None of these restrictions apply to a host that chooses to implement a free-threaded IActiveScriptSite interface and a free-threaded object model. Such a host can use the IActiveScript interface from any thread, without restriction.

See Also

Concepts

Microsoft Windows Script Interfaces-Introduction


Windows Script Engines

Microsoft Windows Script Interfaces
Windows Script Engines
See Also
DropDown image

To implement a Microsoft® Windows® Script engine, create an OLE COM object that supports the following interfaces.

Interface

Description

IActiveScript

Provides the basic scripting ability. Implementation of this interface is required.

IActiveScriptParse

Provides the ability to add script text, evaluate expressions, and so on. Implementation of this interface is optional; however, if it is not implemented, the script engine must implement one of the IPersist* interfaces in order to load a script.

IPersist*

Provides persistence support. Implementation of at least one of the following interfaces is required if IActiveScriptParse is not implemented.

Interface | Description
IPersistStorage | Provides support for the DATA={url} attribute in the OBJECT tag.
IPersistStreamInit | Provides support for the same as IPersistStorage as well as the DATA="string-encoded byte stream" attribute in the OBJECT tag.
IPersistPropertyBag | Provides support for the PARAM= attribute in the OBJECT tag.
Note Note

: It is possible that the scripting engine will never be called upon to save or restore a script state through IPersist*. Instead, IActiveScriptParse is used by calling IActiveScriptParse::InitNew to create a blank script, then scriptlets are added and connected to events with IActiveScriptParse::AddScriptlet and general code is added with IActiveScriptParse::ParseScriptText . Nonetheless, a scripting engine should fully implement at least one IPersist* interface (preferably IPersistStreamInit), because other host applications may try to make use of them.

The following sections describe implementing a Windows Scripting engine in more detail.

See the Windows Script Interfaces Reference for more information.

Registry Standard

A Windows Script engine can identify itself using component categories. Windows Script currently defines two component categories.

Category | Description
CATID_ActiveScript | Indicates that the class identifiers (CLSIDs) are Windows Script engines that support, at a minimum, the IActiveScript interface and a persistence mechanism (the IPersistStorage, IPersistStreamInit, or IPersistPropertyBag interface).
CATID_ActiveScriptParse | Indicates that the CLSIDs are Windows Script engines that support, at a minimum, the IActiveScript and IActiveScriptParse interfaces.

Although IActiveScriptParse is not a true persistence mechanism, it does support the IActiveScriptParse::InitNew method that is functionally equivalent to IPersist*::InitNew.

Script Engine States

At any given time, a Windows Script engine can be in one of several states.

State

Description

uninitialized

The script has not been initialized or loaded using an IPersist* interface, or does not have an IActiveScriptSite interface set. The scripting engine is generally not usable from this state until the script is loaded.

initialized

The script has been initialized with an IPersist* interface and has an IActiveScriptSite interface set, but is not connected to host objects and sinking events. Note that this state simply means that the IPersist*::Load, IPersist*::InitNew, or IActiveScriptParse::InitNew method has been completed, and that the IActiveScript::SetScriptSite method has been called. The engine cannot run code in this mode. The engine queues code that the host passes to it through the IActiveScriptParse::ParseScriptText method, and executes the code after transitioning to the started state.

Because languages can vary widely in semantics, scripting engines are not required to support this state transition. Engines that support the IActiveScript::Clone method must, however, support this state transition. Hosts must prepare for this transition and take the appropriate action: release the current scripting engine, create a new scripting engine, and call IPersist*::Load, IPersist*::InitNew, or IActiveScriptParse::InitNew (and possibly also call IActiveScriptParse::ParseScriptText ). Use of this transition should be considered an optimization of the above steps. Note that any information the scripting engine has obtained about the names of Named Items and the type information describing Named Items remains valid.

Because languages vary widely, defining the exact semantics of this transition is difficult. At a minimum, the scripting engine must disconnect from all events, and release all of the SCRIPTINFO_IUNKNOWN pointers obtained by calling the IActiveScriptSite::GetItemInfo method. The engine must re-obtain these pointers after the script is run again. The scripting engine should also reset the script back to an initial state that is appropriate for the language. VBScript, for example, resets all variables and retains any code added dynamically by calling IActiveScriptParse::ParseScriptText with the SCRIPTTEXT_ISPERSISTENT flag set. Other languages may need to retain current values (such as Lisp because there is no code/data separation) or reset to a well-known state (this includes languages with statically initialized variables).

Note that the transition to the started state should have the same semantics (that is, it should leave the scripting engine in the same state) as calling IPersist*::Save to save the scripting engine, and then calling IPersist*::Load to load a new scripting engine; these actions should have the same semantics as IActiveScript::Clone. Scripting engines that do not yet support IActiveScript::Clone or IPersist* should carefully consider how the transition to the started state should behave, so that such a transition would not violate the above conditions if IActiveScript::Clone or IPersist* support was later added.

During this transition to the started state, the scripting engine will disconnect from event sinks after the appropriate destructors, and so on, are executed in the script. To avoid having these destructors executed, the host can first move the script into the disconnected state before moving into the started state.

Use IActiveScript::InterruptScriptThread to cancel a running script thread without waiting for current events, and so on, to finish running.

started

The transition from the initialized state to the started state causes the engine to execute any code that was queued in the initialized state. The engine can execute code while in the started state, but it is not connected to any events added through the IActiveScript::AddNamedItem method. The engine can execute code by calling the IDispatch interface obtained from the IActiveScript::GetScriptDispatch method, or by calling IActiveScriptParse::ParseScriptText. It is possible that further background initialization (progressive loading) is still ongoing, and that calling the IActiveScript::SetScriptState method with the SCRIPTSTATE_CONNECTED flag set may cause the script to block until initialization is complete.

connected

The script is loaded and connected for sinking events from host objects. If this is a transition from the initialized state, the scripting engine should transition through the started state, performing the necessary actions, before entering the connected state and connecting to events.

disconnected

The script is loaded and has a run-time state, but is temporarily disconnected from sinking events from host objects. This can be done either logically (ignoring events received) or physically (calling IConnectionPoint::Unadvise on the appropriate connection points). If this is a transition from the initialized state, the scripting engine should transition through the started state, performing the necessary actions, before entering the disconnected state. Event sinks that are in progress are completed before the state changes (use IActiveScript::InterruptScriptThread to cancel a running script thread). This state is distinguished from the initialized state in that the transition to this state does not cause the script to reset, the run-time state of the script is not reset, and a script initialization procedure is not executed.

closed

The script has been closed. The scripting engine no longer works and returns errors for most methods.

The following illustration shows the relationships between the various scripting engine states, and shows the methods that cause transitions from one state to another.

The following illustration shows the actions that the scripting engine performs during the various state transitions.

Scripting Engine Threading

Because a Windows Script engine can be used in many environments, it is important to keep its execution model as flexible as possible. For example, a server-based host may need to preserve a multithreaded design while using Windows Script in an efficient manner. At the same time, a host that does not use threading, such as a typical application, should not be burdened with threading management. Windows Script achieves this balance by restricting the ways a free-threaded scripting engine can call back to the host, freeing hosts from this burden.

Scripting engines used on servers are typically implemented as free-threading COM objects. This means that methods on the IActiveScript interface and its associated interfaces can be called from any thread in the process, without marshaling. (Unfortunately, this also means that the scripting engine must be implemented as an in-process server, because OLE does not currently support interprocess marshaling of free-threaded objects.) Synchronization is the responsibility of the scripting engine. For scripting engines that are not internally reentrant, or for language models that are not multithreaded, synchronization could be as simple as serializing access to the scripting engine with a mutex. Of course certain methods, such as IActiveScript::InterruptScriptThread, should not be serialized in this way so that a stuck script can be terminated from another thread.

The fact that IActiveScript is typically free-threaded generally implies that the IActiveScriptSite interface and the host's object model should be free-threaded as well. This would make implementation of the host quite difficult, particularly in the common case where the host is a single-threaded Microsoft Windows®-based application with single-threaded or apartment-model ActiveX Controls in its object model. For this reason, the following constraints are placed on the scripting engine's use of IActiveScriptSite:

The script site is always called in the context of a host thread. That is, the scripting engine never calls the script site in the context of a thread that the scripting engine created, but only from within a scripting engine method that was called from the host through IActiveScript and its derivatives, through the exposed scripting engine's dispatch object, through a Windows message, or from an event source in the host's object model.

The script site is never called from within the context of a simple thread state control method (for example, the IActiveScript::InterruptScriptThread method) or from the IActiveScript::Clone method.

See Also

Concepts

Microsoft Windows Script Interfaces-Introduction


Active Script Debugging Overview

Microsoft Windows Script Interfaces
Active Script Debugging Overview
See Also
DropDown image

The Active Script Debugging interfaces allow language-neutral, host-neutral debugging, and support a wide variety of development environments.

Figure 1

Script Host Process

A language-neutral debugging environment can support any programming language or mix of programming languages, without having specific knowledge of any of those languages. The debugging environment also supports cross-language stepping and breakpoints. (This overview focuses primarily on support scripting languages, such as VBScript and JScript.)

A host-neutral debugger can be automatically used with any Active Scripting host, such as Internet Explorer or a custom host. The host controls what the debugger presents to the user, from the structure of the document tree to the contents and syntax coloring of the debug documents. This allows the debugged source code to be shown in the context of the host document. For example, Internet Explorer can show a script in an HTML page.

In the subsections below, each key component in Active Debugging and its associated interfaces are discussed. However, before proceeding further, several key Active Debugging concepts must be defined:

host application

The application that hosts the script engines and provides a scriptable set of objects (or "object model").

language engine

A component that provides parsing, execution, and debugging abstractions for a particular language.

debugger IDE

The application that provides debugging UI by communicating with the host application and language engines.

machine debug manager

A component that maintains a registry of debuggable application processes.

process debug manager

A component that maintains the tree of debuggable documents for a particular application, tracks the running threads, and so on.

document context

A document context is an abstraction representing a specific range in the source code of a host document.

code context

A code context represents a particular location in the running code of a language engine (a "virtual instruction pointer".)

expression context

A particular context (for example, a stack frame) in which expressions may be evaluated by a language engine.

object browsing

A structured, language-independent representation of an object's name, type, value, and sub-objects, suitable for implementing a "watch window" UI.

Below is an overview of each of the key Active Debugging components and corresponding, associated interfaces, followed by the details of those interfaces.

Language Engine

The language engine provides:

  • Language parsing and execution.

  • Debugging support (breakpoints and so on).

  • Expression evaluation.

  • Syntax coloring.

  • Object browsing.

  • Stack enumeration and parsing.

Below are the interfaces that a script engine needs to support to provide debugging, expression evaluation, and object browsing. These interfaces are used by the host application to map between its document context and the engine's code contexts, and also by the debugger UI to do expression evaluation, stack enumeration, and object browsing.

IActiveScriptDebug Interface

Provides syntax coloring and code context enumeration.

IActiveScriptErrorDebug Interface

Returns document contexts and stack frames for errors.

IActiveScriptSiteDebug Interface

Host provided link from script engine to debugger.

IDebugCodeContext Interface

Provides a virtual "instruction pointer" in a thread.

IEnumDebugCodeContexts Interface

Enumerates the code contexts that correspond to a document context.

IDebugStackFrame Interface

Represents a logical stack frame on the thread stack.

IDebugExpressionContext Interface

Provides context in which expressions can be evaluated.

IDebugStackFrameSniffer Interface

Provides a way to enumerate the logical stack frames known by a component.

IDebugExpression Interface

Represents an asynchronously evaluated expression.

IDebugSyncOperation Interface

Allows a script engine to abstract an operation that needs to be performed while nested in a particular blocked thread.

IDebugAsyncOperation Interface

Provides asynchronous access to a synchronous debug operation.

IDebugAsyncOperationCallBack Interface

Provides status events related to progress of an IDebugAsyncOperation interface evaluation.

IEnumDebugExpressionContexts Interface

Enumerates a collection of IDebugExpressionContexts objects.

IProvideExpressionContexts Interface

Provides a way to enumerate expression contexts known by a certain component.

IDebugFormatter Interface

Allows a language or IDE to customize the conversion between VARIANT values or VARTYPE types and strings.

IDebugStackFrameSnifferEx Interface

Enumerates the logical stack frames known by a component for the PDM.

Hosts

The host:

  • Hosts the language engines.

  • Provides an object model (set of objects that can be scripted).

  • Defines a tree of documents that can be debugged and their contents.

  • Organizes scripts into virtual applications.

There are two kinds of hosts:

  • A dumb host supports just the basic Active Scripting interfaces. It has no control over document structure or organizations; this is determined entirely by the scripts provided to the language engines.

  • A smart host supports a larger set of interfaces that allows it to define the document tree, document contents, and syntax coloring. There is a set of helper interfaces, described in the next subsection, which make it much easier for a host to be a smart host.

Smart-host Helper Interfaces

The IDebugDocumentHelper methods provide a greatly simplified set of interfaces that a host can use to gain the benefits of smart-hosting without handling the full complexity (and power) of the full host interfaces.

A host is not required to use these interfaces, of course. However using these interfaces can avoid implementing or using a number of more complicated interfaces.

IDebugDocumentHelper Interface

Implemented by PDM and provides implementations for many interfaces necessary for smart hosting.

IDebugDocumentHost Interface

Implemented (optionally) by the host to expose host-specific functionality, such as syntax coloring, to the debugger.

For more information, see Implementing Smart Host Helper Interfaces.

Full Smart-host Interfaces

Below is the full set of interfaces that a smart-host must implement or use if it is not using the helper interfaces.

Interfaces implemented by host:

IDebugDocumentInfo Interface

Provides information on a document, which may or may not be instantiated.

IDebugDocumentProvider Interface

Provides the means for instantiating a document on demand.

IDebugDocument Interface

The base interface for all debug documents.

IDebugDocumentText Interface

Provides access to a text-only version of the debug document.

IDebugDocumentTextAuthor Interface

Allows editing of the text-only version of the debug document.

IDebugDocumentContext Interface

Provides an abstract representation of a portion of the document being debugged.

Interfaces implemented by PDM on behalf of the host:

IDebugApplicationNode Interface

Extends the functionality of the IDebugDocumentProvider interface by providing a context within a project tree.

Debugger IDE

The IDE is a language-independent debugging UI. It provides:

  • Document viewers/editors.

  • Breakpoint management.

  • Expression evaluation and watch windows.

  • Stack frame browsing.

  • Object/Class browsing.

  • Browsing the virtual application structure.

Interfaces implemented by the debugger:

IApplicationDebugger Interface

The primary interface exposed by a debugger IDE session.

IApplicationDebuggerUI Interface

Gives an external component more control over the user interface (UI) of the debugger.

IDebugExpressionCallBack Interface

Provides status events for IDebugExpression evaluation progress.

IDebugDocumentTextEvents Interface

Provides events indicating changes to the associated text document.

IDebugApplicationNodeEvents Interface

Provides the event interface for the IDebugApplicationNode interface.

Machine Debug Manager

The machine debug manager provides the hookup point between virtual applications and debuggers by maintaining and enumerating a list of active virtual applications.

IDebugSessionProvider Interface

Establishes a debug session for a running application.

IMachineDebugManager Interface

The primary interface to the machine debug manager.

IMachineDebugManagerCookie Interface

Similar to the IMachineDebugManager interface, but this interface supports debug cookies.

IMachineDebugManagerEvents Interface

Signals changes in the running application list maintained by the machine debug manager.

IEnumRemoteDebugApplications Interface

Enumerates the running applications on a machine.

Process Debug Manager

The PDM does the following:

  • Synchronizes the debugging of multiple language engines.

  • Maintains a tree of debuggable documents.

  • Merges stack frames.

  • Coordinates breakpoints and stepping across language engines.

  • Tracks threads.

  • Maintains a debugger thread for asynchronous processing.

  • Communicates with the machine debug manager and the debugger IDE.

Following are the interfaces provided by the process debug manager.

IProcessDebugManager Interface

Primary interface to the process debug manager. This interface can create, add, or remove a virtual application from a process.

IRemoteDebugApplication Interface

Represents a running application.

IDebugApplication Interface

Exposes non-remotable debugging methods for use by language engines and hosts.

IRemoteDebugApplicationThread Interface

Represents a thread of execution within a particular application.

IDebugApplicationThread Interface

Allows language engines and hosts to provide thread synchronization and to maintain thread-specific, debug-state information.

IEnumRemoteDebugApplicationThreads Interface

Enumerates the running threads in an application.

IDebugThreadCall Interface

Dispatches marshaled calls.

IDebugApplicationNode Interface

Maintains a position for a document in the hierarchy.

IEnumDebugApplicationNodes Interface

Enumerates child nodes of a node associated with an application.

IEnumDebugStackFrames Interface

Enumerates the stack frames corresponding to a thread, merged from the engines.

IDebugCookie Interface

Allows the debug cookie to be set in script debuggers.

IDebugHelper Interface

Serves as a factory for object browsers and simple connection points for script engines.

ISimpleConnectionPoint Interface

Provides a simple way for describing and enumerating the events fired on a particular connection point, for script engines.

See Also

Other Resources

Active Script Debugger Interfaces


Implementing Smart Host Helper Interfaces

Microsoft Windows Script Interfaces
Implementing Smart Host Helper Interfaces
See Also
DropDown image

The IDebugDocumentHelper Interface interface greatly simplifies the task of creating a smart host for Active Debugging, because it provides implementations for many interfaces necessary for smart hosting.

To be a smart host using IDebugDocumentHelper, a host application must do only three things:

  1. CoCreate the Process Debug Manager, and use the IProcessDebugManager Interface interface to add your application to the list of debuggable applications.

  2. Create a debug document helper for each script object, using the IProcessDebugManager::CreateDebugDocumentHelper method. Make sure that the document name, parent document, text, and script blocks are defined.

  3. Implement the IActiveScriptSiteDebug Interface interface on your object that implements the IActiveScriptSite interface (which is needed for Active Scripting). The only non-trivial method on the IActiveScriptSiteDebug interface simply delegates to the helper.

Optionally, the host can implement the IDebugDocumentHost Interface interface if it needs additional control over syntax color, document context creation, and other extended functionality.

The main limitation on the smart host helper is that it can only handle documents whose contents change or shrink after they have been added (although documents can expand). For many smart hosts, however, the functionality it provides is exactly what is needed.

The following sections explain each step in more detail.

Create an Application Object

Before the smart host helper can be used, it is necessary to create an IDebugApplication Interface object to represent your application in the debugger.

To create an application object

  1. Create an instance of the process debug manager using CoCreateInstance.

  2. Call IProcessDebugManager::CreateApplication.

  3. Set the name on the application by using IDebugApplication::SetName.

  4. Add the application object to the list of debuggable applications by using IProcessDebugManager::AddApplication.

    The code below outlines the process, but it does not include error checking or other robust programming techniques.

    CopyCode image Copy Code
    CoCreateInstance(CLSID_ProcessDebugManager, NULL,
      CLSCTX_INPROC_SERVER | CLSCTX_INPROC_HANDLER
      | CLSCTX_LOCAL_SERVER,
IID_IProcessDebugManager, (void **)&g_ppdm);
g_ppdm->CreateApplication(&g_pda);
g_pda->SetName(L"My cool application");
g_ppdm->AddApplication(g_pda, &g_dwAppCookie);

Using IDebugDocumentHelper

To use the helper (minimal sequence of steps)

  1. For each host document, create a helper using IProcessDebugManager::CreateDebugDocumentHelper.

  2. Call IDebugDocumentHelper::Init on the helper, giving the name, document attributes, and so on.

  3. Call IDebugDocumentHelper::Attach with parent helper for the document (or NULL if the document is the root) to define the position of the document in the tree and make it visible to the debugger.

  4. Call IDebugDocumentHelper::AddDBCSText or IDebugDocumentHelper::AddUnicodeText to define the text of the document. (These can be called multiple times if document is downloaded incrementally, as in the case of a browser.)

  5. Call IDebugDocumentHelper::DefineScriptBlock to define the ranges for each script block and the associated script engines.

Implementing IActiveScriptSiteDebug

To implement IActiveScriptSiteDebug::GetDocumentContextFromPosition, get the helper corresponding to the given site, and then get the starting document offset for the given source context, as follows:

CopyCode image Copy Code
pddh->GetScriptBlockInfo(dwSourceContext, NULL, &ulStartPos, NULL);

Next, use the helper to create a new document context for the given character offset:

CopyCode image Copy Code
pddh->CreateDebugDocumentContext(ulStartPos + uCharacterOffset, cChars, &pddcNew);

To implement IActiveScriptSiteDebug::GetRootApplicationNode, simply call IDebugApplication::GetRootNode (inherited from IRemoteDebugApplication::GetRootNode).

To implement IDebugDocumentHelper::GetDebugApplicationNode, simply return the IDebugApplication you initially created using the process debug manager.

The optional IDebugDocumentHost interface

The host can provide an implementation of the IDebugDocumentHost Interface by using IDebugDocumentHelper::SetDebugDocumentHost to give it additional control over the helper. Here are some of the key things the host interface allows you to do:

  • Add text using IDebugDocumentHelper::AddDeferredText so that the host does not need to provide the actual characters immediately. When the characters are really needed, the helper will call IDebugDocumentHost::GetDeferredText on the host.

  • Override the default syntax coloring provided by the helper. The helper calls IDebugDocumentHost::GetScriptTextAttributes to determine the coloring for a range of characters, falling back on its default implementation if the host return E_NOTIMPL.

  • Provide a controlling unknown for document contexts created by the helper by implementing IDebugDocumentHost::OnCreateDocumentContext. This allows the host to override the functionality of the default document context implementation.

  • Provide a path name in the file system for the document. Some debugging UIs use this to permit the user to edit and save changes to the document. IDebugDocumentHost::NotifyChanged is called to notify the host after the document has been saved.

See Also

Concepts

Active Script Debugging Overview


Windows Script Interfaces Reference

Microsoft Windows Script Interfaces
Windows Script Interfaces Reference
See Also
DropDown image

The following sections cover Windows Script Interfaces.

In This Section

Active Script Debugger Interfaces

Active Script Interfaces

Debug Property Interfaces

Dispatch Extension Interfaces

See Also

Other Resources

Windows Script Interfaces


Active Script Debugger Interfaces

Microsoft Windows Script Interfaces
Active Script Debugger Interfaces
See Also
DropDown image

The ActivDbg.h header file provides the interfaces listed in this section.

In This Section

The following interfaces allow language-neutral, host-neutral debugging:

  • IActiveScriptDebug Interface

  • IActiveScriptErrorDebug Interface

  • IActiveScriptSiteDebug Interface

  • IApplicationDebugger Interface

  • IApplicationDebuggerUI Interface

  • IDebugApplication Interface

  • IDebugApplicationNode Interface

  • IDebugApplicationNodeEvents Interface

  • IDebugApplicationThread Interface

  • IDebugAsyncOperation Interface

  • IDebugAsyncOperationCallBack Interface

  • IDebugCodeContext Interface

  • IDebugCookie Interface

  • IDebugDocument Interface

  • IDebugDocumentContext Interface

  • IDebugDocumentHelper Interface

  • IDebugDocumentHost Interface

  • IDebugDocumentInfo Interface

  • IDebugDocumentProvider Interface

  • IDebugDocumentText Interface

  • IDebugDocumentTextAuthor Interface

  • IDebugDocumentTextEvents Interface

  • IDebugDocumentTextExternalAuthor Interface

  • IDebugExpression Interface

  • IDebugExpressionCallBack Interface

  • IDebugExpressionContext Interface

  • IDebugFormatter Interface

  • IDebugHelper Interface

  • IDebugSessionProvider Interface

  • IDebugStackFrame Interface

  • IDebugStackFrameSniffer Interface

  • IDebugStackFrameSnifferEx Interface

  • IDebugSyncOperation Interface

  • IDebugThreadCall Interface

  • IEnumDebugApplicationNodes Interface

  • IEnumDebugCodeContexts Interface

  • IEnumDebugExpressionContexts Interface

  • IEnumDebugStackFrames Interface

  • IEnumRemoteDebugApplications Interface

  • IEnumRemoteDebugApplicationThreads Interface

  • IMachineDebugManager Interface

  • IMachineDebugManagerCookie Interface

  • IMachineDebugManagerEvents Interface

  • IProcessDebugManager Interface

  • IProvideExpressionContexts Interface

  • IRemoteDebugApplication Interface

  • IRemoteDebugApplicationEvents Interface

  • IRemoteDebugApplicationThread Interface

  • ISimpleConnectionPoint Interface

The following section lists the constants, enumerations, and structures used for debugging:

  • Active Script Debugger Constants, Enumerations, and Structures

See Also

Concepts

Active Script Debugging Overview


Active Script Debugger Constants, Enumerations, and Structures

Microsoft Windows Script Interfaces
Active Script Debugger Constants, Enumerations, and Structures
DropDown image

The following constants, enumerations, and structures are used by the Active Debugging interfaces.

Constants, Enumerations, and Structures

Constants | Description
APPBREAKFLAGS Constants | Indicate the current debug state for applications and threads.
SOURCE_TEXT_ATTR Constants | Describe the attributes of a single character of source text.
TEXT_DOC_ATTR Constants | Describe the attributes of the document.
Enumerations | Description
BREAKPOINT_STATE Enumeration | Indicates the state of a breakpoint.
BREAKREASON Enumeration | Indicates what caused the break.
BREAKRESUMEACTION Enumeration | Describes how to continue from a breakpoint.
DOCUMENTNAMETYPE Enumeration | Describes which type to get for a document.
ERRORRESUMEACTION Enumeration | Describes how to continue from a runtime error.
Structures | Description
DebugStackFrameDescriptor Structure | Enumerates stack frames and merges output from several enumerators on the same thread.


APPBREAKFLAGS Constants

Microsoft Windows Script Interfaces
APPBREAKFLAGS Constants
See Also
CollapseAll image DropDown image

Indicate the current debug state for applications and threads.

typedef DWORD APPBREAKFLAGS;

Expand image Constants

Constant | Value | Description
APPBREAKFLAG_DEBUGGER_BLOCK | 0x00000001 | Language engine should break immediately on all threads with BREAKREASON_DEBUGGER_BLOCK.
APPBREAKFLAG_DEBUGGER_HALT | 0x00000002 | Language engine should break immediately with BREAKREASON_DEBUGGER_HALT.
APPBREAKFLAG_STEP | 0x00010000 | Language engine should break immediately in the stepping thread with BREAKREASON_STEP.
APPBREAKFLAG_NESTED | 0x00020000 | The application is in nested execution on a breakpoint.
APPBREAKFLAG_STEPTYPE_SOURCE | 0x00000000 | The debugger is stepping at the source level.
APPBREAKFLAG_STEPTYPE_BYTECODE | 0x00100000 | The debugger is stepping at the byte code level.
APPBREAKFLAG_STEPTYPE_MACHINE | 0x00200000 | The debugger is stepping at the machine level.
APPBREAKFLAG_STEPTYPE_MASK | 0x00F00000 | Mask for factoring out the step types.
APPBREAKFLAG_IN_BREAKPOINT | 0x80000000 | A breakpoint is in progress.

Expand image Remarks

Some flags specify that language engines should break at the next opportunity, while other flags specify the stepping mode of the debugger.

Expand image See Also

Reference

BREAKREASON Enumeration

Concepts

Active Script Debugger Constants, Enumerations, and Structures


BREAKPOINT_STATE Enumeration

Microsoft Windows Script Interfaces
BREAKPOINT_STATE Enumeration
See Also
CollapseAll image DropDown image

Indicates the state of a breakpoint.

typedef enum tagBREAKPOINT_STATE {
   BREAKPOINT_DELETED = 0,
   BREAKPOINT_DISABLED = 1,
   BREAKPOINT_ENABLED = 2
} BREAKPOINT_STATE;

Expand image Members

Member | Description
BREAKPOINT_DELETED | The breakpoint no longer exists, but there are still references to it.
BREAKPOINT_DISABLED | The breakpoint exists but is disabled.
BREAKPOINT_ENABLED | The breakpoint exists and is enabled.

Expand image See Also

Concepts

Active Script Debugger Constants, Enumerations, and Structures


BREAKREASON Enumeration

Microsoft Windows Script Interfaces
BREAKREASON Enumeration
See Also
CollapseAll image DropDown image

Indicates what caused the break.

typedef enum tagBREAKREASON {
   BREAKREASON_STEP,
   BREAKREASON_BREAKPOINT,
   BREAKREASON_DEBUGGER_BLOCK,
   BREAKREASON_HOST_INITIATED,
   BREAKREASON_LANGUAGE_INITIATED,
   BREAKREASON_DEBUGGER_HALT,
   BREAKREASON_ERROR,
   BREAKREASON_JIT
} BREAKREASON;

Expand image Members

Member | Description
BREAKREASON_STEP | The language engine is in the stepping mode.
BREAKREASON_BREAKPOINT | The language engine encountered an explicit breakpoint.
BREAKREASON_DEBUGGER_BLOCK | The language engine encountered a debugger block on another thread.
BREAKREASON_HOST_INITIATED | The host requested a break.
BREAKREASON_LANGUAGE_INITIATED | The language engine requested a break.
BREAKREASON_DEBUGGER_HALT | The debugger IDE requested a break.
BREAKREASON_ERROR | An execution error caused the break.
BREAKREASON_JIT | Caused by JIT Debugging startup.

Expand image See Also

Concepts

Active Script Debugger Constants, Enumerations, and Structures


BREAKRESUMEACTION Enumeration

Microsoft Windows Script Interfaces
BREAKRESUMEACTION Enumeration
See Also
CollapseAll image DropDown image

Describes ways to continue from a breakpoint.

typedef enum tagBREAKRESUME_ACTION {
   BREAKRESUMEACTION_ABORT,
   BREAKRESUMEACTION_CONTINUE,
   BREAKRESUMEACTION_STEP_INTO,
   BREAKRESUMEACTION_STEP_OVER,
   BREAKRESUMEACTION_STEP_OUT,
   BREAKRESUMEACTION_IGNORE,
} BREAKRESUMEACTION;

Expand image Members

Member | Description
BREAKRESUMEACTION_ABORT | Aborts the application.
BREAKRESUMEACTION_CONTINUE | Continues running.
BREAKRESUMEACTION_STEP_INTO | Steps into a procedure.
BREAKRESUMEACTION_STEP_OVER | Steps over a procedure.
BREAKRESUMEACTION_STEP_OUT | Steps out of the current procedure.
BREAKRESUMEACTION_IGNORE | Continues running with state.

Expand image See Also

Concepts

Active Script Debugger Constants, Enumerations, and Structures


DebugStackFrameDescriptor Structure

Microsoft Windows Script Interfaces
DebugStackFrameDescriptor Structure
See Also
CollapseAll image DropDown image

Enumerates stack frames and merges output from several enumerators on the same thread.

typedef struct tagDebugStackFrameDescriptor {
   IDebugStackFrame *pdsf;
   DWORD_PTR        dwMin;
   DWORD_PTR        dwLim;
   BOOL             fFinal;
   IUnknown         *punkFinal;
} DebugStackFrameDescriptor;

Expand image Members

pdsf

The stack frame object.

dwMin

A machine-dependent representation of the lower range of physical addresses associated with this stack frame.

dwLim

A machine-dependent representation of the upper range of physical addresses associated with this stack frame.

fFinal

Flag that indicates that the frame is being processed.

punkFinal

If this parameter is not NULL, the current enumerator merging should stop and a new one should be started. The object indicates how to start the new enumeration.

Expand image Remarks

The process debug manager uses this structure to sort the stack frames from multiple script engines. By convention, stacks grow down. Consequently, on architectures where stacks grow up, the addresses should be twos-complemented.

Expand image See Also

Concepts

Active Script Debugger Constants, Enumerations, and Structures


DOCUMENTNAMETYPE Enumeration

Microsoft Windows Script Interfaces
DOCUMENTNAMETYPE Enumeration
See Also
CollapseAll image DropDown image

Describes which type to get for a document.

typedef enum tagDOCUMENTNAMETYPE {
   DOCUMENTNAMETYPE_APPNODE,
   DOCUMENTNAMETYPE_TITLE,
   DOCUMENTNAMETYPE_FILE_TAIL,
   DOCUMENTNAMETYPE_URL,
} DOCUMENTNAMETYPE;

Expand image Members

Member | Description
DOCUMENTNAMETYPE_APPNODE | Gets the name as it appears in the application tree.
DOCUMENTNAMETYPE_TITLE | Gets the name as it appears on the viewer title bar.
DOCUMENTNAMETYPE_FILE_TAIL | Gets the file name without a path.
DOCUMENTNAMETYPE_URL | Gets the URL of the document.

Expand image See Also

Concepts

Active Script Debugger Constants, Enumerations, and Structures


ERRORRESUMEACTION Enumeration

Microsoft Windows Script Interfaces
ERRORRESUMEACTION Enumeration
See Also
CollapseAll image DropDown image

Describes how to continue from a runtime error.

typedef enum tagERRORRESUMEACTION {
   ERRORRESUMEACTION_ReexecuteErrorStatement,
   ERRORRESUMEACTION_AbortCallAndReturnErrorToCaller,
   ERRORRESUMEACTION_SkipErrorStatement,
} ERRORRESUMEACTION;

Expand image Members

Member | Description
ERRORRESUMEACTION_ReexecuteErrorStatement | Re-executes the statement that produced the error.
ERRORRESUMEACTION_AbortCallAndReturnErrorToCaller | Lets the language engine handle the error.
ERRORRESUMEACTION_SkipErrorStatement | Resumes execution in the code following the statement that produced the error.

Expand image See Also

Concepts

Active Script Debugger Constants, Enumerations, and Structures


SOURCE_TEXT_ATTR Constants

Microsoft Windows Script Interfaces
SOURCE_TEXT_ATTR Constants
See Also
CollapseAll image DropDown image

Describe the attributes of a single character of source text.

typedef WORD SOURCE_TEXT_ATTR;

Expand image Constants

Constant | Value | Description
SOURCETEXT_ATTR_KEYWORD | 0x0001 | The character is part of a language keyword. For example, the VBScript keyword While.
SOURCETEXT_ATTR_COMMENT | 0x0002 | The character is part of a comment block.
SOURCETEXT_ATTR_NONSOURCE | 0x0004 | The character is not part of compiled language source text. For example, the HTML surrounding a script block.
SOURCETEXT_ATTR_OPERATOR | 0x0008 | The character is part of a language operator. For example:, the arithmetic operator +.
SOURCETEXT_ATTR_NUMBER | 0x0010 | The character is part of a language numeric constant. For example, the constant 3.14159.
SOURCETEXT_ATTR_STRING | 0x0020 | The character is part of a language string constant. For example, the string "Hello World".
SOURCETEXT_ATTR_FUNCTION_START | 0x0040 | The character indicates the start of a function block
SOURCETEXT_ATTR_IDENTIFIER | 0x0100 | The character is part of an identifier.
SOURCETEXT_ATTR_MEMBERLOOKUP | 0x0200 | The character is a dot operator. For example, the dot in the Object.Property
SOURCETEXT_ATTR_THIS | 0x0400 | The character is part of the identifier that represents the current object. For example, this in JScript or Me in VBScript.
SOURCETEXT_ATTR_HUMANTEXT | 0x8000 | The character is in the non-delimiter portion of string literals or comment. For example, characters between string delimiters.

Expand image Remarks

Typically, the IDebugDocumentHost::GetScriptTextAttributes, IActiveScriptDebug::GetScriptletTextAttributes, and IActiveScriptDebug::GetScriptTextAttributes methods return one text attribute per character, unless:

  • The GETATTRTYPE_DEPSCAN flag is set, in which case the method may return the SOURCETEXT_ATTR_IDENTIFIER and SOURCETEXT_ATTR_MEMBERLOOKUP flags,

  • The GETATTRFLAG_THIS flag is set, in which case the method may return the SOURCETEXT_ATTR_THIS flag,

  • The GETATTRFLAG_HUMANTEXT flag is set, in which case the method may return the SOURCETEXT_ATTR_HUMANTEXT flag.

Expand image See Also

Concepts

Active Script Debugger Constants, Enumerations, and Structures


TEXT_DOC_ATTR Constants

Microsoft Windows Script Interfaces
TEXT_DOC_ATTR Constants
See Also
CollapseAll image DropDown image

Describe the attributes of the document.

typedef DWORD TEXT_DOC_ATTR;

Expand image Constants

Constant | Value | Description
TEXT_DOC_ATTR_READONLY | 0x00000001 | The document is read-only.

Expand image Remarks

If a TEXT_DOC_ATTR value does not have the TEXT_DOC_ATTR_READONLY flag set, the document is writable.

Expand image See Also

Concepts

Active Script Debugger Constants, Enumerations, and Structures


IActiveScriptDebug Interface

Microsoft Windows Script Interfaces
IActiveScriptDebug Interface
DropDown image

Implemented by script engines that support debugging. Typically, an object that implements the IActiveScriptDebug interface also implements the IActiveScript interface. If this is the case, call the IActiveScript::QueryInterface method to obtain the IActiveScriptDebug interface.

The IActiveScriptDebug interface provides the means for:

  • Smart hosts to take over document management.

  • Process debug manager to synchronize debugging of multiple script engines.

In addition to the methods inherited from IUnknown, the IActiveScriptDebug interface exposes the following methods.

Methods in Vtable Order

Method | Description
IActiveScriptDebug::GetScriptTextAttributes | Returns the text attributes for an arbitrary block of script text.
IActiveScriptDebug::GetScriptletTextAttributes | Returns the text attributes for an arbitrary scriptlet.
IActiveScriptDebug::EnumCodeContextsOfPosition | Delegates to IDebugDocumentContext::EnumCodeContexts.


IActiveScriptDebug::EnumCodeContextsOfPosition

Microsoft Windows Script Interfaces
IActiveScriptDebug::EnumCodeContextsOfPosition
See Also
CollapseAll image DropDown image

Used by a smart host to delegate the IDebugDocumentContext::EnumCodeContexts method.

HRESULT EnumCodeContextsOfPosition(
   DWORD_PTR                 dwSourceContext,
   ULONG                     uCharacterOffset,
   ULONG                     uNumChars,
   IEnumDebugCodeContexts**  ppescc
);

Parameters

dwSourceContext

[in] The source context as provided to IActiveScriptParse::ParseScriptText or IActiveScriptParse::AddScriptlet.

uCharacterOffset

[in] Character offset relative to start of script text.

uNumChars

[in] Number of characters in this context.

ppescc

[out] An enumerator of the code contexts in the specified range.

Expand image Return Value

The method returns an HRESULT. Possible values include, but are not limited to, those in the following table.

Value | Description
S_OK | The method succeeded.

Expand image Remarks

Smart hosts use this method to delegate the IDebugDocumentContext::EnumCodeContexts method.

Expand image See Also

Reference

IDebugDocumentContext::EnumCodeContexts

Concepts

IActiveScriptDebug Interface


IActiveScriptDebug::GetScriptletTextAttributes

Microsoft Windows Script Interfaces
IActiveScriptDebug::GetScriptletTextAttributes
See Also
CollapseAll image DropDown image

Returns the text attributes for an arbitrary scriptlet.

HRESULT GetScriptletTextAttributes(
   LPCOLESTR          pstrCode,
   ULONG              uNumCodeChars,
   LPCOLESTR          pstrDelimiter,
   DWORD              dwFlags,
   SOURCE_TEXT_ATTR*  pattr
);

Parameters

pstrCode

[in] The scriptlet text. This string need not be null terminated.

uNumCodeChars

[in] The number of characters in the scriptlet text.

pstrDelimiter

[in] Address of the end-of-scriptlet delimiter. When pstrCode is parsed from a stream of text, the host typically uses a delimiter, such as two single quotation marks (''), to detect the end of the scriptlet. This parameter specifies the delimiter that the host used, allowing the scripting engine to provide some conditional primitive preprocessing (for example, replacing a single quotation mark ['] with two single quotation marks for use as a delimiter). Exactly how (and if) the scripting engine uses this information depends on the scripting engine. Set this parameter to NULL if the host did not use a delimiter to mark the end of the scriptlet.

dwFlags

[in] Flags associated with the scriptlet. Can be a combination of these values:

Constant Value Description

GETATTRTYPE_DEPSCAN

0x0001

Indicates that identifiers and dot operators should be identified with the SOURCETEXT_ATTR_IDENTIFIER and SOURCETEXT_ATTR_MEMBERLOOKUP flags, respectively.

GETATTRFLAG_THIS

0x0100

Indicates that the identifier for the current object should be identified with the SOURCETEXT_ATTR_THIS flag.

GETATTRFLAG_HUMANTEXT

0x8000

Indicates that string content and comment text should be identified with the SOURCETEXT_ATTR_HUMANTEXT flag.
pattr

[in, out] Buffer to contain the returned attributes.

Expand image Return Value

The method returns an HRESULT. Possible values include, but are not limited to, those in the following table.

Value | Description
S_OK | The method succeeded.

Expand image Remarks

A smart host that implements IDebugDocumentText interface can use this method to delegate calls to the IDebugDocumentText::GetText method.

This call is provided because scriptlets tend to be expressions and may have a different syntax than a script block. If they have the same syntax, the implementation of this method will be identical to the implementation of the GetScriptTextAttributes method.

Expand image See Also

Reference

IActiveScriptDebug::GetScriptTextAttributes
IDebugDocumentText::GetText
SOURCE_TEXT_ATTR Constants

Concepts

IActiveScriptDebug Interface
IDebugDocumentText Interface


IActiveScriptDebug::GetScriptTextAttributes

Microsoft Windows Script Interfaces
IActiveScriptDebug::GetScriptTextAttributes
See Also
CollapseAll image DropDown image

Returns the text attributes for an arbitrary block of script text.

HRESULT GetScriptTextAttributes(
   LPCOLESTR          pstrCode,
   ULONG              uNumCodeChars,
   LPCOLESTR          pstrDelimiter,
   DWORD              dwFlags,
   SOURCE_TEXT_ATTR*  pattr
);

Parameters

pstrCode

[in] The script block text. This string need not be null terminated.

uNumCodeChars

[in] The number of characters in the script block text.

pstrDelimiter

[in] Address of the end-of-script-block delimiter. When pstrCode is parsed from a stream of text, the host typically uses a delimiter, such as two single quotation marks (''), to detect the end of the script block. This parameter specifies the delimiter that the host used, allowing the scripting engine to provide some conditional primitive preprocessing (for example, replacing a single quotation mark ['] with two single quotation marks for use as a delimiter). Exactly how (and if) the scripting engine uses this information depends on the scripting engine. Set this parameter to NULL if the host did not use a delimiter to mark the end of the script block.

dwFlags

[in] Flags associated with the script block. Can be a combination of these values:

Constant Value Description

GETATTRTYPE_DEPSCAN

0x0001

Indicates that identifiers and dot operators should be identified with the SOURCETEXT_ATTR_IDENTIFIER and SOURCETEXT_ATTR_MEMBERLOOKUP flags, respectively.

GETATTRFLAG_THIS

0x0100

Indicates that the identifier for the current object should be identified with the SOURCETEXT_ATTR_THIS flag.

GETATTRFLAG_HUMANTEXT

0x8000

Indicates that string content and comment text should be identified with the SOURCETEXT_ATTR_HUMANTEXT flag.
pattr

[in, out] Buffer to contain the returned attributes.

Expand image Return Value

The method returns an HRESULT. Possible values include, but are not limited to, those in the following table.

Value | Description
S_OK | The method succeeded.

Expand image Remarks

A smart host that implements IDebugDocumentText interface can use this method to delegate calls to the IDebugDocumentText::GetText method.

This method for script blocks; the GetScriptletTextAttributes method is for scriptlets.

Expand image See Also

Reference

IActiveScriptDebug::GetScriptletTextAttributes
IDebugDocumentText::GetText
SOURCE_TEXT_ATTR Constants

Concepts

IActiveScriptDebug Interface
IDebugDocumentText Interface


IActiveScriptErrorDebug Interface

Microsoft Windows Script Interfaces
IActiveScriptErrorDebug Interface
DropDown image

Provides document context information for compile-time errors and run-time exceptions. The IActiveScriptError::QueryInterface method supports the IActiveScriptErrorDebug interface.

In addition to the methods inherited from IActiveScriptError, the IActiveScriptErrorDebug interface exposes the following methods.

Methods in Vtable Order

Method | Description
IActiveScriptErrorDebug::GetDocumentContext | Provides the document context for this error.
IActiveScriptErrorDebug::GetStackFrame | Provides the stack frame that is in effect for runtime errors.


IActiveScriptErrorDebug::GetDocumentContext

Microsoft Windows Script Interfaces
IActiveScriptErrorDebug::GetDocumentContext
See Also
CollapseAll image DropDown image

Provides the document context for this error.

HRESULT GetDocumentContext(
   IDebugDocumentContext**  ppssc
);

Parameters

ppssc

[out] The document context for this error.

Expand image Return Value

The method returns an HRESULT. Possible values include, but are not limited to, those in the following table.

Value | Description
S_OK | The method succeeded.

Expand image Remarks

The document context character-position range should include all the characters corresponding to the error.

Expand image See Also

Concepts

IActiveScriptErrorDebug Interface


IActiveScriptErrorDebug::GetStackFrame

Microsoft Windows Script Interfaces
IActiveScriptErrorDebug::GetStackFrame
See Also
CollapseAll image DropDown image

Provides the stack frame that is in effect for runtime errors.

HRESULT GetStackFrame(
   IDebugStackFrame**  ppdsf
);

Parameters

ppdsf

[out] The stack frame for the error.

Expand image Return Value

The method returns an HRESULT. Possible values include, but are not limited to, those in the following table.

Value | Description
S_OK | The method succeeded.

Expand image Remarks

This method provides the stack frame that is in effect for run-time errors.

Expand image See Also

Concepts

IActiveScriptErrorDebug Interface


IActiveScriptSiteDebug Interface

Microsoft Windows Script Interfaces
IActiveScriptSiteDebug Interface
DropDown image

Smart hosts implement the IActiveScriptSiteDebug interface to perform document management and to participate in debugging. The IActiveScriptSite object typically provides an implementation of the IActiveScriptSiteDebug interface. If this is done, call the IActiveScriptSite::QueryInterface method to obtain the IActiveScriptSiteDebug interface.

In addition to the methods inherited from IUnknown, the IActiveScriptSiteDebug interface exposes the following methods.

Methods in Vtable Order

Method | Description
IActiveScriptSiteDebug::GetDocumentContextFromPosition | Used by the language engine to delegate IDebugCodeContext::GetSourceContext.
IActiveScriptSiteDebug::GetApplication | Returns the debug application object associated with this script site.
IActiveScriptSiteDebug::GetRootApplicationNode | Gets the application node under which script documents should be added.
IActiveScriptSiteDebug::OnScriptErrorDebug | Allows a smart host to determine how to handle run-time errors.


IActiveScriptSiteDebug::GetApplication

Microsoft Windows Script Interfaces
IActiveScriptSiteDebug::GetApplication
See Also
CollapseAll image DropDown image

Returns the debug application object associated with this script site.

HRESULT GetApplication(
   IDebugApplication**  ppda
);

Parameters

ppda

[out] Pointer to the debug application object associated with the script site.

Expand image Return Value

The method returns an HRESULT. Possible values include, but are not limited to, those in the following table.

Value | Description
S_OK | The method succeeded.
E_NOTIMPL | The host does not directly support debugging.

Expand image Remarks

The GetApplication method provides a way for a smart host to define the application object to which each script belongs. Script engines should attempt to call this method to get their containing application and resort to IProcessDebugManager::GetDefaultApplication if this fails.

Expand image See Also

Reference

IProcessDebugManager::GetDefaultApplication

Concepts

IActiveScriptSiteDebug Interface


IActiveScriptSiteDebug::GetDocumentContextFromPosition

Microsoft Windows Script Interfaces
IActiveScriptSiteDebug::GetDocumentContextFromPosition
See Also
CollapseAll image DropDown image

Used by the language engine to delegate IDebugCodeContext::GetSourceContext.

HRESULT GetDocumentContextFromPosition(
   DWORD_PTR                dwSourceContext,
   ULONG                    uCharacterOffset,
   ULONG                    uNumChars,
   IDebugDocumentContext**  ppsc
);

Parameters

dwSourceContext

[in] The source content as provided to ParseScriptText or AddScriptlet.

uCharacterOffset

[in] Character offset relative to start of script block or scriptlet.

uNumChars

[in] Number of characters in this context.

ppsc

[out] The document context corresponding to this character-position range.

Expand image Return Value

The method returns an HRESULT. Possible values include, but are not limited to, those in the following table.

Value | Description
S_OK | The method succeeded.

Expand image Remarks

Language engines use this method to delegate IDebugCodeContext::GetSourceContext.

Expand image See Also

Concepts

IActiveScriptSiteDebug Interface


IActiveScriptSiteDebug::GetRootApplicationNode

Microsoft Windows Script Interfaces
IActiveScriptSiteDebug::GetRootApplicationNode
See Also
CollapseAll image DropDown image

Gets the application node under which script documents should be added.

HRESULT GetRootApplicationNode(
   IDebugApplicationNode**  ppdanRoot
);

Parameters

ppdanRoot

[out] The debug application node that holds script documents. Can be NULL.

Expand image Return Value

The method returns an HRESULT. Possible values include, but are not limited to, those in the following table.

Value | Description
S_OK | The method succeeded.

Expand image Remarks

This method returns the application node under which script documents should be added. The method can return NULL for ppdanRoot if script documents should be top-level.

Expand image See Also

Concepts

IActiveScriptSiteDebug Interface


IActiveScriptSiteDebug::OnScriptErrorDebug

Microsoft Windows Script Interfaces
IActiveScriptSiteDebug::OnScriptErrorDebug
See Also
CollapseAll image DropDown image

Allows a smart host to determine how to handle run-time errors.

HRESULT OnScriptErrorDebug(
   IActiveScriptErrorDebug*  pErrorDebug,
   BOOL*                     pfEnterDebugger,
   BOOL*                     pfCallOnScriptErrorWhenContinuing
);

Parameters

pErrorDebug

[in] The run-time error that occurred

pfEnterDebugger

[out] Flag indicating whether to pass the error to the debugger to do JIT debugging.

pfCallOnScriptErrorWhenContinuing

[out] Flag indicating whether to call IActiveScriptSite::OnScriptError when the user decides to continue without debugging.

Expand image Return Value

The method returns an HRESULT. Possible values include, but are not limited to the value in the following table.

Value | Description
S_OK | The method succeeded.

Expand image Remarks

A smart host can use this method to determine how to handle run-time errors.

Expand image See Also

Concepts

IActiveScriptSiteDebug Interface


IApplicationDebugger Interface

Microsoft Windows Script Interfaces
IApplicationDebugger Interface
DropDown image

The primary interface exposed by a debugger. In addition to the methods inherited from IUnknown, the IApplicationDebugger interface exposes the following methods.

Methods in Vtable Order

Method | Description
IApplicationDebugger::QueryAlive | Indicates if the debugger is responsive.
IApplicationDebugger::CreateInstanceAtDebugger | Allows the creation of objects in the debugger process by code that is out-of-process to the debugger.
IApplicationDebugger::onDebugOutput | Handles a debug output event.
IApplicationDebugger::onHandleBreakPoint | Handles a breakpoint event.
IApplicationDebugger::onClose | Handles a debug application close event.
IApplicationDebugger::onDebuggerEvent | Handles a custom application event.


IApplicationDebugger::CreateInstanceAtDebugger

Microsoft Windows Script Interfaces
IApplicationDebugger::CreateInstanceAtDebugger
See Also
CollapseAll image DropDown image

Allows the creation of objects in the debugger process by code that is out-of-process to the debugger.

Security note Security Note

This method should not be implemented, because it allows untrusted code to create arbitrary objects in a trusted debugger thread.

HRESULT CreateInstanceAtDebugger(
   REFCLSID    rclsid,
   IUnknown*   pUnkOuter,
   DWORD       dwClsContext,
   REFIID      riid,
   IUnknown**  ppvObject
);

Parameters

rclsid

[in] Class identifier (CLSID) of the object to create.

pUnkOuter

[in] If NULL, the object is not being created as part of an aggregate. Otherwise, pUnkOuter is a pointer to the aggregate object's IUnknown interface (the controlling IUnknown).

dwClsContext

[in] Context for running executable code. The values are taken from the enumeration CLSCTX.

riid

[in] The interface identifier used to communicate with the object.

ppvObject

[out] Address of pointer variable that receives the interface pointer requested in riid. Upon successful return, *ppvObject contains the requested interface pointer. Upon failure, *ppvObject contains NULL.

Expand image Return Value

The method returns an HRESULT. Possible values include, but are not limited to, those in the following table.

Value | Description
S_OK | The method succeeded.

Expand image Remarks

This method delegates to CoCreateInstance.

The method is not currently implemented.

Expand image See Also

Concepts

IApplicationDebugger Interface


IApplicationDebugger::onClose

Microsoft Windows Script Interfaces
IApplicationDebugger::onClose
See Also
CollapseAll image DropDown image

Handles a debug application close event.

HRESULT onClose();

Parameters

This method takes no parameters.

Expand image Return Value

The method returns an HRESULT. Possible values include, but are not limited to, those in the following table.

Value | Description
S_OK | The method succeeded.

Expand image Remarks

This method is called when IDebugApplication::Close is called.

Expand image See Also

Reference

IDebugApplication::Close

Concepts

IApplicationDebugger Interface


IApplicationDebugger::onDebuggerEvent

Microsoft Windows Script Interfaces
IApplicationDebugger::onDebuggerEvent
See Also
CollapseAll image DropDown image

Handles a custom application event.

HRESULT onDebuggerEvent(
   REFIID     riid,
   IUnknown*  punk
);

Parameters

riid

[in] The interface identifier for the object.

punk

[in] The event object, which implements the interface defined by riid.

Expand image Return Value

The method returns an HRESULT. Possible values include, but are not limited to, those in the following table.

Value | Description
S_OK | The method succeeded.
E_NOTIMPL | The method is not currently implemented.

Expand image Remarks

The semantics of the IUnknown is entirely application/debugger defined.

This method allows for custom extensions of the debugger model; it is not currently implemented.

This method is called when IDebugApplication::FireDebuggerEvent is called.

Expand image See Also

Reference

IDebugApplication::FireDebuggerEvent

Concepts

IApplicationDebugger Interface


IApplicationDebugger::onDebugOutput

Microsoft Windows Script Interfaces
IApplicationDebugger::onDebugOutput
See Also
CollapseAll image DropDown image

Handles a debug output event.

HRESULT onDebugOutput(
   LPCOLESTR  pstr
);

Parameters

pstr

[in] String to display in the debugger.

Expand image Return Value

The method returns an HRESULT. Possible values include, but are not limited to, those in the following table.

Value | Description
S_OK | The method succeeded.

Expand image Remarks

The debugger typically displays pstr in an output window.

This method is called when IDebugApplication::DebugOutput is called.

Expand image See Also

Reference

IDebugApplication::DebugOutput

Concepts

IApplicationDebugger Interface


IApplicationDebugger::onHandleBreakPoint

Microsoft Windows Script Interfaces
IApplicationDebugger::onHandleBreakPoint
See Also
CollapseAll image DropDown image

Handles a breakpoint event.

HRESULT onHandleBreakPoint(
   IRemoteDebugApplicationThread*  prpt,
   BREAKREASON                     br,
   IActiveScriptErrorDebug*        pError
);

Parameters

prpt

[in] The thread where the breakpoint occurred.

br

[in] The reason for the breakpoint.

pError

[in] Runtime error information, provided when the value of br is BREAKREASON_ERROR.

Expand image Return Value

The method returns an HRESULT. Possible values include, but are not limited to, those in the following table.

Value | Description
S_OK | The method succeeded.

Expand image Remarks

This method is called when a breakpoint is hit and IDebugApplication::HandleBreakPoint is called.

The application will remain suspended until the debugger IDE calls IRemoteDebugApplication::ResumeFromBreakPoint.

Expand image See Also

Reference

IDebugApplication::HandleBreakPoint
IRemoteDebugApplication::ResumeFromBreakPoint
BREAKREASON Enumeration

Concepts

IApplicationDebugger Interface


IApplicationDebugger::QueryAlive

Microsoft Windows Script Interfaces
IApplicationDebugger::QueryAlive
See Also
CollapseAll image DropDown image

Indicates if the debugger is responsive.

HRESULT QueryAlive();

Parameters

This method takes no parameters.

Expand image Return Value

The method returns an HRESULT. Possible values include, but are not limited to, those in the following table.

Value | Description
S_OK | The method succeeded.

Expand image Remarks

This method indicates if the debugger is responsive. Implementations of this method should always return S_OK.

If the debugger process terminates unexpectedly, COM returns an error from the marshalling proxy for calls to this method.

Expand image See Also

Concepts

IApplicationDebugger Interface


IApplicationDebuggerUI Interface

Microsoft Windows Script Interfaces
IApplicationDebuggerUI Interface
DropDown image

Implemented by the debugger integrated development environment (IDE) (in addition to IApplicationDebugger) to give an external component more control over the user interface (UI) of the debugger.

In addition to the methods inherited from IUnknown, the IApplicationDebuggerUI interface exposes the following methods.

Methods in Vtable Order

Method | Description
IApplicationDebuggerUI::BringDocumentToTop | Brings the window containing the specified debug document to the top in the debugger user interface.
IApplicationDebuggerUI::BringDocumentContextToTop | Brings the window containing the given document context to the top in the debugger user interface and scrolls the window to the context.


IApplicationDebuggerUI::BringDocumentContextToTop

Microsoft Windows Script Interfaces
IApplicationDebuggerUI::BringDocumentContextToTop
See Also
CollapseAll image DropDown image

Brings the window containing the given document context to the top in the debugger user interface and scrolls the window to the context.

HRESULT BringDocumentContextToTop(
   IDebugDocumentContext*  pddc
);

Parameters

pddc

[in] Document context to bring to the top in the debugger user interface.

Expand image Return Value

The method returns an HRESULT. Possible values include, but are not limited to, those in the following table.

Value | Description
S_OK | The method succeeded.
E_INVALIDARG | The context specified by pddc is not known.

Expand image Remarks

This method brings the window containing the given document context to the top in the debugger user interface and scrolls the window to the context.

Expand image See Also

Concepts

IApplicationDebuggerUI Interface


IApplicationDebuggerUI::BringDocumentToTop

Microsoft Windows Script Interfaces
IApplicationDebuggerUI::BringDocumentToTop
See Also
CollapseAll image DropDown image

Brings the window containing the specified debug document to the top in the debugger user interface.

HRESULT BringDocumentToTop(
   IDebugDocumentText*  pddt
);

Parameters

pddt

[in] Debug document to bring to the top in the debugger user interface.

Expand image Return Value

The method returns an HRESULT. Possible values include, but are not limited to, those in the following table.

Value | Description
S_OK | The method succeeded.
E_INVALIDARG | The document is not known.

Expand image Remarks

This method brings the window containing the specified debug document to the top in the debugger user interface.

Expand image See Also

Concepts

IApplicationDebuggerUI Interface


IDebugApplication Interface

Microsoft Windows Script Interfaces
IDebugApplication Interface
DropDown image

Exposes non-remote debugging methods for use by language engines and hosts.

In addition to the methods inherited from IRemoteDebugApplication, the IDebugApplication interface exposes the following methods.

Methods in Vtable Order

Method | Description
IDebugApplication::SetName | Sets the name of the application.
IDebugApplication::StepOutComplete | Notifies the process debug manager that a language engine in single-step mode is about to return to its caller.
IDebugApplication::DebugOutput | Causes the given string to be displayed by the debugger IDE.
IDebugApplication::StartDebugSession | Starts the default debugger IDE and attaches a debug session to this application, if one is not already attached.
IDebugApplication::HandleBreakPoint | Causes the current thread to block and sends a notification of the breakpoint to the debugger IDE.
IDebugApplication::Close | Causes this application to release all references and enter an inactive state.
IDebugApplication::GetBreakFlags | Returns the current break flags for the application.
IDebugApplication::GetCurrentThread | Returns the thread associated with the currently running thread.
IDebugApplication::CreateAsyncDebugOperation | Provides asynchronous access to a given synchronous debug operation.
IDebugApplication::AddStackFrameSniffer | Adds a stack frame enumerator provider to this application.
IDebugApplication::RemoveStackFrameSniffer | Removes a stack frame enumerator provider from this application.
IDebugApplication::QueryCurrentThreadIsDebuggerThread | Determines if the current running thread is the debugger thread.
IDebugApplication::SynchronousCallInDebuggerThread | Provides a mechanism for the caller to run code in the debugger thread.
IDebugApplication::CreateApplicationNode | Creates a new application node that is associated with a specific document provider.
IDebugApplication::FireDebuggerEvent | Fires a generic event to the debugger's IApplicationDebugger interface.
IDebugApplication::HandleRuntimeError | Causes the current thread to block and sends a notification of the error to the debugger IDE.
IDebugApplication::FCanJitDebug | Determines if a just-in-time (JIT) debugger is registered.
IDebugApplication::FIsAutoJitDebugEnabled | Determines if a JIT debugger is registered to auto-debug dumb hosts.
IDebugApplication::AddGlobalExpressionContextProvider | Adds a global expression context provider to this application.
IDebugApplication::RemoveGlobalExpressionContextProvider | Removes a global expression context provider from this application.


IDebugApplication::AddGlobalExpressionContextProvider

Microsoft Windows Script Interfaces
IDebugApplication::AddGlobalExpressionContextProvider
See Also
CollapseAll image DropDown image

Adds a global expression context provider to this application.

HRESULT AddGlobalExpressionContextProvider(
   IProvideExpressionContexts*  pdsfs,
   DWORD_PTR*                   pdwCookie
);

Parameters

pdsfs

[in] The global context provider to add to this application.

pdwCookie

[out] A cookie that is used to remove this global expression context provider from the application.

Expand image Return Value

The method returns an HRESULT. Possible values include, but are not limited to, those in the following table.

Value | Description
S_OK | The method succeeded.

Expand image Remarks

This method adds a global expression context provider to this application.

Expand image See Also

Reference

IDebugApplication::RemoveGlobalExpressionContextProvider

Concepts

IDebugApplication Interface


IDebugApplication::AddStackFrameSniffer

Microsoft Windows Script Interfaces
IDebugApplication::AddStackFrameSniffer
See Also
CollapseAll image DropDown image

Adds a stack frame enumerator provider to this application.

HRESULT AddStackFrameSniffer(
   IDebugStackFrameSniffer*  pdsfs,
   DWORD*                    pdwCookie
);

Parameters

pdsfs

[in] The stack frame enumerator provider to add to this application.

pdwCookie

[out] A cookie that is used to remove this stack frame enumerator provider from the application.

Expand image Return Value

The method returns an HRESULT. Possible values include, but are not limited to, those in the following table.

Value | Description
S_OK | The method succeeded.

Expand image Remarks

Although language engines typically call this method to expose their stack frames to the debugger, it is possible for other entities to expose stack frames.

Expand image See Also

Reference

IDebugApplication::RemoveStackFrameSniffer

Concepts

IDebugApplication Interface
IDebugStackFrameSniffer Interface


IDebugApplication::Close

Microsoft Windows Script Interfaces
IDebugApplication::Close
See Also
CollapseAll image DropDown image

Causes this application to release all references and enter an inactive state.

HRESULT Close();

Parameters

This method takes no parameters.

Expand image Return Value

The method returns an HRESULT. Possible values include, but are not limited to, those in the following table.

Value | Description
S_OK | The method succeeded.

Expand image Remarks

Typically, the owner of an application calls this method when the application exits.

This method causes IApplicationDebugger::onClose to be called.

Expand image See Also

Reference

IApplicationDebugger::onClose

Concepts

IDebugApplication Interface


IDebugApplication::CreateApplicationNode

Microsoft Windows Script Interfaces
IDebugApplication::CreateApplicationNode
See Also
CollapseAll image DropDown image

Creates a new application node that is associated with a specific document provider.

HRESULT CreateApplicationNode(
   IDebugApplicationNode**  ppdanNew
);

Parameters

ppdanNew

[out] The application node associated with this document provider.

Expand image Return Value

The method returns an HRESULT. Possible values include, but are not limited to, those in the following table.

Value | Description
S_OK | The method succeeded.

Expand image Remarks

The new application node is not visible until it is attached to a parent node.

Expand image See Also

Concepts

IDebugApplication Interface


IDebugApplication::CreateAsyncDebugOperation

Microsoft Windows Script Interfaces
IDebugApplication::CreateAsyncDebugOperation
See Also
CollapseAll image DropDown image

Provides asynchronous access to a given synchronous debug operation.

HRESULT CreateAsyncDebugOperation(
   IDebugSyncOperation*    psdo,
   IDebugAsyncOperation**  ppado
);

Parameters

psdo

[in] The synchronous debug operation object.

ppado

[out] The asynchronous debug operation object.

Expand image Return Value

The method returns an HRESULT. Possible values include, but are not limited to, those in the following table.

Value | Description
S_OK | The method succeeded.

Expand image Remarks

This method allows language engines to evaluate expressions asynchronously without explicitly synchronizing with the debugger thread. For more information, see IDebugSyncOperation Interface and IDebugAsyncOperation Interface.

Expand image See Also

Concepts

IDebugApplication Interface
IDebugSyncOperation Interface
IDebugAsyncOperation Interface


IDebugApplication::DebugOutput

Microsoft Windows Script Interfaces
IDebugApplication::DebugOutput
See Also
CollapseAll image DropDown image

Causes the given string to be displayed by the debugger integrated development environment (IDE).

HRESULT DebugOutput(
   LPCOLESTR  pstr
);

Parameters

pstr

[in] String to display in the debugger.

Expand image Return Value

The method returns an HRESULT. Possible values include, but are not limited to, those in the following table.

Value | Description
S_OK | The method succeeded.

Expand image Remarks

This method allows a language engine to implement language-specific debugging output support. The string is typically displayed in the debugger's output window.

This method causes IApplicationDebugger::onDebugOutput to be called.

Expand image See Also

Reference

IApplicationDebugger::onDebugOutput

Concepts

IDebugApplication Interface


IDebugApplication::FCanJitDebug

Microsoft Windows Script Interfaces
IDebugApplication::FCanJitDebug
See Also
CollapseAll image DropDown image

Determines if a just-in-time (JIT) debugger is registered.

BOOL FCanJitDebug();

Parameters

This method takes no parameters.

Expand image Return Value

If the method succeeds and a JIT debugger is registered, the method returns TRUE. Otherwise, it returns FALSE.

Expand image Remarks

This method determines if a JIT debugger is registered.

Expand image See Also

Concepts

IDebugApplication Interface


IDebugApplication::FireDebuggerEvent

Microsoft Windows Script Interfaces
IDebugApplication::FireDebuggerEvent
See Also
CollapseAll image DropDown image

Fires a generic event to the debugger's IApplicationDebugger interface.

HRESULT FireDebuggerEvent(
   REFGUID    riid,
   IUnknown*  punk
);

Parameters

riid

[in] A GUID for the object.

punk

[in] An event object to pass to the debugger.

Expand image Return Value

The method returns an HRESULT. Possible values include, but are not limited to, those in the following table.

Value | Description
S_OK | The method succeeded.
E_NOTIMPL | The method is not currently implemented.

Expand image Remarks

The semantics of the GUID and the IUnknown are entirely application/debugger defined.

This method allows for custom extensions of the debugger model; it is not currently implemented.

This method causes IApplicationDebugger::onDebuggerEvent to be called.

Expand image See Also

Reference

IApplicationDebugger::onDebuggerEvent

Concepts

IDebugApplication Interface


IDebugApplication::FIsAutoJitDebugEnabled

Microsoft Windows Script Interfaces
IDebugApplication::FIsAutoJitDebugEnabled
See Also
CollapseAll image DropDown image

Determines if a just-in-time (JIT) debugger is registered to auto-debug dumb hosts.

BOOL FIsAutoJitDebugEnabled();

Parameters

This method takes no parameters.

Expand image Return Value

If the method succeeds and a JIT debugger is registered to auto-debug dumb hosts, the method returns TRUE. Otherwise, it returns FALSE.

Expand image Remarks

This method determines if a JIT debugger is registered to auto-debug dumb hosts.

Expand image See Also

Concepts

IDebugApplication Interface


IDebugApplication::GetBreakFlags

Microsoft Windows Script Interfaces
IDebugApplication::GetBreakFlags
See Also
CollapseAll image DropDown image

Returns the current break flags for the application.

HRESULT GetBreakFlags(
   APPBREAKFLAGS*                   pabf,
   IRemoteDebugApplicationThread**  pprdatSteppingThread
);

Parameters

pabf

[out] The current break flags for the application.

pprdatSteppingThread

[out] The currently running thread.

Expand image Return Value

The method returns an HRESULT. Possible values include, but are not limited to, those in the following table.

Value | Description
S_OK | The method succeeded.

Expand image Remarks

This method returns the current break flags for the application.

Expand image See Also

Reference

APPBREAKFLAGS Constants

Concepts

IDebugApplication Interface


IDebugApplication::GetCurrentThread

Microsoft Windows Script Interfaces
IDebugApplication::GetCurrentThread
See Also
CollapseAll image DropDown image

Returns the thread associated with the currently running thread.

HRESULT GetCurrentThread(
   IDebugApplicationThread**  pat
);

Parameters

pat

[out] The thread associated with the currently running thread.

Expand image Return Value

The method returns an HRESULT. Possible values include, but are not limited to, those in the following table.

Value | Description
S_OK | The method succeeded.

Expand image Remarks

This method returns the thread associated with the currently running thread.

Expand image See Also

Concepts

IDebugApplication Interface


IDebugApplication::HandleBreakPoint

Microsoft Windows Script Interfaces
IDebugApplication::HandleBreakPoint
See Also
CollapseAll image DropDown image

Causes the current thread to block and sends a notification of the breakpoint to the debugger IDE.

HRESULT HandleBreakPoint(
   BREAKREASON         br,
   BREAKRESUMEACTION*  pbra
);

Parameters

br

[in] The reason for the break.

pbra

[out] Action to take when the debugger resumes the application.

Expand image Return Value

The method returns an HRESULT. Possible values include, but are not limited to, those in the following table.

Value | Description
S_OK | The method succeeded.

Expand image Remarks

A language engine calls this method in the context of a thread that hits a breakpoint. This method blocks the current thread and sends a breakpoint notification to the debugger IDE. When the debugger resumes the application, the pbra parameter specifies what action to take.

Note Note

The language engine may be called by the thread to do tasks such as enumerate stack frames or evaluate expressions during the breakpoint.

This method causes IApplicationDebugger::onHandleBreakPoint to be called.

Expand image See Also

Reference

IApplicationDebugger::onHandleBreakPoint
BREAKREASON Enumeration
BREAKRESUMEACTION Enumeration

Concepts

IDebugApplication Interface


IDebugApplication::HandleRuntimeError

Microsoft Windows Script Interfaces
IDebugApplication::HandleRuntimeError
See Also
CollapseAll image DropDown image

Causes the current thread to block and sends a notification of the error to the debugger IDE.

HRESULT HandleRuntimeError(
   IActiveScriptErrorDebug*  pErrorDebug,
   IActiveScriptSite*        pScriptSite,
   BREAKRESUMEACTION*        pbra,
   ERRORRESUMEACTION*        perra,
   BOOL*                     pfCallOnScriptError
);

Parameters

pErrorDebug

[in] The error that occurred.

pScriptSite

[in] The script site of the thread.

pbra

[out] Action to take when the debugger resumes the application.

perra

[out] Action to take when the debugger resumes the application if there is an error.

pfCallOnScriptError

[out] Flag which is TRUE if the engine should call the IActiveScriptSite::OnScriptError method.

Expand image Return Value

The method returns an HRESULT. Possible values include, but are not limited to, those in the following table.

Value | Description
S_OK | The method succeeded.

Expand image Remarks

A language engine calls this method in the context of a thread that causes a run-time error. This method causes the current thread to block and sends an error notification to be sent to the debugger IDE. When the debugger IDE resumes the application, this method returns with the action to be taken.

Note Note

While in the run-time fault, the language engine may be called by the thread to do such tasks as enumerate stack frames or evaluate expressions.

Expand image See Also

Reference

BREAKRESUMEACTION Enumeration
ERRORRESUMEACTION Enumeration

Concepts

IDebugApplication Interface
IActiveScriptErrorDebug Interface
IActiveScriptSite


IDebugApplication::QueryCurrentThreadIsDebuggerThread

Microsoft Windows Script Interfaces
IDebugApplication::QueryCurrentThreadIsDebuggerThread
See Also
CollapseAll image DropDown image

Determines if the current running thread is the debugger thread.

HRESULT QueryCurrentThreadIsDebuggerThread();

Parameters

This method takes no parameters.

Expand image Return Value

The method returns an HRESULT. Possible values include, but are not limited to, those in the following table.

Value | Description
S_OK | The method succeeded and the current running thread is the debugger thread.
S_FALSE | The current running thread is not the debugger thread.

Expand image Remarks

This method determines if the current running thread is the debugger thread.

Expand image See Also

Concepts

IDebugApplication Interface


IDebugApplication::RemoveGlobalExpressionContextProvider

Microsoft Windows Script Interfaces
IDebugApplication::RemoveGlobalExpressionContextProvider
See Also
CollapseAll image DropDown image

Removes a global expression context provider from this application.

HRESULT RemoveGlobalExpressionContextProvider(
   DWORD_PTR  dwCookie
);

Parameters

dwCookie

[in] The cookie returned by the AddGlobalExpressionContextProvider method when the global context provider was added.

Expand image Return Value

The method returns an HRESULT. Possible values include, but are not limited to, those in the following table.

Value | Description
S_OK | The method succeeded.

Expand image Remarks

The RemoveGlobalExpressionContextProvider method removes a global expression context provider from this application.

Expand image See Also

Reference

IDebugApplication::AddGlobalExpressionContextProvider

Concepts

IDebugApplication Interface


IDebugApplication::RemoveStackFrameSniffer

Microsoft Windows Script Interfaces
IDebugApplication::RemoveStackFrameSniffer
See Also
CollapseAll image DropDown image

Removes a stack frame enumerator provider from this application.

HRESULT RemoveStackFrameSniffer(
   DWORD  dwCookie
);

Parameters

dwCookie

[in] The cookie returned by the AddStackFrameSniffer method when the stack frame enumerator provider was added.

Expand image Return Value

The method returns an HRESULT. Possible values include, but are not limited to, those in the following table.

Value | Description
S_OK | The method succeeded.

Expand image Remarks

The RemoveStackFrameSniffer method removes a stack frame enumerator provider from this application.

Expand image See Also

Reference

IDebugApplication::AddStackFrameSniffer

Concepts

IDebugApplication Interface
IDebugStackFrameSniffer Interface


IDebugApplication::SetName

Microsoft Windows Script Interfaces
IDebugApplication::SetName
See Also
CollapseAll image DropDown image

Sets the name of the application.

HRESULT SetName(
   LPCOLESTR  pstrName
);

Parameters

pstrName

[in] The name of the application.

Expand image Return Value

The method returns an HRESULT. Possible values include, but are not limited to, those in the following table.

Value | Description
S_OK | The method succeeded.

Expand image Remarks

The name provided to this method is returned in subsequent calls to the IRemoteDebugApplication::GetName method.

This method should be called before calling the IProcessDebugManager::AddApplication method.

Expand image See Also

Reference

IProcessDebugManager::AddApplication

Concepts

IDebugApplication Interface


IDebugApplication::StartDebugSession

Microsoft Windows Script Interfaces
IDebugApplication::StartDebugSession
See Also
CollapseAll image DropDown image

Starts the default debugger integrated development environment (IDE) and attaches a debug session to this application, if one is not already attached.

HRESULT StartDebugSession();

Parameters

This method takes no parameters.

Expand image Return Value

The method returns an HRESULT. Possible values include, but are not limited to, those in the following table.

Value | Description
S_OK | The method succeeded.

Expand image Remarks

This method is used to implement just-in-time debugging.

Expand image See Also

Concepts

IDebugApplication Interface


IDebugApplication::StepOutComplete

Microsoft Windows Script Interfaces
IDebugApplication::StepOutComplete
See Also
CollapseAll image DropDown image

Notifies the process debug manager that a language engine in single-step mode is about to return to its caller.

HRESULT StepOutComplete();

Parameters

This method takes no parameters.

Expand image Return Value

The method returns an HRESULT. Possible values include, but are not limited to, those in the following table.

Value | Description
S_OK | The method succeeded.

Expand image Remarks

Language engines call this method in single-step mode just before they return to their caller. The process debug manager uses this opportunity to notify all other script engines that they should break at the first opportunity. This technique is how cross-language step modes are implemented.

Expand image See Also

Concepts

IDebugApplication Interface


IDebugApplication::SynchronousCallInDebuggerThread

Microsoft Windows Script Interfaces
IDebugApplication::SynchronousCallInDebuggerThread
See Also
CollapseAll image DropDown image

Provides a mechanism for the caller to run code in the debugger thread.

HRESULT SynchronousCallInDebuggerThread(
   IDebugThreadCall*  pptc,
   DWORD_PTR          dwParam1,
   DWORD_PTR          dwParam2,
   DWORD_PTR          dwParam3
);

Parameters

pptc

[in] The object to call.

dwParam1

[in] First parameter to pass to the IDebugThreadCall::ThreadCallHandler method.

dwParam2

[in] Second parameter to pass to the IDebugThreadCall::ThreadCallHandler method.

dwParam3

[in] Third parameter to pass to the IDebugThreadCall::ThreadCallHandler method.

Expand image Return Value

The method returns an HRESULT. Possible values include, but are not limited to, those in the following table.

Value | Description
S_OK | The method succeeded.

Expand image Remarks

Language engines and hosts typically use this method to implement free-threaded objects on top of their single threaded implementations.

Expand image See Also

Concepts

IDebugApplication Interface
IDebugThreadCall Interface


IDebugApplicationNode Interface

Microsoft Windows Script Interfaces
IDebugApplicationNode Interface
DropDown image

The IDebugApplicationNode interface extends the functionality of the IDebugDocumentProvider interface by providing a context within a project tree.

In addition to the methods inherited from IDebugDocumentProvider, the IDebugApplicationNode interface exposes the following methods.

Methods in Vtable order

Method | Description
IDebugApplicationNode::EnumChildren | Enumerates the child nodes of this application node.
IDebugApplicationNode::GetParent | Returns the parent node of this application node.
IDebugApplicationNode::SetDocumentProvider | Sets the document provider for this application node.
IDebugApplicationNode::Close | Causes this application to release all references and enter an inactive state.
IDebugApplicationNode::Attach | Adds this application node to the specified project tree.
IDebugApplicationNode::Detach | Removes this application node from the project tree.


IDebugApplicationNode::Attach

Microsoft Windows Script Interfaces
IDebugApplicationNode::Attach
See Also
CollapseAll image DropDown image

Adds this application node to the specified project tree.

HRESULT Attach(
   IDebugApplicationNode*  pdanParent
);

Parameters

pdanParent

[in] The project tree where this application node is to be added.

Expand image Return Value

The method returns an HRESULT. Possible values include, but are not limited to, those in the following table.

Value | Description
S_OK | The method succeeded.

Expand image Remarks

This method adds this application node to the project tree, using pdanParent as the parent. If pdanParent is NULL, this application node will be the top-level node.

Expand image See Also

Reference

IDebugApplicationNode::Detach

Concepts

IDebugApplicationNode Interface


IDebugApplicationNode::Close

Microsoft Windows Script Interfaces
IDebugApplicationNode::Close
See Also
CollapseAll image DropDown image

Causes this application to release all references and enter an inactive state.

HRESULT Close();

Parameters

This method takes no parameters.

Expand image Return Value

The method returns an HRESULT. Possible values include, but are not limited to, those in the following table.

Value | Description
S_OK | The method succeeded.

Expand image Remarks

Typically, the owner of an application calls this method when the application exits.

Expand image See Also

Concepts

IDebugApplicationNode Interface


IDebugApplicationNode::Detach

Microsoft Windows Script Interfaces
IDebugApplicationNode::Detach
See Also
CollapseAll image DropDown image

Removes this application node from the project tree.

HRESULT Detach();

Parameters

This method takes no parameters.

Expand image Return Value

The method returns an HRESULT. Possible values include, but are not limited to, those in the following table.

Value | Description
S_OK | The method succeeded.

Expand image Remarks

This method removes this application node from the project tree.

Expand image See Also

Reference

IDebugApplicationNode::Attach

Concepts

IDebugApplicationNode Interface


IDebugApplicationNode::EnumChildren

Microsoft Windows Script Interfaces
IDebugApplicationNode::EnumChildren
See Also
CollapseAll image DropDown image

Enumerates the child nodes of this application node.

HRESULT EnumChildren(
   IEnumDebugApplicationNodes**  pperddp
);

Parameters

pperddp

[out] The enumeration of this node's child nodes.

Expand image Return Value

The method returns an HRESULT. Possible values include, but are not limited to, those in the following table.

Value | Description
S_OK | The method succeeded.

Expand image Remarks

This method enumerates the child nodes of this application node.

Expand image See Also

Concepts

IDebugApplicationNode Interface


IDebugApplicationNode::GetParent

Microsoft Windows Script Interfaces
IDebugApplicationNode::GetParent
See Also
CollapseAll image DropDown image

Returns the parent node of this application node.

HRESULT GetParent(
   IDebugApplicationNode**  pprddp
);

Parameters

pprddp

[out] Parent application node of this application node.

Expand image Return Value

The method returns an HRESULT. Possible values include, but are not limited to, those in the following table.

Value | Description
S_OK | The method succeeded.

Expand image Remarks

This method returns the parent node of this application node.

Expand image See Also

Concepts

IDebugApplicationNode Interface


IDebugApplicationNode::SetDocumentProvider

Microsoft Windows Script Interfaces
IDebugApplicationNode::SetDocumentProvider
See Also
CollapseAll image DropDown image

Sets the document provider for this application node.

HRESULT SetDocumentProvider(
   IDebugDocumentProvider*  pddp
);

Parameters

pddp

[in] The document provider for this application node.

Expand image Return Value

The method returns an HRESULT. Possible values include, but are not limited to, those in the following table.

Value | Description
S_OK | The method succeeded.

Expand image Remarks

This method sets the document provider for this application node.

Expand image See Also

Concepts

IDebugApplicationNode Interface


IDebugApplicationNodeEvents Interface

Microsoft Windows Script Interfaces
IDebugApplicationNodeEvents Interface
See Also
DropDown image

Provides the event interface for the IDebugApplicationNode interface.

In addition to the methods inherited from IUnknown, the IDebugApplicationNodeEvents interface exposes the following methods.

Methods in Vtable Order

Method | Description
IDebugApplicationNodeEvents::onAddChild | Handles the event when a child node is added to a debug application node object.
IDebugApplicationNodeEvents::onRemoveChild | Handles the event when a child node is removed from a debug application node object.
IDebugApplicationNodeEvents::onDetach | Handles an event signifying that the debug application node object was detached from a parent node.
IDebugApplicationNodeEvents::onAttach | Handles an event signifying that the debug application node object was attached to a parent node.

See Also

Concepts

IDebugApplicationNode Interface


IDebugApplicationNodeEvents::onAddChild

Microsoft Windows Script Interfaces
IDebugApplicationNodeEvents::onAddChild
See Also
CollapseAll image DropDown image

Handles the event when a child node is added to a debug application node object.

HRESULT onAddChild(
   IDebugApplicationNode*  prddpChild
);

Parameters

prddpChild

[in] The child debug application node that was added.

Expand image Return Value

The method returns an HRESULT. Possible values include, but are not limited to, those in the following table.

Value | Description
S_OK | The method succeeded.

Expand image Remarks

This method handles the event when a child node is added to a debug application node object.

Implementers of the IDebugApplicationNode interface raise this event

Expand image See Also

Reference

IDebugApplicationNodeEvents::onRemoveChild

Concepts

IDebugApplicationNodeEvents Interface
IDebugApplicationNode Interface


IDebugApplicationNodeEvents::onAttach

Microsoft Windows Script Interfaces
IDebugApplicationNodeEvents::onAttach
See Also
CollapseAll image DropDown image

Handles an event signifying that the debug application node object was attached to a parent node.

HRESULT onAttach(
   IDebugApplicationNode*  prddpParent
);

Parameters

prddpParent

[in] The debug application node that is the parent of this node.

Expand image Return Value

The method returns an HRESULT. Possible values include, but are not limited to, those in the following table.

Value | Description
S_OK | The method succeeded.

Expand image Remarks

This method handles an event signifying that the debug application node object was attached to a parent node.

Implementers of the IDebugApplicationNode interface raise this event.

Expand image See Also

Reference

IDebugApplicationNodeEvents::onDetach

Concepts

IDebugApplicationNodeEvents Interface
IDebugApplicationNode Interface


IDebugApplicationNodeEvents::onDetach

Microsoft Windows Script Interfaces
IDebugApplicationNodeEvents::onDetach
See Also
CollapseAll image DropDown image

Handles an event signifying that the debug application node object was detached from a parent node.

HRESULT onDetach();

Parameters

This method takes no parameters.

Expand image Return Value

The method returns an HRESULT. Possible values include, but are not limited to, those in the following table.

Value | Description
S_OK | The method succeeded.

Expand image Remarks

This method handles an event signifying that the debug application node object was detached from a parent node.

Implementers of the IDebugApplicationNode interface raise this event.

Expand image See Also

Reference

IDebugApplicationNodeEvents::onAttach

Concepts

IDebugApplicationNodeEvents Interface
IDebugApplicationNode Interface


IDebugApplicationNodeEvents::onRemoveChild

Microsoft Windows Script Interfaces
IDebugApplicationNodeEvents::onRemoveChild
See Also
CollapseAll image DropDown image

Handles the event when a child node is removed from a debug application node object.

HRESULT onRemoveChild(
   IDebugApplicationNode*  prddpChild
);

Parameters

prddpChild

[in] The child application node that was removed.

Expand image Return Value

The method returns an HRESULT. Possible values include, but are not limited to, those in the following table.

Value | Description
S_OK | The method succeeded.

Expand image Remarks

This method handles the event when a child node is removed from a debug application node object.

Implementers of the IDebugApplicationNode interface raise this event.

Expand image See Also

Reference

IDebugApplicationNodeEvents::onAddChild

Concepts

IDebugApplicationNodeEvents Interface
IDebugApplicationNode Interface


IDebugApplicationThread Interface

Microsoft Windows Script Interfaces
IDebugApplicationThread Interface
DropDown image

Allows language engines and hosts to provide thread synchronization and to maintain thread-specific debug state information. This interface extends the IRemoteDebugApplicationThread interface to provide non-remote access to the thread.

In addition to the methods inherited from IRemoteDebugApplicationThread, the IDebugApplicationThread interface exposes the following methods.

Methods in Vtable Order

Method | Description
IDebugApplicationThread::SynchronousCallIntoThread | Provides a mechanism for the caller to run code in the application thread.
IDebugApplicationThread::QueryIsCurrentThread | Determines if this thread is the currently running thread.
IDebugApplicationThread::QueryIsDebuggerThread | Determines if this thread is the debugger thread.
IDebugApplicationThread::SetDescription | Sets the description of this thread.
IDebugApplicationThread::SetStateString | Sets the description of the thread state.


IDebugApplicationThread::QueryIsCurrentThread

Microsoft Windows Script Interfaces
IDebugApplicationThread::QueryIsCurrentThread
See Also
CollapseAll image DropDown image

Determines if this thread is the currently running thread.

HRESULT QueryIsCurrentThread();

Parameters

This method takes no parameters.

Expand image Return Value

The method returns an HRESULT. Possible values include, but are not limited to, those in the following table.

Value | Description
S_OK | The method succeeded and this is the currently running thread.
S_FALSE | This is not the currently running thread.

Expand image Remarks

This method determines if this thread is the currently running thread.

Expand image See Also

Concepts

IDebugApplicationThread Interface


IDebugApplicationThread::QueryIsDebuggerThread

Microsoft Windows Script Interfaces
IDebugApplicationThread::QueryIsDebuggerThread
See Also
CollapseAll image DropDown image

Determines if this thread is the debugger thread.

HRESULT QueryIsDebuggerThread();

Parameters

This method takes no parameters.

Expand image Return Value

The method returns an HRESULT. Possible values include, but are not limited to, those in the following table.

Value | Description
S_OK | The method succeeded and this is the debugger thread.
S_FALSE | This is not the debugger thread.

Expand image Remarks

This method determines if this thread is the debugger thread.

Expand image See Also

Concepts

IDebugApplicationThread Interface


IDebugApplicationThread::SetDescription

Microsoft Windows Script Interfaces
IDebugApplicationThread::SetDescription
See Also
CollapseAll image DropDown image

Sets the description of this thread.

HRESULT SetDescription(
   LPCOLESTR  pstrDescription
);

Parameters

pstrDescription

[in] The description of this thread.

Expand image Return Value

The method returns an HRESULT. Possible values include, but are not limited to, those in the following table.

Value | Description
S_OK | The method succeeded.

Expand image Remarks

This method sets the description of this thread.

Expand image See Also

Concepts

IDebugApplicationThread Interface


IDebugApplicationThread::SetStateString

Microsoft Windows Script Interfaces
IDebugApplicationThread::SetStateString
See Also
CollapseAll image DropDown image

Sets the description of thread state.

HRESULT SetStateString(
   LPCOLESTR  pstrState
);

Parameters

pstrState

[in] The description of the thread state.

Expand image Return Value

The method returns an HRESULT. Possible values include, but are not limited to, those in the following table.

Value | Description
S_OK | The method succeeded.

Expand image Remarks

This method sets the description of the thread state.

Expand image See Also

Concepts

IDebugApplicationThread Interface


IDebugApplicationThread::SynchronousCallIntoThread

Microsoft Windows Script Interfaces
IDebugApplicationThread::SynchronousCallIntoThread
See Also
CollapseAll image DropDown image

Provides a mechanism for the caller to run code in the application thread.

HRESULT SynchronousCallIntoThread(
   IDebugThreadCall*  pstcb,
   DWORD_PTR          dwParam1,
   DWORD_PTR          dwParam2,
   DWORD_PTR          dwParam3
);

Parameters

pstcb

[in] The object to call.

dwParam1

[in] First parameter to pass to the IDebugThreadCall::ThreadCallHandler method.

dwParam2

[in] Second parameter to pass to the IDebugThreadCall::ThreadCallHandler method.

dwParam3

[in] Third parameter to pass to the IDebugThreadCall::ThreadCallHandler method.

Expand image Return Value

The method returns an HRESULT. Possible values include, but are not limited to, those in the following table.

Value | Description
S_OK | The method succeeded.

Expand image Remarks

This method provides a mechanism for the caller to run code in the debugger thread. Language engines and hosts typically use this method to implement free-threaded objects on top of their single threaded implementations.

Expand image See Also

Concepts

IDebugApplicationThread Interface
IDebugThreadCall Interface


IDebugAsyncOperation Interface

Microsoft Windows Script Interfaces
IDebugAsyncOperation Interface
DropDown image

The Process Debug Manager implements the IDebugAsyncOperation interface. A language engine calls the IDebugApplication::CreateAsyncDebugOperation method to obtain a reference to this interface. The language engine can use the IDebugAsyncOperation interface to provide asynchronous access to a synchronous debug operation.

In addition to the methods inherited from IUnknown, the IDebugAsyncOperation interface exposes the following methods.

Methods in Vtable Order

Method | Description
IDebugAsyncOperation::GetSyncDebugOperation | Returns the synchronous debug operation associated with this object.
IDebugAsyncOperation::Start | Causes the asynchronous operation to begin.
IDebugAsyncOperation::Abort | Cancels an operation.
IDebugAsyncOperation::QueryIsComplete | Determines if the debug operation has completed.
IDebugAsyncOperation::GetResult | Provides the return value and return object parameter from the synchronous debug operation.


IDebugAsyncOperation::Abort

Microsoft Windows Script Interfaces
IDebugAsyncOperation::Abort
See Also
CollapseAll image DropDown image

Cancels an operation.

HRESULT Abort();

Parameters

This method takes no parameters.

Expand image Return Value

The method returns an HRESULT. Possible values include, but are not limited to, those in the following table.

Value | Description
S_OK | The method succeeded.
E_NOTIMPL | The operations cannot be canceled.

Expand image Remarks

This method is typically called from within the debugger thread to cancel an unresponsive operation. This method causes the InProgressAbort method on the IDebugSyncOperation object to be called.

Expand image See Also

Reference

IDebugAsyncOperation::Start
IDebugSyncOperation::InProgressAbort

Concepts

IDebugAsyncOperation Interface


IDebugAsyncOperation::GetResult

Microsoft Windows Script Interfaces
IDebugAsyncOperation::GetResult
See Also
CollapseAll image DropDown image

Provides the return value and return object parameter from the synchronous debug operation.

HRESULT GetResult(
   HRESULT*    phrResult,
   IUnknown**  ppunkResult
);

Parameters

phrResult

[out] If the operation is complete, phrResult is the return value of IDebugSyncOperation::Execute.

ppunkResult

[out] If the operation is complete, ppunkResult is the object parameter returned by the operation.

Expand image Return Value

The method returns an HRESULT. Possible values include, but are not limited to, those in the following table.

Value | Description
S_OK | The method succeeded.
E_PENDING | The operation has not completed.

Expand image Remarks

If the operation has completed, this method returns the HRESULT and object parameter from IDebugSyncOperation::Execute.

Expand image See Also

Reference

IDebugSyncOperation::Execute

Concepts

IDebugAsyncOperation Interface


IDebugAsyncOperation::GetSyncDebugOperation

Microsoft Windows Script Interfaces
IDebugAsyncOperation::GetSyncDebugOperation
See Also
CollapseAll image DropDown image

Returns the synchronous debug operation associated with this object.

HRESULT GetSyncDebugOperation(
   IDebugSyncOperation**  ppsdo
);

Parameters

ppsdo

[out] The synchronous debug operation associated with this object.

Expand image Return Value

The method returns an HRESULT. Possible values include, but are not limited to, those in the following table.

Value | Description
S_OK | The method succeeded.

Expand image Remarks

This method returns the synchronous debug operation associated with this object.

Expand image See Also

Concepts

IDebugAsyncOperation Interface


IDebugAsyncOperation::QueryIsComplete

Microsoft Windows Script Interfaces
IDebugAsyncOperation::QueryIsComplete
See Also
CollapseAll image DropDown image

Determines if the debug operation has completed.

HRESULT QueryIsComplete();

Parameters

This method takes no parameters.

Expand image Return Value

The method returns an HRESULT. Possible values include, but are not limited to, those in the following table.

Value | Description
S_OK | The operation is complete.
S_FALSE | The operation is not complete.

Expand image Remarks

This method determines if the debug operation has completed.

Expand image See Also

Concepts

IDebugAsyncOperation Interface


IDebugAsyncOperation::Start

Microsoft Windows Script Interfaces
IDebugAsyncOperation::Start
See Also
CollapseAll image DropDown image

Causes the asynchronous operation to begin.

HRESULT Start(
   IDebugAsyncOperationCallBack*  padocb
);

Parameters

padocb

The callback interface that receives status events from this operation.

Expand image Return Value

The method returns an HRESULT. Possible values include, but are not limited to, those in the following table.

Value | Description
S_OK | The method succeeded.
E_UNEXPECTED | An operation is already pending.

Expand image Remarks

This method causes IDebugSyncOperation::Execute to be called asynchronously in the thread obtained from IDebugSyncOperation::GetTargetThread. This method should be called only from within the debugger thread; otherwise, it will not return until the operation is complete.

Expand image See Also

Reference

IDebugAsyncOperation::Abort
IDebugSyncOperation::Execute
IDebugSyncOperation::GetTargetThread

Concepts

IDebugAsyncOperation Interface


IDebugAsyncOperationCallBack Interface

Microsoft Windows Script Interfaces
IDebugAsyncOperationCallBack Interface
DropDown image

Provides status events related to progress of an IDebugAsyncOperation interface evaluation.

Methods

In addition to the methods inherited from IUnknown, the IDebugAsyncOperationCallBack interface exposes the following methods.

Method | Description
IDebugAsyncOperationCallBack::onComplete | Signals that a result is available from an asynchronous debug operation.


IDebugAsyncOperationCallBack::onComplete

Microsoft Windows Script Interfaces
IDebugAsyncOperationCallBack::onComplete
See Also
CollapseAll image DropDown image

Signals that a result is available from an asynchronous debug operation.

HRESULT onComplete();

Parameters

This method takes no parameters.

Expand image Return Value

The method returns an HRESULT. Possible values include, but are not limited to, those in the following table.

Value | Description
S_OK | The method succeeded.

Expand image Remarks

This method signals that a result is available from an IDebugAsyncOperation object. The event fires in the debugger thread.

Expand image See Also

Concepts

IDebugAsyncOperationCallBack Interface
IDebugAsyncOperation Interface


IDebugCodeContext Interface

Microsoft Windows Script Interfaces
IDebugCodeContext Interface
DropDown image

An abstraction that represents a position in executable code.

In addition to the methods inherited from IUnknown, the IDebugCodeContext interface exposes the following methods.

Methods in Vtable Order

Method | Description
IDebugCodeContext::GetDocumentContext | Returns the document context associated with this code context.
IDebugCodeContext::SetBreakPoint | Sets or clears a breakpoint at this code context.


IDebugCodeContext::GetDocumentContext

Microsoft Windows Script Interfaces
IDebugCodeContext::GetDocumentContext
See Also
CollapseAll image DropDown image

Returns the document context associated with this code context.

HRESULT GetDocumentContext(
   IDebugDocumentContext**  ppsc
);

Parameters

ppsc

[out] The document context associated with this code context.

Expand image Return Value

The method returns an HRESULT. Possible values include, but are not limited to, those in the following table.

Value | Description
S_OK | The method succeeded.

Expand image Remarks

For text documents, the character-position range should include the text for the entire statement. This allows the debugger IDE to highlight the current source statement.

Expand image See Also

Concepts

IDebugCodeContext Interface


IDebugCodeContext::SetBreakPoint

Microsoft Windows Script Interfaces
IDebugCodeContext::SetBreakPoint
See Also
CollapseAll image DropDown image

Sets or clears a breakpoint at this code context.

HRESULT SetBreakPoint(
   BREAKPOINT_STATE  bps
);

Parameters

bps

[in] Specifies the breakpoint state for this code context.

Expand image Return Value

The method returns an HRESULT. Possible values include, but are not limited to, those in the following table.

Value | Description
S_OK | The method succeeded.

Expand image Remarks

This method sets or clears a breakpoint at this code context.

Expand image See Also

Reference

BREAKPOINT_STATE Enumeration

Concepts

IDebugCodeContext Interface


IDebugCookie Interface

Microsoft Windows Script Interfaces
IDebugCookie Interface
See Also
DropDown image

Allows the debug cookie to be set, for use with the IMachineDebugManagerCookie interface. For more information, see IMachineDebugManagerCookie Interface. This interface is implemented by the Process Debug Manager (PDM) and consumed by script debuggers.

Methods

In addition to the methods inherited from IUnknown, the IDebugCookie interface exposes the following methods.

Method | Description
IDebugCookie::SetDebugCookie | Sets the debug application cookie.

See Also

Concepts

IMachineDebugManagerCookie Interface


IDebugCookie::SetDebugCookie

Microsoft Windows Script Interfaces
IDebugCookie::SetDebugCookie
See Also
CollapseAll image DropDown image

Sets the debug application cookie.

HRESULT SetDebugCookie(
   DWORD  dwDebugAppCookie
);

Parameters

dwDebugAppCookie

[in] A cookie that identifies the debug application.

Expand image Return Value

The method returns an HRESULT. Possible values include, but are not limited to, those in the following table.

Value | Description
S_OK | The method succeeded.

Expand image Remarks

This method sets the debug application cookie, which allows more than one debugger to attach to a process.

Expand image See Also

Concepts

IDebugCookie Interface


IDebugDocument Interface

Microsoft Windows Script Interfaces
IDebugDocument Interface
DropDown image

The base interface for all debug documents.

Remarks

The IDebugDocument interface exposes only the methods inherited from IDebugDocumentInfo Interface. It does not expose any additional methods.


IDebugDocumentContext Interface

Microsoft Windows Script Interfaces
IDebugDocumentContext Interface
DropDown image

Provides an abstract representation of a portion of the document being debugged. For text documents, this representation consists of a character-position range.

In addition to the methods inherited from IUnknown, the IDebugDocumentContext interface exposes the following methods.

Methods in Vtable Order

Method | Description
IDebugDocumentContext::GetDocument | Returns the document that contains this context.
IDebugDocumentContext::EnumCodeContexts | Enumerates the code contexts associated with this document context.


IDebugDocumentContext::EnumCodeContexts

Microsoft Windows Script Interfaces
IDebugDocumentContext::EnumCodeContexts
See Also
CollapseAll image DropDown image

Enumerates the code contexts associated with this document context.

HRESULT EnumCodeContexts(
   IEnumDebugCodeContexts**  ppescc
);

Parameters

ppescc

[out] The code contexts associated with this document context.

Expand image Return Value

The method returns an HRESULT. Possible values include, but are not limited to, those in the following table.

Value | Description
S_OK | The method succeeded.

Expand image Remarks

A document is usually associated with only one code context, unless the document is an include file or a template.

Expand image See Also

Concepts

IDebugDocumentContext Interface


IDebugDocumentContext::GetDocument

Microsoft Windows Script Interfaces
IDebugDocumentContext::GetDocument
See Also
CollapseAll image DropDown image

Returns the document that contains this context.

HRESULT GetDocument(
   IDebugDocument**  ppsd
);

Parameters

ppsd

[out] The document that contains this context.

Expand image Return Value

The method returns an HRESULT. Possible values include, but are not limited to, those in the following table.

Value | Description
S_OK | The method succeeded.

Expand image Remarks

The GetDocument method returns the document that contains this context.

Expand image See Also

Concepts

IDebugDocumentContext Interface


IDebugDocumentHelper Interface

Microsoft Windows Script Interfaces
IDebugDocumentHelper Interface
DropDown image

Provide implementations for many interfaces necessary for smart hosting, such as the IDebugDocument, IDebugDocumentContext, IDebugDocumentProvider, IDebugDocumentText, and IDebugDocumentTextEvents interfaces.

In addition to the methods inherited from IUnknown, the IDebugDocumentHelper interface exposes the following methods.

Methods in Vtable Order

Method | Description
IDebugDocumentHelper::Init | Initializes a debug document helper with a name and initial attributes.
IDebugDocumentHelper::Attach | Adds this document to the document tree.
IDebugDocumentHelper::Detach | Removes this document from the document tree.
IDebugDocumentHelper::AddUnicodeText | Appends a Unicode string to end of this document.
IDebugDocumentHelper::AddDBCSText | Appends a DBCS string to end of this document.
IDebugDocumentHelper::SetDebugDocumentHost | Sets the IDebugDocumentHost for this document.
IDebugDocumentHelper::AddDeferredText | Notifies the helper that the given text is available, but it does not provide the characters.
IDebugDocumentHelper::DefineScriptBlock | Signifies to the helper that a particular range of characters is a script block handled by the given script engine.
IDebugDocumentHelper::SetDefaultTextAttr | Sets the default attributes to use for text that is not in a script block.
IDebugDocumentHelper::SetTextAttributes | Sets the attributes on a range of text.
IDebugDocumentHelper::SetLongName | Sets the long name for the document.
IDebugDocumentHelper::SetShortName | Sets the short name for the document.
IDebugDocumentHelper::SetDocumentAttr | Sets the attributes for this document.
IDebugDocumentHelper::GetDebugApplicationNode | Returns the debug application node corresponding to this document.
IDebugDocumentHelper::GetScriptBlockInfo | Retrieves the range of characters and the script engine corresponding to a script block.
IDebugDocumentHelper::CreateDebugDocumentContext | Creates a new debug document context.
IDebugDocumentHelper::BringDocumentToTop | Brings this document to the top in the debugger user interface.
IDebugDocumentHelper::BringDocumentContextToTop | Brings a context of this document to the top in the debugger user interface.


IDebugDocumentHelper::AddDBCSText

Microsoft Windows Script Interfaces
IDebugDocumentHelper::AddDBCSText
See Also
CollapseAll image DropDown image

Appends a DBCS string to the end of this document.

HRESULT AddDBCSText(
   LPCSTR  pszText
);

Parameters

pszText

[in] Pointer to a null-terminated string containing the text.

Expand image Return Value

The method returns an HRESULT. Possible values include, but are not limited to, those in the following table.

Value | Description
S_OK | The method succeeded.
E_FAIL | The method was unable to add the characters.

Expand image Remarks

This method generates IDebugDocumentTextEvents notifications.

Note Note

If this method is called after IDebugDocumentHelper::AddDeferredText has been called, E_FAIL is returned.

Expand image See Also

Reference

IDebugDocumentHelper::AddDeferredText

Concepts

IDebugDocumentHelper Interface
IDebugDocumentTextEvents Interface


IDebugDocumentHelper::AddDeferredText

Microsoft Windows Script Interfaces
IDebugDocumentHelper::AddDeferredText
See Also
CollapseAll image DropDown image

Notifies the helper that the given text is available, but it does not provide the characters.

HRESULT AddDeferredText(
   ULONG  cChars,
   DWORD  dwTextStartCookie
);

Parameters

cChars

[in] Number of (Unicode) characters to add.

dwTextStartCookie

[in] Host-defined cookie that represents the starting position of the text.

Expand image Return Value

The method returns an HRESULT. Possible values include, but are not limited to, those in the following table.

Value | Description
S_OK | The method succeeded.
E_FAIL | The method failed.

Expand image Remarks

This method allows the host to defer providing the characters to add until they are needed, while allowing the helper to generate accurate notifications and size information. The dwTextStartCookie parameter is a cookie, defined by the host, which represents the starting position of the text. Subsequent calls to IDebugDocumentText::GetText must provide this cookie. For example, in a host that represents text in DBCS, the cookie could be a byte offset.

It is assumed that a single call to IDebugDocumentText::GetText can get characters from multiple calls to AddDeferredText. Helper classes may also ask for the same range of deferred characters more than once.

Note Note

Calls to AddDeferredText should not be mixed with calls to AddUnicodeText or AddDBCSText. If this occurs, E_FAIL is returned.

Expand image See Also

Reference

IDebugDocumentHelper::AddUnicodeText
IDebugDocumentHelper::AddDBCSText
IDebugDocumentText::GetText

Concepts

IDebugDocumentHelper Interface


IDebugDocumentHelper::AddUnicodeText

Microsoft Windows Script Interfaces
IDebugDocumentHelper::AddUnicodeText
See Also
CollapseAll image DropDown image

Appends a Unicode string to the end of this document.

HRESULT AddUnicodeText(
   LPCOLESTR  pszText
);

Parameters

pszText

[in] Pointer to a null-terminated string containing the text.

Expand image Return Value

The method returns an HRESULT. Possible values include, but are not limited to, those in the following table.

Value | Description
S_OK | The method succeeded.
E_FAIL | The method was unable to add the characters.

Expand image Remarks

This method generates IDebugDocumentTextEvents notifications.

Note Note

If this method is called after AddDeferredText has been called, E_FAIL is returned.

Expand image See Also

Reference

IDebugDocumentHelper::AddDeferredText

Concepts

IDebugDocumentHelper Interface
IDebugDocumentTextEvents Interface


IDebugDocumentHelper::Attach

Microsoft Windows Script Interfaces
IDebugDocumentHelper::Attach
See Also
CollapseAll image DropDown image

Adds this document to the document tree.

HRESULT Attach(
   IDebugDocumentHelper*  pddhParent
);

Parameters

pddhParent

[in] The document tree where this document will be added. May be NULL.

Expand image Return Value

The method returns an HRESULT. Possible values include, but are not limited to, those in the following table.

Value | Description
S_OK | The method succeeded.

Expand image Remarks

This method adds this document to the document tree, using pddhParent as the parent. If the pddhParent is NULL, this document will be the top-level document.

Expand image See Also

Reference

IDebugDocumentHelper::Detach

Concepts

IDebugDocumentHelper Interface


IDebugDocumentHelper::BringDocumentContextToTop

Microsoft Windows Script Interfaces
IDebugDocumentHelper::BringDocumentContextToTop
See Also
CollapseAll image DropDown image

Brings a context of this document to the top in the debugger user interface.

HRESULT BringDocumentContextToTop(
   IDebugDocumentContext*  pddc
);

Parameters

pddc

Document context to bring to the top in the debugger user interface.

Expand image Return Value

The method returns an HRESULT. Possible values include, but are not limited to, those in the following table.

Value | Description
S_OK | The method succeeded.

Expand image Remarks

This method brings a context of this document to the top in the debugger user interface.

Expand image See Also

Concepts

IDebugDocumentHelper Interface


IDebugDocumentHelper::BringDocumentToTop

Microsoft Windows Script Interfaces
IDebugDocumentHelper::BringDocumentToTop
See Also
CollapseAll image DropDown image

Brings this document to the top in the debugger user interface.

HRESULT BringDocumentToTop();

Parameters

This method takes no parameters.

Expand image Return Value

The method returns an HRESULT. Possible values include, but are not limited to, those in the following table.

Value | Description
S_OK | The method succeeded.

Expand image Remarks

This method starts the debugger if it is not already started.

Expand image See Also

Concepts

IDebugDocumentHelper Interface


IDebugDocumentHelper::CreateDebugDocumentContext

Microsoft Windows Script Interfaces
IDebugDocumentHelper::CreateDebugDocumentContext
See Also
CollapseAll image DropDown image

Creates a new debug document context.

HRESULT CreateDebugDocumentContext(
   ULONG                    iCharPos,
   ULONG                    cChars,
   IDebugDocumentContext**  ppddc
);

Parameters

iCharPos

[in] Location of the start of the debug document content.

cChars

[in] Number of characters in the context.

ppddc

[out] The new debug document context.

Expand image Return Value

The method returns an HRESULT. Possible values include, but are not limited to, those in the following table.

Value | Description
S_OK | The method succeeded.

Expand image Remarks

This method allows the host to create a new debug document context.

Expand image See Also

Concepts

IDebugDocumentHelper Interface


IDebugDocumentHelper::DefineScriptBlock

Microsoft Windows Script Interfaces
IDebugDocumentHelper::DefineScriptBlock
See Also
CollapseAll image DropDown image

Indicates to the helper that a particular range of characters is a script block that is handled by the given script engine.

HRESULT DefineScriptBlock(
   ULONG           ulCharOffset,
   ULONG           cChars,
   IActiveScript*  pas,
   BOOL            fScriptlet,
   DWORD_PTR*      pdwSourceContext
);

Parameters

ulCharOffset

[in] Location of the start of the script block.

cChars

[in] Number of characters in the script block.

pas

[in] The script engine for this script block.

fScriptlet

[in] Flag that indicates if the script block is a scriptlet.

pdwSourceContext

[out] The source context for the script block.

Expand image Return Value

The method returns an HRESULT. Possible values include, but are not limited to, those in the following table.

Value | Description
S_OK | The method succeeded.

Expand image Remarks

A smart host can use this method when its documents contain embedded script blocks. A language engine can use this method when its code contains embedded scripts for other languages.

The script engine is responsible for all syntax coloring and code context lookups in the script block.

The DefineScriptBlock method should be called after the text has been added (for example, using the IDebugDocumentHelper::AddDBCSText method) but before the script block has been parsed (for example, using the IActiveScriptParse ::ParseScriptText method).

Expand image See Also

Reference

IDebugDocumentHelper::AddDBCSText
IDebugDocumentHelper::AddUnicodeText

Concepts

IDebugDocumentHelper Interface


IDebugDocumentHelper::Detach

Microsoft Windows Script Interfaces
IDebugDocumentHelper::Detach
See Also
CollapseAll image DropDown image

Removes this document from the document tree.

HRESULT Detach();

Parameters

This method takes no parameters.

Expand image Return Value

The method returns an HRESULT. Possible values include, but are not limited to, those in the following table.

Value | Description
S_OK | The method succeeded.

Expand image Remarks

This method removes this document from the document tree.

Expand image See Also

Reference

IDebugDocumentHelper::Attach

Concepts

IDebugDocumentHelper Interface


IDebugDocumentHelper::GetDebugApplicationNode

Microsoft Windows Script Interfaces
IDebugDocumentHelper::GetDebugApplicationNode
See Also
CollapseAll image DropDown image

Returns the debug application node corresponding to this document.

HRESULT GetDebugApplicationNode(
   IDebugApplicationNode**  ppdan
);

Parameters

ppdan

[out] The debug application node corresponding to this document.

Expand image Return Value

The method returns an HRESULT. Possible values include, but are not limited to, those in the following table.

Value | Description
S_OK | The method succeeded.

Expand image Remarks

Return the debug application node corresponding to this document.

Expand image See Also

Concepts

IDebugDocumentHelper Interface


IDebugDocumentHelper::GetScriptBlockInfo

Microsoft Windows Script Interfaces
IDebugDocumentHelper::GetScriptBlockInfo
See Also
CollapseAll image DropDown image

Retrieves the range of characters and the script engine corresponding to a script block.

HRESULT GetScriptBlockInfo(
   DWORD_PTR        dwSourceContext,
   IActiveScript**  ppasd,
   ULONG*           piCharPos,
   ULONG*           pcChars
);

Parameters

dwSourceContext

[in] The source context for the script block.

ppasd

[out] The script engine for this script block.

piCharPos

[out] Location of the start of the script block.

cChars

[out] Number of characters in the script block.

Expand image Return Value

The method returns an HRESULT. Possible values include, but are not limited to, those in the following table.

Value | Description
S_OK | The method succeeded.

Expand image Remarks

This method retrieves the range of characters and the script engine corresponding to a script block.

Expand image See Also

Concepts

IDebugDocumentHelper Interface


IDebugDocumentHelper::Init

Microsoft Windows Script Interfaces
IDebugDocumentHelper::Init
See Also
CollapseAll image DropDown image

The Init method initializes a debug document helper with a name and initial attributes.

HRESULT Init(
   IDebugApplication*  pda,
   LPCOLESTR           pszShortName,
   LPCOLESTR           pszLongName,
   TEXT_DOC_ATTR       docAttr
);

Parameters

pda

[in] The debug application associated with this document.

pszShortName

[in] A null-terminated string containing the short name of the document.

pszLongName

[in] A null-terminated string containing the long name of the document.

docAttr

[in] Specifies text document attributes.

Expand image Return Value

The method returns an HRESULT. Possible values include, but are not limited to, those in the following table.

Value | Description
S_OK | The method succeeded.

Expand image Remarks

This method initializes a debug document helper with a name and initial attributes.

This document does not appear in the tree until IDebugDocumentHelper::Attach is called.

Expand image See Also

Reference

IDebugDocumentHelper::Attach
TEXT_DOC_ATTR Constants

Concepts

IDebugDocumentHelper Interface


IDebugDocumentHelper::SetDebugDocumentHost

Microsoft Windows Script Interfaces
IDebugDocumentHelper::SetDebugDocumentHost
See Also
CollapseAll image DropDown image

Sets the IDebugDocumentHost for this document.

HRESULT SetDebugDocumentHost(
   IDebugDocumentHost*  pddh
);

Parameters

pddh

[in] The debug document host.

Expand image Return Value

The method returns an HRESULT. Possible values include, but are not limited to, those in the following table.

Value | Description
S_OK | The method succeeded.

Expand image Remarks

The IDebugDocumentHost interface is used for smart-host syntax coloring, fetching deferred text, and returning controlling objects for newly created document contexts.

Expand image See Also

Concepts

IDebugDocumentHelper Interface
IDebugDocumentHost Interface


IDebugDocumentHelper::SetDefaultTextAttr

Microsoft Windows Script Interfaces
IDebugDocumentHelper::SetDefaultTextAttr
See Also
CollapseAll image DropDown image

Sets the default attributes to use for text that is not in a script block.

HRESULT SetDefaultTextAttr(
   SOURCE_TEXT_ATTR  staTextAttr
);

Parameters

staTextAttr

The default source text attributes.

Expand image Return Value

The method returns an HRESULT. Possible values include, but are not limited to, those in the following table.

Value | Description
S_OK | The method succeeded.

Expand image Remarks

Unless the default attributes are changed by this method, the default attributes for text outside a script block is SOURCETEXT_ATTR_NONSOURCE. The user interface can use this information to mark text outside script blocks as read-only.

Expand image See Also

Reference

SOURCE_TEXT_ATTR Constants

Concepts

IDebugDocumentHelper Interface


IDebugDocumentHelper::SetDocumentAttr

Microsoft Windows Script Interfaces
IDebugDocumentHelper::SetDocumentAttr
See Also
CollapseAll image DropDown image

Sets the attributes for this document.

HRESULT SetDocumentAttr(
   TEXT_DOC_ATTR  pszAttributes
);

Parameters

pszAttributes

[in] The attributes to apply to the document.

Expand image Return Value

The method returns an HRESULT. Possible values include, but are not limited to, those in the following table.

Value | Description
S_OK | The method succeeded.

Expand image Remarks

This method sets the attributes for this document.

Expand image See Also

Reference

TEXT_DOC_ATTR Constants

Concepts

IDebugDocumentHelper Interface


IDebugDocumentHelper::SetLongName

Microsoft Windows Script Interfaces
IDebugDocumentHelper::SetLongName
See Also
CollapseAll image DropDown image

Sets the long name for the document.

HRESULT SetLongName(
   LPCOLESTR  pszLongName
);

Parameters

pszLongName

[in] A null-terminated string containing the long name of the document.

Expand image Return Value

The method returns an HRESULT. Possible values include, but are not limited to, those in the following table.

Value | Description
S_OK | The method succeeded.

Expand image Remarks

This method sets a new long name for the document.

Expand image See Also

Concepts

IDebugDocumentHelper Interface


IDebugDocumentHelper::SetShortName

Microsoft Windows Script Interfaces
IDebugDocumentHelper::SetShortName
See Also
CollapseAll image DropDown image

Sets the short name for the document.

HRESULT SetShortName(
   LPCOLESTR  pszShortName
);

Parameters

pszShortName

[in] A null-terminated string containing the short name of the document.

Expand image Return Value

The method returns an HRESULT. Possible values include, but are not limited to, those in the following table.

Value | Description
S_OK | The method succeeded.

Expand image Remarks

This method sets a new short name for the document.

Expand image See Also

Concepts

IDebugDocumentHelper Interface


IDebugDocumentHelper::SetTextAttributes

Microsoft Windows Script Interfaces
IDebugDocumentHelper::SetTextAttributes
See Also
CollapseAll image DropDown image

Sets the attributes on a range of text, overriding other attributes on that text.

HRESULT SetTextAttributes(
   ULONG              ulCharOffset,
   ULONG              cChars,
   SOURCE_TEXT_ATTR*  pstaTextAttr
);

Parameters

ulCharOffset

[in] The location of the start of the text range.

cChars

[in] The number of characters in the range.

pstaTextAttr

[in] The source text attributes for the range of text.

Expand image Return Value

The method returns an HRESULT. Possible values include, but are not limited to, those in the following table.

Value | Description
S_OK | The method succeeded.

Expand image Remarks

It is an error to call SetTextAttributes on a text range before that text is added to the document. Call the AddDBCSText, AddUnicodeText, or AddDeferredText methods to add text to the document.

Expand image See Also

Reference

IDebugDocumentHelper::AddUnicodeText
IDebugDocumentHelper::AddDBCSText
IDebugDocumentHelper::AddDeferredText
SOURCE_TEXT_ATTR Constants

Concepts

IDebugDocumentHelper Interface


IDebugDocumentHost Interface

Microsoft Windows Script Interfaces
IDebugDocumentHost Interface
DropDown image

Exposes host-specific functionality, such as syntax coloring, to the debugger. The IDebugDocumentHelper::SetDebugDocumentHost method takes this interface as an argument.

In addition to the methods inherited from IUnknown, the IDebugDocumentHost interface exposes the following methods.

Methods in Vtable Order

Method | Description
IDebugDocumentHost::GetDeferredText | Returns a range of characters that were added by using IDebugDocumentHelper::AddDeferredText, in the original host document.
IDebugDocumentHost::GetScriptTextAttributes | Returns the text attributes for a block of document text.
IDebugDocumentHost::OnCreateDocumentContext | Notifies the host that a new document context is being created, and allows the host to optionally return an object that controls the new context.
IDebugDocumentHost::GetPathName | Returns the full path (including the file name) of the document's source file.
IDebugDocumentHost::GetFileName | Returns the name of the document, without path information.
IDebugDocumentHost::NotifyChanged | Notifies the host that the document's source file has been saved and that its contents should be refreshed.


IDebugDocumentHost::GetDeferredText

Microsoft Windows Script Interfaces
IDebugDocumentHost::GetDeferredText
See Also
CollapseAll image DropDown image

Returns a range of characters that were added by using the IDebugDocumentHelper::AddDeferredText method, in the original host document.

HRESULT GetDeferredText(
   DWORD              dwTextStartCookie,
   WCHAR*             pcharText,
   SOURCE_TEXT_ATTR*  pstaTextAttr,
   ULONG*             pcNumChars,
   ULONG              cMaxChars
);

Parameters

dwTextStartCookie

[in] Host-defined cookie that represents the starting position of the text.

pcharText

[in, out] A character text buffer. This method does not return characters if this parameter is NULL.

pstaTextAttr

[in, out] A character attribute buffer. This method does not return attributes if this parameter is NULL.

pcNumChars

[in, out] Indicates the actual number of characters/attributes returned. This parameter must be set to zero before calling this method.

cMaxChars

[in] The maximum number of characters to return.

Expand image Return Value

The method returns an HRESULT. Possible values include, but are not limited to, those in the following table.

Value | Description
S_OK | The method succeeded.
E_NOTIMPL | The method is not implemented.

Expand image Remarks

This method may return E_NOTIMPL, if the host does not call IDebugDocumentHelper::AddDeferredText.

Note Note

This method returns the text from the original document. The host does not keep track of edits or other changes to the document.

Expand image See Also

Reference

IDebugDocumentHelper::AddDeferredText
SOURCE_TEXT_ATTR Constants

Concepts

IDebugDocumentHost Interface


IDebugDocumentHost::GetFileName

Microsoft Windows Script Interfaces
IDebugDocumentHost::GetFileName
See Also
CollapseAll image DropDown image

Returns the name of the document without path information.

HRESULT GetFileName(
   BSTR*  pbstrShortName
);

Parameters

pbstrShortName

[out] A string containing the short name of the document.

Expand image Return Value

The method returns an HRESULT. Possible values include, but are not limited to, those in the following table.

Value | Description
S_OK | The method succeeded.

Expand image Remarks

This method returns the short name of the document without path information. The short name is typically used in situations such as the Save As... dialog box.

Expand image See Also

Concepts

IDebugDocumentHost Interface


IDebugDocumentHost::GetPathName

Microsoft Windows Script Interfaces
IDebugDocumentHost::GetPathName
See Also
CollapseAll image DropDown image

Returns the full path and file name of the document's source file.

HRESULT GetPathName(
   BSTR*  pbstrLongName,
   BOOL*  pfIsOriginalFile
);

Parameters

pbstrLongName

[out] A string containing the long name.

pfIsOriginalFile

[out] A flag that is true if pbstrLongName refers to the original file for the document, false otherwise.

Expand image Return Value

The method returns an HRESULT. Possible values include, but are not limited to, those in the following table.

Value | Description
S_OK | The method succeeded.
E_FAIL | No source file can be created or determined.

Expand image Remarks

This method returns the full path and file name of the document's source file.

Expand image See Also

Concepts

IDebugDocumentHost Interface


IDebugDocumentHost::GetScriptTextAttributes

Microsoft Windows Script Interfaces
IDebugDocumentHost::GetScriptTextAttributes
See Also
CollapseAll image DropDown image

Returns the text attributes for a block of document text.

HRESULT GetScriptTextAttributes(
   LPCOLESTR          pstrCode,
   ULONG              uNumCodeChars,
   LPCOLESTR          pstrDelimiter,
   DWORD              dwFlags,
   SOURCE_TEXT_ATTR*  pattr
);

Parameters

pstrCode

[in] The script block text. This string does not need to be null terminated.

uNumCodeChars

[in] The number of characters in the script block text.

pstrDelimiter

[in] Address of the end-of-script-block delimiter. When pstrCode is parsed from a stream of text, the host typically uses a delimiter, such as two single quotation marks (''), to detect the end of the script block. This parameter specifies the delimiter that the host used, allowing the scripting engine to provide some conditional primitive preprocessing (for example, replacing a single quotation mark ['] with two single quotation marks for use as a delimiter). Exactly how (and if) the scripting engine uses this information depends on the scripting engine. Set this parameter to NULL if the host did not use a delimiter to mark the end of the script block.

dwFlags

[in] Flags associated with the script block. Can be a combination of these values:

Constant Value Description

GETATTRTYPE_DEPSCAN

0x0001

Indicates that identifiers and dot operators should be identified with the SOURCETEXT_ATTR_IDENTIFIER and SOURCETEXT_ATTR_MEMBERLOOKUP flags, respectively.

GETATTRFLAG_THIS

0x0100

Indicates that the identifier for the current object should be identified with the SOURCETEXT_ATTR_THIS flag.

GETATTRFLAG_HUMANTEXT

0x8000

Indicates that string content and comment text should be identified with the SOURCETEXT_ATTR_HUMANTEXT flag.
pattr

[in, out] Buffer to contain the returned attributes.

Expand image Return Value

The method returns an HRESULT. Possible values include, but are not limited to, those in the following table.

Value | Description
S_OK | The method succeeded.
E_NOTIMPL | The host uses only default attributes.

Expand image Remarks

This method returns the text attributes for an arbitrary block of document text. It is acceptable for hosts to return E_NOTIMPL, in which case the default attributes are used.

Expand image See Also

Reference

SOURCE_TEXT_ATTR Constants

Concepts

IDebugDocumentHost Interface


IDebugDocumentHost::NotifyChanged

Microsoft Windows Script Interfaces
IDebugDocumentHost::NotifyChanged
See Also
CollapseAll image DropDown image

Notifies the host that the document's source file has been saved and that its contents should be refreshed.

HRESULT NotifyChanged();

Parameters

This method takes no parameters.

Expand image Return Value

The method returns an HRESULT. Possible values include, but are not limited to, those in the following table.

Value | Description
S_OK | The method succeeded.

Expand image Remarks

This method notifies the host that the document's source file has been saved and that its contents should be refreshed.

Expand image See Also

Concepts

IDebugDocumentHost Interface


IDebugDocumentHost::OnCreateDocumentContext

Microsoft Windows Script Interfaces
IDebugDocumentHost::OnCreateDocumentContext
See Also
CollapseAll image DropDown image

Notifies the host that a new document context is being created and allows the host to optionally return a controlling unknown for the new context.

HRESULT OnCreateDocumentContext(
   IUnknown**  ppunkOuter
);

Parameters

ppunkOuter

[out] An object that controls the new context.

Expand image Return Value

The method returns an HRESULT. Possible values include, but are not limited to, those in the following table.

Value | Description
S_OK | The method succeeded.
E_NOTIMPL | The host does not provide a controlling object.

Expand image Remarks

This method allows the host to add new functionality to the helper-provided document contexts. This method may return E_NOTIMPL or a null outer object, in which case the caller is responsible for creating the context.

Expand image See Also

Concepts

IDebugDocumentHost Interface


IDebugDocumentInfo Interface

Microsoft Windows Script Interfaces
IDebugDocumentInfo Interface
DropDown image

Provides information on a document, which may or may not be instantiated.

In addition to the methods inherited from IUnknown, the IDebugDocumentInfo interface exposes the following methods.

Methods in Vtable Order

Method | Description
IDebugDocumentInfo::GetName | Returns the specified document name.
IDebugDocumentInfo::GetDocumentClassId | Returns a CLSID identifying the document type.


IDebugDocumentInfo::GetDocumentClassId

Microsoft Windows Script Interfaces
IDebugDocumentInfo::GetDocumentClassId
See Also
CollapseAll image DropDown image

Returns a CLSID identifying the document type.

HRESULT GetDocumentClassId(
   CLSID*  pclsidDocument
);

Parameters

pclsidDocument

[out] A CLSID identifying the document type.

Expand image Return Value

The method returns an HRESULT. Possible values include, but are not limited to, those in the following table.

Value | Description
S_OK | The method succeeded.

Expand image Remarks

This method allows the debugger IDE to host custom viewers for this document.

If the document does not have viewable data, the return value of pclsidDocument is CLSID_NULL.

Expand image See Also

Concepts

IDebugDocumentInfo Interface


IDebugDocumentInfo::GetName

Microsoft Windows Script Interfaces
IDebugDocumentInfo::GetName
See Also
CollapseAll image DropDown image

Returns the specified document name.

HRESULT GetName(
   DOCUMENTNAMETYPE  dnt,
   BSTR*             pbstrName
);

Parameters

dnt

[in] The type of document name to return.

pbstrName

[out] String containing the name.

Expand image Return Value

The method returns an HRESULT. Possible values include, but are not limited to, those in the following table.

Value | Description
S_OK | The method succeeded.
E_FAIL | The specified document name is not known.

Expand image Remarks

This method returns the specified document name.

Expand image See Also

Reference

DOCUMENTNAMETYPE Enumeration

Concepts

IDebugDocumentInfo Interface


IDebugDocumentProvider Interface

Microsoft Windows Script Interfaces
IDebugDocumentProvider Interface
DropDown image

Provides the means for instantiating a document on demand.

Remarks

This indirect means for instantiating a document:

  • Allows the document to load when it is needed.

  • Allows the document object to be contained within the debugger IDE.

  • Allows multiple ways to access the same document object.

This effectively separates the document from its provider and allows the provider to carry additional run-time, context information.

In addition to the methods inherited from IDebugDocumentInfo, the IDebugDocumentProvider interface exposes the following methods.

Method | Description
IDebugDocumentProvider::GetDocument | Causes the document to be instantiated if it does not already exist.


IDebugDocumentProvider::GetDocument

Microsoft Windows Script Interfaces
IDebugDocumentProvider::GetDocument
See Also
CollapseAll image DropDown image

Causes the document to be instantiated if it does not already exist.

HRESULT GetDocument(
   IDebugDocument**  ppssd
);

Parameters

ppssd

[out] The debug document corresponding to the document.

Expand image Return Value

The method returns an HRESULT. Possible values include, but are not limited to, those in the following table.

Value | Description
S_OK | The method succeeded.

Expand image Remarks

This method causes the document to be instantiated if it does not already exist.

Expand image See Also

Concepts

IDebugDocumentProvider Interface


IDebugDocumentText Interface

Microsoft Windows Script Interfaces
IDebugDocumentText Interface
DropDown image

Provides access to a text-only version of the debug document. This interface uses the following conventions:

  • Both character positions and line numbers are zero based.

  • Character-positions represent character offsets; they do not represent byte or word offsets. For Win32, a character-position is a Unicode offset.

In addition to the methods inherited from IDebugDocument, the IDebugDocumentText interface exposes the following methods.

Methods in Vtable Order

Method | Description
IDebugDocumentText::GetDocumentAttributes | Returns the attributes of the document.
IDebugDocumentText::GetSize | Returns the number of lines and number of characters in the document.
IDebugDocumentText::GetPositionOfLine | Returns character-position corresponding to the first character of a line.
IDebugDocumentText::GetLineOfPosition | Returns the line number and, optionally, the character offset within the line that corresponds to the given character-position.
IDebugDocumentText::GetText | Retrieves the characters and/or the character attributes associated with a character-position range.
IDebugDocumentText::GetPositionOfContext | Returns the character-position range corresponding to a document context.
IDebugDocumentText::GetContextOfPosition | Creates a document context object corresponding to the provided character position range.


IDebugDocumentText::GetContextOfPosition

Microsoft Windows Script Interfaces
IDebugDocumentText::GetContextOfPosition
See Also
CollapseAll image DropDown image

Creates a document context object corresponding to the provided character position range.

HRESULT GetContextOfPosition(
   ULONG                    cCharacterPosition,
   ULONG                    cNumChars,
   IDebugDocumentContext**  ppsc
);

Parameters

cCharacterPosition

[in] Start location of the character position range.

cNumChars

[in] Number of characters in the range.

ppsc

[out] The document context object corresponding to the specified character position range.

Expand image Return Value

The method returns an HRESULT. Possible values include, but are not limited to, those in the following table.

Value | Description
S_OK | The method succeeded.

Expand image Remarks

This method creates a document context object corresponding to the provided character position range.

Expand image See Also

Concepts

IDebugDocumentText Interface


IDebugDocumentText::GetDocumentAttributes

Microsoft Windows Script Interfaces
IDebugDocumentText::GetDocumentAttributes
See Also
CollapseAll image DropDown image

Returns the attributes of the document.

HRESULT GetDocumentAttributes(
   TEXT_DOC_ATTR*  ptextdocattr
);

Parameters

ptextdocattr

[out] The text attributes of the document.

Expand image Return Value

The method returns an HRESULT. Possible values include, but are not limited to, those in the following table.

Value | Description
S_OK | The method succeeded.

Expand image Remarks

This method returns the attributes of the document.

Expand image See Also

Reference

TEXT_DOC_ATTR Constants

Concepts

IDebugDocumentText Interface


IDebugDocumentText::GetLineOfPosition

Microsoft Windows Script Interfaces
IDebugDocumentText::GetLineOfPosition
See Also
CollapseAll image DropDown image

Returns the line number and, optionally, the character offset within the line that corresponds to the given character-position.

HRESULT GetLineOfPosition(
   ULONG   cCharacterPosition,
   ULONG*  pcLineNumber,
   ULONG*  pcCharacterOffsetInLine
);

Parameters

cCharacterPosition

[in] Start location of the character position range.

pcLineNumber

[out] The line number of the range.

pcCharacterOffsetInLine

[in, out] The character offset of the range within line pcLineNumber. If this parameter is NULL, the method does not return a value.

Expand image Return Value

The method returns an HRESULT. Possible values include, but are not limited to, those in the following table.

Value | Description
S_OK | The method succeeded.

Expand image Remarks

This method returns the line number and, optionally, the character offset within the line that corresponds to the given character-position.

Expand image See Also

Concepts

IDebugDocumentText Interface


IDebugDocumentText::GetPositionOfContext

Microsoft Windows Script Interfaces
IDebugDocumentText::GetPositionOfContext
See Also
CollapseAll image DropDown image

Returns the character-position range corresponding to a document context.

HRESULT GetPositionOfContext(
   IDebugDocumentContext*  psc,
   ULONG*                  pcCharacterPosition,
   ULONG*                  cNumChars
);

Parameters

psc

[in] The document context object.

pcCharacterPosition

[out] Start location of the character position range.

cNumChars

[out] Number of characters in the range.

Expand image Return Value

The method returns an HRESULT. Possible values include, but are not limited to, those in the following table.

Value | Description
S_OK | The method succeeded.

Expand image Remarks

The document context provided to this method must be associated with this document.

Expand image See Also

Concepts

IDebugDocumentText Interface


IDebugDocumentText::GetPositionOfLine

Microsoft Windows Script Interfaces
IDebugDocumentText::GetPositionOfLine
See Also
CollapseAll image DropDown image

Returns the character-position corresponding to the first character of a line.

HRESULT GetPositionOfLine(
   ULONG   cLineNumber,
   ULONG*  pcCharacterPosition
);

Parameters

cLineNumber

[in] The line number.

pcCharacterPosition

[out] The character position within the document of the start of line cLineNumber.

Expand image Return Value

The method returns an HRESULT. Possible values include, but are not limited to, those in the following table.

Value | Description
S_OK | The method succeeded.

Expand image Remarks

This method returns the character position corresponding to the first character of a line.

Expand image See Also

Concepts

IDebugDocumentText Interface


IDebugDocumentText::GetSize

Microsoft Windows Script Interfaces
IDebugDocumentText::GetSize
See Also
CollapseAll image DropDown image

Returns the number of lines and number of characters in the document.

HRESULT GetSize(
   ULONG*  pcNumLines,
   ULONG*  pcNumChars
);

Parameters

pcNumLines

[out] Number of lines in the document. If this parameter is NULL, the method does not return a value.

pcNumChars

[out] Number of characters in the document. If this parameter is NULL, the method does not return a value.

Expand image Return Value

The method returns an HRESULT. Possible values include, but are not limited to, those in the following table.

Value | Description
S_OK | The method succeeded.

Expand image Remarks

This method returns the number of lines and number of characters in the document.

Expand image See Also

Concepts

IDebugDocumentText Interface


IDebugDocumentText::GetText

Microsoft Windows Script Interfaces
IDebugDocumentText::GetText
See Also
CollapseAll image DropDown image

Retrieves the characters and/or the character attributes associated with a character-position range.

HRESULT GetText(
   ULONG              cCharacterPosition,
   WCHAR*             pcharText,
   SOURCE_TEXT_ATTR*  pstaTextAttr,
   ULONG*             pcNumChars,
   ULONG              cMaxChars
);

Parameters

cCharacterPosition

[in] Start location of the character position range.

pcharText

[in, out] A character text buffer. The buffer must be large enough to hold cMaxChars characters. If this parameter is NULL, the method does not return characters.

pstaTextAttr

[in, out] A character attribute buffer. The buffer must be large enough to hold cMaxChars characters. If this parameter is NULL, the method does not return attributes.

pcNumChars

[in, out] The number of characters/attributes returned. This parameter must be set to zero before calling this method.

cMaxChars

[in] Number of characters in the character position range. Also specifies the maximum number of characters to return.

Expand image Return Value

The method returns an HRESULT. Possible values include, but are not limited to, those in the following table.

Value | Description
S_OK | The method succeeded.

Expand image Remarks

This method retrieves the characters and/or the character attributes associated with a character-position range. The character position range is specified by a character-position and a number of characters.

Expand image See Also

Reference

SOURCE_TEXT_ATTR Constants

Concepts

IDebugDocumentText Interface


IDebugDocumentTextAuthor Interface

Microsoft Windows Script Interfaces
IDebugDocumentTextAuthor Interface
DropDown image

Provided by text documents that support editing.

In addition to the methods inherited from IDebugDocumentText, the IDebugDocumentTextAuthor interface exposes the following methods.

Methods in Vtable Order

Method | Description
IDebugDocumentTextAuthor::InsertText | Inserts new text into the document.
IDebugDocumentTextAuthor::RemoveText | Removes text from the document.
IDebugDocumentTextAuthor::ReplaceText | Replaces text in the document.


IDebugDocumentTextAuthor::InsertText

Microsoft Windows Script Interfaces
IDebugDocumentTextAuthor::InsertText
See Also
CollapseAll image DropDown image

Inserts new text into the document.

HRESULT InsertText(
   ULONG    cCharacterPosition,
   ULONG    cNumToInsert,
   OLECHAR  pcharText[]
);

Parameters

cCharacterPosition

[in] Location to insert text.

cNumToInsert

[in] Number of characters to insert.

pcharText[]

[in] A buffer containing the characters to insert.

Expand image Return Value

The method returns an HRESULT. Possible values include, but are not limited to, those in the following table.

Value | Description
S_OK | The method succeeded.

Expand image Remarks

This method inserts new text into the document.

Expand image See Also

Reference

IDebugDocumentTextAuthor::RemoveText

Concepts

IDebugDocumentTextAuthor Interface


IDebugDocumentTextAuthor::RemoveText

Microsoft Windows Script Interfaces
IDebugDocumentTextAuthor::RemoveText
See Also
CollapseAll image DropDown image

Removes text from the document.

HRESULT RemoveText(
   ULONG  cCharacterPosition,
   ULONG  cNumToRemove
);

Parameters

cCharacterPosition

[in] Start location of the character range to remove.

cNumToRemove

[in] Number of characters to remove.

Expand image Return Value

The method returns an HRESULT. Possible values include, but are not limited to, those in the following table.

Value | Description
S_OK | The method succeeded.

Expand image Remarks

This method removes text from the document.

Expand image See Also

Reference

IDebugDocumentTextAuthor::InsertText

Concepts

IDebugDocumentTextAuthor Interface


IDebugDocumentTextAuthor::ReplaceText

Microsoft Windows Script Interfaces
IDebugDocumentTextAuthor::ReplaceText
See Also
CollapseAll image DropDown image

Replaces text in the document.

HRESULT ReplaceText(
   ULONG    cCharacterPosition,
   ULONG    cNumToReplace,
   OLECHAR  pcharText[]
);

Parameters

cCharacterPosition

[in] Start location of the character range to replace.

cNumToReplace

[in] Number of characters to replace.

pcharText[]

[in] A buffer containing the new characters to replace the old characters.

Expand image Return Value

The method returns an HRESULT. Possible values include, but are not limited to, those in the following table.

Value | Description
S_OK | The method succeeded.

Expand image Remarks

This method replaces text in the document.

Expand image See Also

Concepts

IDebugDocumentTextAuthor Interface


IDebugDocumentTextEvents Interface

Microsoft Windows Script Interfaces
IDebugDocumentTextEvents Interface
DropDown image

Provides events indicating changes to the associated text document.

Note Note

The document text changes when the events on this interface fire. Event handlers may retrieve the new text using the IDebugDocumentText interface.

In addition to the methods inherited from IUnknown, the IDebugDocumentTextEvents interface exposes the following methods.

Methods in Vtable Order

Method | Description
IDebugDocumentTextEvents::onDestroy | Indicates that the underlying document has been destroyed and is no longer valid
IDebugDocumentTextEvents::onInsertText | Indicates that new text has been added to the document
IDebugDocumentTextEvents::onRemoveText | Indicates that text has been removed from the document.
IDebugDocumentTextEvents::onReplaceText | Indicates that text has been replaced.
IDebugDocumentTextEvents::onUpdateTextAttributes | Indicates that the text attributes associated with the underlying character position range have changed.
IDebugDocumentTextEvents::onUpdateDocumentAttributes | Indicates that the document attributes changed.


IDebugDocumentTextEvents::onDestroy

Microsoft Windows Script Interfaces
IDebugDocumentTextEvents::onDestroy
See Also
CollapseAll image DropDown image

Indicates that the underlying document has been destroyed and is no longer valid.

HRESULT onDestroy();

Parameters

This method takes no parameters.

Expand image Return Value

The method returns an HRESULT. Possible values include, but are not limited to, those in the following table.

Value | Description
S_OK | The method succeeded.

Expand image Remarks

This method indicates that the underlying document has been destroyed and is no longer valid.

Expand image See Also

Concepts

IDebugDocumentTextEvents Interface


IDebugDocumentTextEvents::onInsertText

Microsoft Windows Script Interfaces
IDebugDocumentTextEvents::onInsertText
See Also
CollapseAll image DropDown image

Indicates that new text has been added to the document.

HRESULT onInsertText(
   ULONG  cCharacterPosition,
   ULONG  cNumToInsert
);

Parameters

cCharacterPosition

[in] The character position where the new text was inserted.

cNumToInsert

[in] The number of characters that have been inserted.

Expand image Return Value

The method returns an HRESULT. Possible values include, but are not limited to, those in the following table.

Value | Description
S_OK | The method succeeded.

Expand image Remarks

This method is typically called by a host that progressively loads content, such as a Web browser.

Expand image See Also

Reference

IDebugDocumentTextEvents::onRemoveText

Concepts

IDebugDocumentTextEvents Interface


IDebugDocumentTextEvents::onRemoveText

Microsoft Windows Script Interfaces
IDebugDocumentTextEvents::onRemoveText
See Also
CollapseAll image DropDown image

Indicates that text has been removed from the document.

HRESULT onRemoveText(
   ULONG  cCharacterPosition,
   ULONG  cNumToRemove
);

Parameters

cCharacterPosition

[in] The character position of the first character removed.

cNumToRemove

[in] The number of characters removed.

Expand image Return Value

The method returns an HRESULT. Possible values include, but are not limited to, those in the following table.

Value | Description
S_OK | The method succeeded.

Expand image Remarks

This method indicates that text has been removed from the document.

Expand image See Also

Reference

IDebugDocumentTextEvents::onInsertText

Concepts

IDebugDocumentTextEvents Interface


IDebugDocumentTextEvents::onReplaceText

Microsoft Windows Script Interfaces
IDebugDocumentTextEvents::onReplaceText
See Also
CollapseAll image DropDown image

Indicates that text has been replaced.

HRESULT onReplaceText(
   ULONG  cCharacterPosition,
   ULONG  cNumToReplace
);

Parameters

cCharacterPosition

[in] The character position of the first character replaced.

cNumToReplace

[in] The number of characters replaced.

Expand image Return Value

The method returns an HRESULT. Possible values include, but are not limited to, those in the following table.

Value | Description
S_OK | The method succeeded.

Expand image Remarks

This method indicates that text has been replaced.

Expand image See Also

Concepts

IDebugDocumentTextEvents Interface


IDebugDocumentTextEvents::onUpdateDocumentAttributes

Microsoft Windows Script Interfaces
IDebugDocumentTextEvents::onUpdateDocumentAttributes
See Also
CollapseAll image DropDown image

Indicates that the document attributes changed.

HRESULT onUpdateDocumentAttributes(
   TEXT_DOC_ATTR  textdocattr
);

Parameters

textdocattr

[in] The new document attributes.

Expand image Return Value

The method returns an HRESULT. Possible values include, but are not limited to, those in the following table.

Value | Description
S_OK | The method succeeded.

Expand image Remarks

This method indicates that the document attributes have changed.

Expand image See Also

Reference

TEXT_DOC_ATTR Constants

Concepts

IDebugDocumentTextEvents Interface


IDebugDocumentTextEvents::onUpdateTextAttributes

Microsoft Windows Script Interfaces
IDebugDocumentTextEvents::onUpdateTextAttributes
See Also
CollapseAll image DropDown image

Indicates that the text attributes associated with the underlying character position range have changed.

HRESULT onUpdateTextAttributes(
   ULONG  cCharacterPosition,
   ULONG  cNumToUpdate
);

Parameters

cCharacterPosition

[in] The character position of the first character that the attributes have changed.

cNumToUpdate

[in] The number of characters in the range.

Expand image Return Value

The method returns an HRESULT. Possible values include, but are not limited to, those in the following table.

Value | Description
S_OK | The method succeeded.

Expand image Remarks

This method indicates that the text attributes associated with the underlying character position range have changed.

Expand image See Also

Concepts

IDebugDocumentTextEvents Interface


IDebugDocumentTextExternalAuthor Interface

Microsoft Windows Script Interfaces
IDebugDocumentTextExternalAuthor Interface
DropDown image

Allows external editors to safely edit file-based debugger documents by notifying the document when the source file is changed.

In addition to the methods inherited from IUnknown, the IDebugDocumentTextExternalAuthor interface exposes the following methods.

Methods in Vtable Order

Method | Description
IDebugDocumentTextExternalAuthor::GetPathName | Returns the full path and file name of the document.
IDebugDocumentTextExternalAuthor::GetFileName | Returns the name of the document without path information.
IDebugDocumentTextExternalAuthor::NotifyChanged | Notifies the host that the document source has changed.


IDebugDocumentTextExternalAuthor::GetFileName

Microsoft Windows Script Interfaces
IDebugDocumentTextExternalAuthor::GetFileName
See Also
CollapseAll image DropDown image

Returns the name of the document without path information.

HRESULT GetFileName(
   BSTR*  pbstrShortName
);

Parameters

pbstrShortName

[out] String containing the short name of the document.

Expand image Return Value

The method returns an HRESULT. Possible values include, but are not limited to, those in the following table.

Value | Description
S_OK | The method succeeded.

Expand image Remarks

This method returns the name of the document without path information. The short name is typically used in dialog boxes.

Expand image See Also

Concepts

IDebugDocumentTextExternalAuthor Interface


IDebugDocumentTextExternalAuthor::GetPathName

Microsoft Windows Script Interfaces
IDebugDocumentTextExternalAuthor::GetPathName
See Also
CollapseAll image DropDown image

Returns the full path and file name of the document.

HRESULT GetPathName(
   BSTR*  pbstrLongName,
   BOOL*  pfIsOriginalFile
);

Parameters

pbstrLongName

[out] String containing the full path and file name.

pfIsOriginalFile

[out] Boolean that indicates if the path and file name refer to the original document.

Expand image Return Value

The method returns an HRESULT. Possible values include, but are not limited to, those in the following table.

Value | Description
S_OK | The method succeeded.
E_FAIL | The source file cannot be created or determined.

Expand image Remarks

This method returns the full path and file name of the document.

If pfIsOriginalFile is FALSE, the path and file name in pbstrLongName refer to a newly created temporary file.

Expand image See Also

Concepts

IDebugDocumentTextExternalAuthor Interface


IDebugDocumentTextExternalAuthor::NotifyChanged

Microsoft Windows Script Interfaces
IDebugDocumentTextExternalAuthor::NotifyChanged
See Also
CollapseAll image DropDown image

Notifies the host that the document source has changed.

HRESULT NotifyChanged();

Parameters

This method takes no parameters.

Expand image Return Value

The method returns an HRESULT. Possible values include, but are not limited to, those in the following table.

Value | Description
S_OK | The method succeeded.

Expand image Remarks

This method is called by an external editor after a file-based debugger document is modified and saved to notify the host that the document source has changed. The host then refreshes the document from the source file.

Expand image See Also

Concepts

IDebugDocumentTextExternalAuthor Interface


IDebugExpression Interface

Microsoft Windows Script Interfaces
IDebugExpression Interface
DropDown image

Represents an asynchronously evaluated expression. Script engines typically implement this interface. A debugger IDE typically uses this interface to enable an immediate execution window or watch window.

Note Note

The IDebugExpression interface is available only from a stack frame.

In addition to the methods inherited from IUnknown, the IDebugExpression interface exposes the following methods.

Methods in Vtable Order

Method | Description
IDebugExpression::Start | Begins the evaluation of the expression.
IDebugExpression::Abort | Aborts the expression.
IDebugExpression::QueryIsComplete | Determines if the operation is complete.
IDebugExpression::GetResultAsString | Returns the result of the expression evaluation as a string and the operation's return value.
IDebugExpression::GetResultAsDebugProperty | Returns the result of the expression evaluation as a debug property and the operation's return value.


IDebugExpression::Abort

Microsoft Windows Script Interfaces
IDebugExpression::Abort
See Also
CollapseAll image DropDown image

Stops the expression.

HRESULT Abort();

Parameters

This method takes no parameters.

Expand image Return Value

The method returns an HRESULT. Possible values include, but are not limited to, those in the following table.

Value | Description
S_OK | The method succeeded.

Expand image Remarks

This method stops an expression evaluation at the earliest opportunity.

Expand image See Also

Reference

IDebugExpression::Start

Concepts

IDebugExpression Interface


IDebugExpression::GetResultAsDebugProperty

Microsoft Windows Script Interfaces
IDebugExpression::GetResultAsDebugProperty
See Also
CollapseAll image DropDown image

Returns the result of the expression evaluation as a debug property and the operation's return value.

HRESULT GetResultAsDebugProperty(
   HRESULT*          phrResult,
   IDebugProperty**  ppdp
);

Parameters

phrResult

[out] The operation's return value.

ppdp

[out] The debug property for the expression.

Expand image Return Value

The method returns an HRESULT. Possible values include, but are not limited to, those in the following table.

Value | Description
S_OK | The method succeeded.
E_PENDING | The operation is still pending.

Expand image Remarks

This method returns the result of the expression evaluation as an IDebugProperty and the operation's HRESULT.

This method returns S_OK and phrResult returns E_ABORT if Abort aborts the operation.

Expand image See Also

Reference

IDebugExpression::Abort

Concepts

IDebugExpression Interface


IDebugExpression::GetResultAsString

Microsoft Windows Script Interfaces
IDebugExpression::GetResultAsString
See Also
CollapseAll image DropDown image

Returns the result of the expression evaluation as a string and the operation's return value.

HRESULT GetResultAsString(
   HRESULT*  phrResult,
   BSTR*     pbstrResult
);

Parameters

phrResult

[out] The operation's return value.

pbstrResult

[out] The result of the expression evaluation.

Expand image Return Value

The method returns an HRESULT. Possible values include, but are not limited to, those in the following table.

Value | Description
S_OK | The method succeeded.
E_PENDING | The operation is still pending.

Expand image Remarks

This method returns the result of the expression evaluation as a string and the operation's HRESULT.

This method returns S_OK and phrResult returns E_ABORT if Abort aborts the operation.

Expand image See Also

Concepts

IDebugExpression Interface


IDebugExpression::QueryIsComplete

Microsoft Windows Script Interfaces
IDebugExpression::QueryIsComplete
See Also
CollapseAll image DropDown image

Determines if the operation is complete.

HRESULT QueryIsComplete();

Parameters

This method takes no parameters.

Expand image Return Value

The method returns an HRESULT. Possible values include, but are not limited to, those in the following table.

Value | Description
S_OK | The method succeeded, and the operation is complete.
S_FALSE | The operation is still pending.

Expand image Remarks

This method determines if the operation is complete.

Expand image See Also

Concepts

IDebugExpression Interface


IDebugExpression::Start

Microsoft Windows Script Interfaces
IDebugExpression::Start
See Also
CollapseAll image DropDown image

Begins the evaluation of the expression.

HRESULT Start(
   IDebugExpressionCallBack*  pdecb
);

Parameters

pdecb

[in] Callback for indicating when the expression evaluation is complete. If this parameter is NULL, no events are fired and the client must poll the expression state by using QueryIsComplete.

Expand image Return Value

The method returns an HRESULT. Possible values include, but are not limited to, those in the following table.

Value | Description
S_OK | The method succeeded.

Expand image Remarks

This method begins the evaluation of the expression.

Expand image See Also

Reference

IDebugExpression::Abort

Concepts

IDebugExpression Interface


IDebugExpressionCallBack Interface

Microsoft Windows Script Interfaces
IDebugExpressionCallBack Interface
DropDown image

Provides status events related to progress of an IDebugExpression evaluation.

Methods

In addition to the methods inherited from IUnknown, the IDebugExpressionCallBack interface exposes the following methods.

Method | Description
IDebugExpressionCallBack::onComplete | Indicates that the expression evaluation is complete.


IDebugExpressionCallBack::onComplete

Microsoft Windows Script Interfaces
IDebugExpressionCallBack::onComplete
See Also
CollapseAll image DropDown image

Indicates that the expression evaluation is complete.

HRESULT onComplete();

Parameters

This method takes no parameters.

Expand image Return Value

The method returns an HRESULT. Possible values include, but are not limited to, those in the following table.

Value | Description
S_OK | The method succeeded.

Expand image Remarks

This method is called when the expression evaluation is complete. The IDebugExpression::GetResultAsString method can be called from within this event handler.

Expand image See Also

Reference

IDebugExpression::GetResultAsString

Concepts

IDebugExpressionCallBack Interface


IDebugExpressionContext Interface

Microsoft Windows Script Interfaces
IDebugExpressionContext Interface
CollapseAll image DropDown image

Represents a context where expressions can be evaluated. The stack frame object implements this interface.

In addition to the methods inherited from IUnknown, the IDebugExpressionContext interface exposes the following methods.

Expand image Methods in Vtable Order

Method | Description
IDebugExpressionContext::ParseLanguageText | Creates a debug expression for the specified text.
IDebugExpressionContext::GetLanguageInfo | Returns a name and GUID for the language that owns this context.


IDebugExpressionContext::GetLanguageInfo

Microsoft Windows Script Interfaces
IDebugExpressionContext::GetLanguageInfo
See Also
CollapseAll image DropDown image

Returns a name and GUID for the language that owns this context.

HRESULT GetLanguageInfo(
   BSTR*  pbstrLanguageName,
   GUID*  pLanguageID
);

Parameters

pbstrLanguageName

[out] The name of the language.

pLanguageID

[out] The unique id for the language.

Expand image Return Value

The method returns an HRESULT. Possible values include, but are not limited to, those in the following table.

Value | Description
S_OK | The method succeeded.

Expand image Remarks

This method returns a name and GUID for the language that owns this context.

Expand image See Also

Reference

IDebugExpressionContext Interface


IDebugExpressionContext::ParseLanguageText

Microsoft Windows Script Interfaces
IDebugExpressionContext::ParseLanguageText
See Also
CollapseAll image DropDown image

Creates a debug expression for the specified text.

HRESULT ParseLanguageText(
   LPCOLESTR           pstrCode,
   UINT                nRadix,
   LPCOLESTR           pstrDelimiter,
   DWORD               dwFlags,
   IDebugExpression**  ppe
);

Parameters

pstrCode

[in] Provides the text of the expression or statement(s).

nRadix

[in] Radix to use.

pstrDelimiter

[in] The end-of-script-block delimiter. When pstrCode is parsed from a stream of text, the host typically uses a delimiter, such as two single quotation marks (''), to detect the end of the script block. This parameter specifies the delimiter that the host used, allowing the scripting engine to provide some conditional primitive preprocessing (for example, replacing a single quotation mark ['] with two single quotation marks for use as a delimiter). Exactly how (and if) the scripting engine uses this information depends on the scripting engine. Set this parameter to NULL if the host did not use a delimiter to mark the end of the script block.

dwFlags

[in] Combination of the following debug text flags:

Constant Value Description

DEBUG_TEXT_ISEXPRESSION

0x00000001

Indicates that the text is an expression as opposed to a statement. This flag may affect the way in which the text is parsed by some languages.

DEBUG_TEXT_RETURNVALUE

0x00000002

If a return value is available, it will be used by the caller.

DEBUG_TEXT_NOSIDEEFFECTS

0x00000004

Do not allow side effects. If this flag is set, the evaluation of the expression should change no runtime state.

DEBUG_TEXT_ALLOWBREAKPOINTS

0x00000008

Allows breakpoints during the evaluation of the text. If this flag is not set then breakpoints are ignored during the evaluation of the text.

DEBUG_TEXT_ALLOWERRORREPORT

0x00000010

Allows error reports during the evaluation of the text. If this flag is not set then errors are not reported to the host during the evaluation.

DEBUG_TEXT_EVALUATETOCODECONTEXT

0x00000020

Indicates the expression is to be evaluated to a code context rather than running the expression itself
ppe

[out] Returns the debug expression for the specified text.

Expand image Return Value

The method returns an HRESULT. Possible values include, but are not limited to, those in the following table.

Value | Description
S_OK | The method succeeded.

Expand image Remarks

This method creates a debug expression for the specified text.

Expand image See Also

Reference

IDebugExpressionContext Interface


IDebugFormatter Interface

Microsoft Windows Script Interfaces
IDebugFormatter Interface
DropDown image

Allows a language or IDE to customize the conversion between VARIANT values or VARTYPE types and strings.

In addition to the methods inherited from IUnknown, the IDebugFormatter interface exposes the following methods.

Methods in Vtable Order

Method | Description
IDebugFormatter::GetStringForVariant | Returns a string that represents the given VARIANT value.
IDebugFormatter::GetVariantForString | Returns a VARIANT containing the given string.
IDebugFormatter::GetStringForVarType | Returns a string that represents the given VARTYPE value.


IDebugFormatter::GetStringForVariant

Microsoft Windows Script Interfaces
IDebugFormatter::GetStringForVariant
See Also
CollapseAll image DropDown image

Returns a string that represents the given VARIANT value.

HRESULT GetStringForVariant(
   VARIANT*  pvar,
   ULONG     nRadix,
   BSTR*     pbstrValue
);

Parameters

pvar

[in] VARIANT to represent as a string.

nRadix

[in] Radix to use for numeric values.

pbstrValue

[out] String representing pvar.

Expand image Return Value

The method returns an HRESULT. Possible values include, but are not limited to, those in the following table.

Value | Description
S_OK | The method succeeded.

Expand image Remarks

This method returns a string that represents the given variant value.

Expand image See Also

Concepts

IDebugFormatter Interface


IDebugFormatter::GetStringForVarType

Microsoft Windows Script Interfaces
IDebugFormatter::GetStringForVarType
See Also
CollapseAll image DropDown image

Returns a string that represents the given VARTYPE value.

HRESULT GetStringForVarType(
   VARTYPE    vt,
   TYPEDESC*  ptdescArrayType,
   BSTR*      pbstr
);

Parameters

vt

[in] VARTYPE to represent as a string.

ptdescArrayType

[in] Array of structures that describes types.

pbstr

[out] String representing vt.

Expand image Return Value

The method returns an HRESULT. Possible values include, but are not limited to, those in the following table.

Value | Description
S_OK | The method succeeded.

Expand image Remarks

The method returns a string that represents the given VARTYPE value.

Expand image See Also

Concepts

IDebugFormatter Interface


IDebugFormatter::GetVariantForString

Microsoft Windows Script Interfaces
IDebugFormatter::GetVariantForString
See Also
CollapseAll image DropDown image

Returns a VARIANT containing the given string.

HRESULT GetVariantForString(
   LPCOLESTR  pwstrValue,
   VARIANT*   pvar
);

Parameters

pwstrValue

[in] String to store in a VARIANT.

pvar

[out] VARIANT containing pwstrValue.

Expand image Return Value

The method returns an HRESULT. Possible values include, but are not limited to, those in the following table.

Value | Description
S_OK | The method succeeded.

Expand image Remarks

This method returns a VARIANT containing the given string.

Expand image See Also

Concepts

IDebugFormatter Interface


IDebugHelper Interface

Microsoft Windows Script Interfaces
IDebugHelper Interface
DropDown image

Serves as a factory for object browsers and simple connection points. The process debug manager (PDM) implements this interface, which is consumed by script engines.

In addition to the methods inherited from IUnknown, the IDebugHelper interface exposes the following methods.

Methods in Vtable Order

Method | Description
IDebugHelper::CreatePropertyBrowser | Returns a property browser that wraps a VARIANT.
IDebugHelper::CreatePropertyBrowserEx | Returns a property browser that wraps a VARIANT, and allows for custom conversion of VARIANT values or VARTYPE types to strings.
IDebugHelper::CreateSimpleConnectionPoint | Returns an event interface that wraps a given IDispatch object.


IDebugHelper::CreatePropertyBrowser

Microsoft Windows Script Interfaces
IDebugHelper::CreatePropertyBrowser
See Also
CollapseAll image DropDown image

Returns a property browser that wraps a VARIANT.

HRESULT CreatePropertyBrowser(
   VARIANT*                  pvar,
   LPCOLESTR                 bstrName,
   IDebugApplicationThread*  pdat,
   IDebugProperty**          ppdob
);

Parameters

pvar

[in] Root variant to browse.

bstrName

[in] Name to give the root.

pdat

[in] Thread on which to request properties. If this parameter is NULL, no marshalling is performed.

ppdob

[out] The property browser.

Expand image Return Value

The method returns an HRESULT. Possible values include, but are not limited to, those in the following table.

Value | Description
S_OK | The method succeeded.

Expand image Remarks

This method returns a property browser that wraps a VARIANT.

Expand image See Also

Reference

IDebugHelper::CreatePropertyBrowserEx

Concepts

IDebugHelper Interface
IDebugProperty Interface


IDebugHelper::CreatePropertyBrowserEx

Microsoft Windows Script Interfaces
IDebugHelper::CreatePropertyBrowserEx
See Also
CollapseAll image DropDown image

Returns a property browser that wraps a VARIANT and allows for custom conversion of VARIANT values or VARTYPE types to strings.

HRESULT CreatePropertyBrowserEx(
   VARIANT*                  pvar,
   LPCOLESTR                 bstrName,
   IDebugApplicationThread*  pdat,
   IDebugFormatter*          pdf,
   IDebugProperty**          ppdob
);

Parameters

pvar

[in] Root variant to browse.

bstrName

[in] Name to give the root.

pdat

[in] Thread on which to request properties. If this parameter is NULL, no marshalling is performed.

pdf

[in] Object that provides custom formatting for variants.

ppdob

[out] The property browser.

Expand image Return Value

The method returns an HRESULT. Possible values include, but are not limited to, those in the following table.

Value | Description
S_OK | The method succeeded.

Expand image Remarks

This method returns a property browser that wraps a VARIANT and allows for custom conversion of VARIANT values or VARTYPE types to strings.

Expand image See Also

Reference

IDebugHelper::CreatePropertyBrowser

Concepts

IDebugHelper Interface
IDebugProperty Interface


IDebugHelper::CreateSimpleConnectionPoint

Microsoft Windows Script Interfaces
IDebugHelper::CreateSimpleConnectionPoint
See Also
CollapseAll image DropDown image

Returns an event interface that wraps a given IDispatch object.

HRESULT CreateSimpleConnectionPoint(
   IDispatch*                pdisp
   ISimpleConnectionPoint**  ppscp
);

Parameters

pdisp

[in] The IDispatch object to wrap.

ppscp

[out] The event interface that wraps pdisp.

Expand image Return Value

The method returns an HRESULT. Possible values include, but are not limited to, those in the following table.

Value | Description
S_OK | The method succeeded.

Expand image Remarks

Returns an event interface that wraps the given IDispatch (see ISimpleConnectionPoint Interface).

Expand image See Also

Concepts

IDebugHelper Interface
ISimpleConnectionPoint Interface


IDebugSessionProvider Interface

Microsoft Windows Script Interfaces
IDebugSessionProvider Interface
DropDown image

The primary interface provided by a debugger IDE to enable host and language initiated debugging. It establishes a debug session for a running application. This interface is implemented by the machine debug manager.

In addition to the methods inherited from IUnknown, the IDebugSessionProvider interface exposes the following methods.

Methods in Vtable Order

Method | Description
IDebugSessionProvider::StartDebugSession | Initiates a debug session with the specified application.


IDebugSessionProvider::StartDebugSession

Microsoft Windows Script Interfaces
IDebugSessionProvider::StartDebugSession
See Also
CollapseAll image DropDown image

Initiates a debug session with the specified application.

HRESULT StartDebugSession(
   IRemoteDebugApplication*  pda
);

Parameters

pda

[in] Specifies the debug application.

Expand image Return Value

The method returns an HRESULT. Possible values include, but are not limited to, those in the following table.

Value | Description
S_OK | The method succeeded.

Expand image Remarks

This method initiates a debug session with the specified application. The debugger should call IRemoteDebugApplication::ConnectDebugger before returning from this call.

Expand image See Also

Reference

IRemoteDebugApplication::ConnectDebugger

Concepts

IDebugSessionProvider Interface


IDebugStackFrame Interface

Microsoft Windows Script Interfaces
IDebugStackFrame Interface
DropDown image

Represents a logical stack frame on the thread stack. Call the IDebugStackFrame::QueryInterface method to obtain the IDebugExpressionContext interface, which allows expression evaluation and watch windows.

In addition to the methods inherited from IUnknown, the IDebugStackFrame interface exposes the following methods.

Methods in Vtable Order

Method | Description
IDebugStackFrame::GetCodeContext | Returns the current code context associated with the stack frame.
IDebugStackFrame::GetDescriptionString | Returns a short or long textual description of the stack frame.
IDebugStackFrame::GetLanguageString | Returns a short or long textual description of the language.
IDebugStackFrame::GetThread | Returns the thread associated with this stack frame.
IDebugStackFrame::GetDebugProperty | Returns a property browser for the current frame.


IDebugStackFrame::GetCodeContext

Microsoft Windows Script Interfaces
IDebugStackFrame::GetCodeContext
See Also
CollapseAll image DropDown image

Returns the current code context associated with the stack frame.

HRESULT GetCodeContext(
   IDebugCodeContext**  ppcc
);

Parameters

ppcc

[out] The code context associated with the stack frame.

Expand image Return Value

The method returns an HRESULT. Possible values include, but are not limited to, those in the following table.

Value | Description
S_OK | The method succeeded.

Expand image Remarks

This method returns the current code context associated with the stack frame.

Expand image See Also

Concepts

IDebugStackFrame Interface


IDebugStackFrame::GetDebugProperty

Microsoft Windows Script Interfaces
IDebugStackFrame::GetDebugProperty
See Also
CollapseAll image DropDown image

Returns a property browser for the current frame.

HRESULT GetDebugProperty(
   IDebugProperty**  ppDebugProp
);

Parameters

ppDebugProp

[out] A property browser for the current frame.

Expand image Return Value

The method returns an HRESULT. Possible values include, but are not limited to, those in the following table.

Value | Description
S_OK | The method succeeded.

Expand image Remarks

This method returns a property browser for the current frame.

Expand image See Also

Concepts

IDebugStackFrame Interface


IDebugStackFrame::GetDescriptionString

Microsoft Windows Script Interfaces
IDebugStackFrame::GetDescriptionString
See Also
CollapseAll image DropDown image

Returns a short or long textual description of the stack frame.

HRESULT GetDescriptionString(
   BOOL   fLong,
   BSTR*  pbstrDescription
);

Parameters

fLong

[in] Flag, where TRUE returns a long description and FALSE returns a short description.

pbstrDescription

[out] The description of the stack frame.

Expand image Return Value

The method returns an HRESULT. Possible values include, but are not limited to, those in the following table.

Value | Description
S_OK | The method succeeded.

Expand image Remarks

Typically, if fLong is FALSE, this method provides only the name of the function associated with the stack frame. When fLong is TRUE, this method may also provide the function parameters and other relevant information.

Expand image See Also

Concepts

IDebugStackFrame Interface


IDebugStackFrame::GetLanguageString

Microsoft Windows Script Interfaces
IDebugStackFrame::GetLanguageString
See Also
CollapseAll image DropDown image

Returns a short or long textual description of the language.

HRESULT GetLanguageString(
   BOOL   fLong,
   BSTR*  pbstrLanguage
);

Parameters

fLong

[in] Flag, where TRUE returns a long description and FALSE returns a short description.

pbstrLanguage

[out] The description of the language.

Expand image Return Value

The method returns an HRESULT. Possible values include, but are not limited to, those in the following table.

Value | Description
S_OK | The method succeeded.

Expand image Remarks

Typically, if fLong is FALSE, this method provides only the name of the language associated with the stack frame. When fLong is TRUE, this method may provide a full product description.

Expand image See Also

Concepts

IDebugStackFrame Interface


IDebugStackFrame::GetThread

Microsoft Windows Script Interfaces
IDebugStackFrame::GetThread
See Also
CollapseAll image DropDown image

Returns the thread associated with this stack frame.

HRESULT GetThread(
   IDebugApplicationThread**  ppat
);

Parameters

ppat

[out] The thread associated with this stack frame.

Expand image Return Value

The method returns an HRESULT. Possible values include, but are not limited to, those in the following table.

Value | Description
S_OK | The method succeeded.

Expand image Remarks

This method returns the thread associated with this stack frame.

Expand image See Also

Concepts

IDebugStackFrame Interface


IDebugStackFrameSniffer Interface

Microsoft Windows Script Interfaces
IDebugStackFrameSniffer Interface
DropDown image

Provides a way to enumerate the logical stack frames known by a component. Script engines typically implement this interface. The process debug manager uses this interface to find all stack frames associated with a given thread.

Note Note

The debugger calls this interface from within the thread of interest. The script engine must identify the current thread and return an appropriate enumerator.

Methods

In addition to the methods inherited from IUnknown, the IDebugStackFrameSniffer interface exposes the following methods.

Method | Description
IDebugStackFrameSniffer::EnumStackFrames | Returns an enumerator of stack frames for the current thread.


IDebugStackFrameSniffer::EnumStackFrames

Microsoft Windows Script Interfaces
IDebugStackFrameSniffer::EnumStackFrames
See Also
CollapseAll image DropDown image

Returns an enumerator of stack frames for the current thread.

HRESULT EnumStackFrames(
   IEnumDebugStackFrames**  ppedsf
);

Parameters

ppedsf

[out] Enumerator of stack frames for the current thread.

Expand image Return Value

The method returns an HRESULT. Possible values include, but are not limited to, those in the following table.

Value | Description
S_OK | The method succeeded.

Expand image Remarks

The stack frame enumerator returns the frames starting at the top of the stack, starting with the most recently pushed frame.

Expand image See Also

Concepts

IDebugStackFrameSniffer Interface


IDebugStackFrameSnifferEx Interface

Microsoft Windows Script Interfaces
IDebugStackFrameSnifferEx Interface
DropDown image

Provides a way to enumerate the logical stack frames known by a component. Script engines typically implement this interface. The process debug manager uses this interface to find all stack frames associated with a given thread.

Note Note

This interface is called from within the thread of interest. The interface implementation must identify the current thread and return an appropriate enumerator.

In addition to the methods inherited from IDebugStackFrameSniffer, the IDebugStackFrameSnifferEx interface exposes the following methods.

Methods in Vtable Order

Method | Description
IDebugStackFrameSnifferEx::EnumStackFramesEx | Returns an enumerator of stack frames for the current thread.


IDebugStackFrameSnifferEx::EnumStackFramesEx

Microsoft Windows Script Interfaces
IDebugStackFrameSnifferEx::EnumStackFramesEx
See Also
CollapseAll image DropDown image

Returns an enumerator of stack frames for the current thread.

HRESULT EnumStackFramesEx(
   DWORD_PTR                dwSpMin,
   IEnumDebugStackFrames**  ppedsf
);

Parameters

dwSpMin

[in] The lower address limit for enumerating stack frames.

ppedsf

[out] Enumerator of stack frames for the current thread.

Expand image Return Value

The method returns an HRESULT. Possible values include, but are not limited to, those in the following table.

Value | Description
S_OK | The method succeeded.

Expand image Remarks

The stack frame enumerator returns the frames starting at the top of the stack, with the most recently pushed frame. The enumerator contains only stack frames with addresses greater than or equal to dwSpMin.

Expand image See Also

Concepts

IDebugStackFrameSnifferEx Interface


IDebugSyncOperation Interface

Microsoft Windows Script Interfaces
IDebugSyncOperation Interface
DropDown image

Allows a script engine to abstract an operation (such as expression evaluation) that needs to be performed while nested in a particular blocked thread. The interface also provides a mechanism for canceling unresponsive operations.

In addition to the methods inherited from IUnknown, the IDebugSyncOperation interface exposes the following methods.

Methods in Vtable Order

Method | Description
IDebugSyncOperation::GetTargetThread | Returns the target application thread for this synchronous operation.
IDebugSyncOperation::Execute | Synchronously performs the operation and returns.
IDebugSyncOperation::InProgressAbort | Cancels an operation in progress on another thread.


IDebugSyncOperation::Execute

Microsoft Windows Script Interfaces
IDebugSyncOperation::Execute
See Also
CollapseAll image DropDown image

Synchronously performs the operation and returns.

HRESULT Execute(
   IUnknown**  ppunkResult
);

Parameters

ppunkResult

[out] The object parameter returned by the operation.

Expand image Return Value

The method returns an HRESULT. Possible values include, but are not limited to, those in the following table.

Value | Description
S_OK | The method succeeded.
E_ABORT | The operation was aborted by calling the IDebugSyncOperation::InProgressAbort method.

Expand image Remarks

The Process Debug Manager in the target thread calls the Execute method synchronously.

Expand image See Also

Concepts

IDebugSyncOperation Interface


IDebugSyncOperation::GetTargetThread

Microsoft Windows Script Interfaces
IDebugSyncOperation::GetTargetThread
See Also
CollapseAll image DropDown image

Returns the target application thread for this synchronous operation.

HRESULT GetTargetThread(
   IDebugApplicationThread**  ppatTarget
);

Parameters

ppatTarget

[out] The target application thread for this synchronous operation.

Expand image Return Value

The method returns an HRESULT. Possible values include, but are not limited to, those in the following table.

Value | Description
S_OK | The method succeeded.

Expand image Remarks

This method returns the target application thread for this synchronous operation.

Expand image See Also

Concepts

IDebugSyncOperation Interface


IDebugSyncOperation::InProgressAbort

Microsoft Windows Script Interfaces
IDebugSyncOperation::InProgressAbort
See Also
CollapseAll image DropDown image

Cancels an operation in progress on another thread.

HRESULT InProgressAbort();

Parameters

This method takes no parameters.

Expand image Return Value

The method returns an HRESULT. Possible values include, but are not limited to, those in the following table.

Value | Description
S_OK | The method succeeded.
E_NOTIMPL | The operation cannot be cancelled.
E_ABORT | The operation could not be completed.

Expand image Remarks

The Process Debug Manager calls this method from within the debugger thread to cancel an operation that is in progress in another thread.

If the InProgressAbort method cannot complete the operation, it returns E_ABORT as soon as possible. This method can return E_NOTIMPL if the operation cannot be cancelled.

Expand image See Also

Concepts

IDebugSyncOperation Interface


IDebugThreadCall Interface

Microsoft Windows Script Interfaces
IDebugThreadCall Interface
DropDown image

The IDebugThreadCall interface is typically implemented by a component that makes cross-thread calls with the IDebugThread marshalling implementation provided by the process debug manager (PDM).

The PDM calls the IDebugThreadCall interface in the desired thread, and the IDebugThreadCall interface dispatches the call to the desired implementation. The IDebugThreadCall interface casts the parameter information passed in the parameters to the appropriate top.

The IDebugThreadCall interface is a free-threaded object.

Methods

In addition to the methods inherited from IUnknown, the IDebugThreadCall interface exposes the following methods.

Method | Description
IDebugThreadCall::ThreadCallHandler | Handles calls to run code in another thread.


IDebugThreadCall::ThreadCallHandler

Microsoft Windows Script Interfaces
IDebugThreadCall::ThreadCallHandler
See Also
CollapseAll image DropDown image

Handles calls to run code in another thread.

HRESULT ThreadCallHandler(
   DWORD_PTR  dwParam1,
   DWORD_PTR  dwParam2,
   DWORD_PTR  dwParam3
);

Parameters

dwParam1

[in] The first parameter.

dwParam2

[in] The second parameter.

dwParam3

[in] The third parameter.

Expand image Return Value

The method returns an HRESULT. Possible values include, but are not limited to, those in the following table.

Value | Description
S_OK | The method succeeded.

Expand image Remarks

This method handles calls to run code in the debugger thread.

Expand image See Also

Reference

IDebugApplication::SynchronousCallInDebuggerThread
IDebugApplicationThread::SynchronousCallIntoThread

Concepts

IDebugThreadCall Interface


IEnumDebugApplicationNodes Interface

Microsoft Windows Script Interfaces
IEnumDebugApplicationNodes Interface
DropDown image

Enumerates child nodes of a node associated with an application.

In addition to the methods inherited from IUnknown, the IEnumDebugApplicationNodes interface exposes the following methods.

Methods in Vtable Order

Method | Description
IEnumDebugApplicationNodes::Next | Retrieves a specified number of segments in an enumeration sequence.
IEnumDebugApplicationNodes::Skip | Skips a specified number of segments in an enumeration sequence.
IEnumDebugApplicationNodes::Reset | Resets an enumeration sequence to the beginning.
IEnumDebugApplicationNodes::Clone | Creates an enumerator that contains the same state as the current enumerator.


IEnumDebugApplicationNodes::Clone

Microsoft Windows Script Interfaces
IEnumDebugApplicationNodes::Clone
See Also
CollapseAll image DropDown image

Creates an enumerator that contains the same state as the current enumerator.

HRESULT Clone(
   IEnumDebugApplicationNodes**  pperddp
);

Parameters

pperddp

[out] Returns the IEnumDebugApplicationNodes interface of the clone of the enumerator.

Expand image Return Value

The method returns an HRESULT. Possible values include, but are not limited to, those in the following table.

Value | Description
S_OK | The method succeeded.

Expand image Remarks

This method creates an enumerator that contains the same state as the current enumerator.

Expand image See Also

Concepts

IEnumDebugApplicationNodes Interface


IEnumDebugApplicationNodes::Next

Microsoft Windows Script Interfaces
IEnumDebugApplicationNodes::Next
See Also
CollapseAll image DropDown image

Retrieves a specified number of segments in the enumeration sequence.

HRESULT Next(
   ULONG                    celt,
   IDebugApplicationNode**  pprddp,
   ULONG*                   pceltFetched
);

Parameters

celt

[in] The number of segments to retrieve.

pprddp

[out] Returns an array of IDebugApplicationNode interfaces that represents the segments being retrieved.

pceltFetched

[out] The actual number of segments fetched by the enumerator.

Expand image Return Value

The method returns an HRESULT. Possible values include, but are not limited to, those in the following table.

Value | Description
S_OK | The method succeeded.

Expand image Remarks

This method retrieves a specified number of segments in the enumeration sequence.

Expand image See Also

Concepts

IEnumDebugApplicationNodes Interface


IEnumDebugApplicationNodes::Reset

Microsoft Windows Script Interfaces
IEnumDebugApplicationNodes::Reset
See Also
CollapseAll image DropDown image

Resets an enumeration sequence to the beginning.

HRESULT Reset();

Parameters

This method takes no parameters.

Expand image Return Value

The method returns an HRESULT. Possible values include, but are not limited to, those in the following table.

Value | Description
S_OK | The method succeeded.

Expand image Remarks

This method resets an enumeration sequence to the beginning.

Expand image See Also

Concepts

IEnumDebugApplicationNodes Interface


IEnumDebugApplicationNodes::Skip

Microsoft Windows Script Interfaces
IEnumDebugApplicationNodes::Skip
See Also
CollapseAll image DropDown image

Skips a specified number of segments in an enumeration sequence.

HRESULT Skip(
   ULONG  celt
);

Parameters

celt

[in] Number of segments in the enumeration sequence to skip.

Expand image Return Value

The method returns an HRESULT. Possible values include, but are not limited to, those in the following table.

Value | Description
S_OK | The method succeeded.

Expand image Remarks

This method skips a specified number of segments in an enumeration sequence.

Expand image See Also

Concepts

IEnumDebugApplicationNodes Interface


IEnumDebugCodeContexts Interface

Microsoft Windows Script Interfaces
IEnumDebugCodeContexts Interface
DropDown image

Enumerates the code contexts that correspond to a document context.

In addition to the methods inherited from IUnknown, the IEnumDebugCodeContexts interface exposes the following methods.

Methods in Vtable Order

Method | Description
IEnumDebugCodeContexts::Next | Retrieves a specified number of segments in the enumeration sequence.
IEnumDebugCodeContexts::Skip | Skips a specified number of segments in an enumeration sequence.
IEnumDebugCodeContexts::Reset | Resets an enumeration sequence to the beginning.
IEnumDebugCodeContexts::Clone | Creates an enumerator that contains the same state as the current enumerator.


IEnumDebugCodeContexts::Clone

Microsoft Windows Script Interfaces
IEnumDebugCodeContexts::Clone
See Also
CollapseAll image DropDown image

Creates an enumerator that contains the same state as the current enumerator.

HRESULT Clone(
   IEnumDebugCodeContexts**  ppescc
);

Parameters

ppescc

[out] Returns the IEnumDebugCodeContexts interface of the clone of the enumerator.

Expand image Return Value

The method returns an HRESULT. Possible values include, but are not limited to, those in the following table.

Value | Description
S_OK | The method succeeded.

Expand image Remarks

This method creates an enumerator that contains the same state as the current enumerator.

Expand image See Also

Concepts

IEnumDebugCodeContexts Interface


IEnumDebugCodeContexts::Next

Microsoft Windows Script Interfaces
IEnumDebugCodeContexts::Next
See Also
CollapseAll image DropDown image

Retrieves a specified number of segments in the enumeration sequence.

HRESULT Next(
   ULONG                celt,
   IDebugCodeContext**  pscc,
   ULONG*               pceltFetched
);

Parameters

celt

[in] The number of segments to retrieve.

pscc

[out] Returns an array of IDebugCodeContext interfaces that represents the segments being retrieved.

pceltFetched

[out] The actual number of segments fetched by the enumerator.

Expand image Return Value

The method returns an HRESULT. Possible values include, but are not limited to, those in the following table.

Value | Description
S_OK | The method succeeded.

Expand image Remarks

This method retrieves a specified number of segments in the enumeration sequence.

Expand image See Also

Concepts

IEnumDebugCodeContexts Interface


IEnumDebugCodeContexts::Reset

Microsoft Windows Script Interfaces
IEnumDebugCodeContexts::Reset
See Also
CollapseAll image DropDown image

Resets an enumeration sequence to the beginning.

HRESULT Reset();

Parameters

This method takes no parameters.

Expand image Return Value

The method returns an HRESULT. Possible values include, but are not limited to, those in the following table.

Value | Description
S_OK | The method succeeded.

Expand image Remarks

This method resets an enumeration sequence to the beginning.

Expand image See Also

Concepts

IEnumDebugCodeContexts Interface


IEnumDebugCodeContexts::Skip

Microsoft Windows Script Interfaces
IEnumDebugCodeContexts::Skip
See Also
CollapseAll image DropDown image

Skips a specified number of segments in an enumeration sequence.

HRESULT Skip(
   ULONG  celt
);

Parameters

celt

[in] Number of segments in the enumeration sequence to skip.

Expand image Return Value

The method returns an HRESULT. Possible values include, but are not limited to, those in the following table.

Value | Description
S_OK | The method succeeded.

Expand image Remarks

This method skips a specified number of segments in an enumeration sequence.

Expand image See Also

Concepts

IEnumDebugCodeContexts Interface


IEnumDebugExpressionContexts Interface

Microsoft Windows Script Interfaces
IEnumDebugExpressionContexts Interface
DropDown image

Enumerates a collection of IDebugExpressionContexts objects.

In addition to the methods inherited from IUnknown, the IEnumDebugExpressionContexts interface exposes the following methods.

Methods in Vtable Order

Method | Description
IEnumDebugExpressionContexts::Next | Retrieves a specified number of segments in the enumeration sequence.
IEnumDebugExpressionContexts::Skip | Skips a specified number of segments in an enumeration sequence.
IEnumDebugExpressionContexts::Reset | Resets an enumeration sequence to the beginning.
IEnumDebugExpressionContexts::Clone | Creates an enumerator that contains the same state as the current enumerator.


IEnumDebugExpressionContexts::Clone

Microsoft Windows Script Interfaces
IEnumDebugExpressionContexts::Clone
See Also
CollapseAll image DropDown image

Creates an enumerator that contains the same state as the current enumerator.

HRESULT Clone(
   IEnumDebugExpressionContexts**  ppedec
);

Parameters

ppedec

[out] Returns the IEnumDebugExpressionContexts interface of the clone of the enumerator.

Expand image Return Value

The method returns an HRESULT. Possible values include, but are not limited to, those in the following table.

Value | Description
S_OK | The method succeeded.

Expand image Remarks

This method creates an enumerator that contains the same state as the current enumerator.

Expand image See Also

Concepts

IEnumDebugExpressionContexts Interface


IEnumDebugExpressionContexts::Next

Microsoft Windows Script Interfaces
IEnumDebugExpressionContexts::Next
See Also
CollapseAll image DropDown image

Retrieves a specified number of segments in the enumeration sequence.

HRESULT Next(
   ULONG                      celt,
   IDebugExpressionContext**  ppdec,
   ULONG*                     pceltFetched
);

Parameters

celt

[in] The number of segments to retrieve.

ppdec

[out] Returns an array of IDebugExpressionContext interfaces that represents the segments being retrieved.

pceltFetched

[out] The actual number of segments fetched by the enumerator.

Expand image Return Value

The method returns an HRESULT. Possible values include, but are not limited to, those in the following table.

Value | Description
S_OK | The method succeeded.

Expand image Remarks

This method retrieves a specified number of segments in the enumeration sequence.

Expand image See Also

Concepts

IEnumDebugExpressionContexts Interface


IEnumDebugExpressionContexts::Reset

Microsoft Windows Script Interfaces
IEnumDebugExpressionContexts::Reset
See Also
CollapseAll image DropDown image

Resets an enumeration sequence to the beginning.

HRESULT Reset();

Parameters

This method takes no parameters.

Expand image Return Value

The method returns an HRESULT. Possible values include, but are not limited to, those in the following table.

Value | Description
S_OK | The method succeeded.

Expand image Remarks

This method resets an enumeration sequence to the beginning.

Expand image See Also

Concepts

IEnumDebugExpressionContexts Interface


IEnumDebugExpressionContexts::Skip

Microsoft Windows Script Interfaces
IEnumDebugExpressionContexts::Skip
See Also
CollapseAll image DropDown image

Skips a specified number of segments in an enumeration sequence.

HRESULT Skip(
   ULONG  celt
);

Parameters

celt

[in] Number of segments in the enumeration sequence to skip.

Expand image Return Value

The method returns an HRESULT. Possible values include, but are not limited to, those in the following table.

Value | Description
S_OK | The method succeeded.

Expand image Remarks

This method skips a specified number of segments in an enumeration sequence.

Expand image See Also

Concepts

IEnumDebugExpressionContexts Interface


IEnumDebugStackFrames Interface

Microsoft Windows Script Interfaces
IEnumDebugStackFrames Interface
DropDown image

Enumerates the stack frames corresponding to a thread.

Methods

In addition to the methods inherited from IUnknown, the IEnumDebugStackFrames interface exposes the following methods.

Method | Description
IEnumDebugStackFrames::Next | Retrieves a specified number of segments in the enumeration sequence.
IEnumDebugStackFrames::Skip | Skips a specified number of segments in an enumeration sequence.
IEnumDebugStackFrames::Reset | Resets an enumeration sequence to the beginning.
IEnumDebugStackFrames::Clone | Creates an enumerator that contains the same state as the current enumerator.


IEnumDebugStackFrames::Clone

Microsoft Windows Script Interfaces
IEnumDebugStackFrames::Clone
See Also
CollapseAll image DropDown image

Creates an enumerator that contains the same state as the current enumerator.

HRESULT Clone(
   IEnumDebugStackFrames**  ppedsf
);

Parameters

ppedsf

[out] Returns the IEnumDebugStackFrames interface of the clone of the enumerator.

Expand image Return Value

The method returns an HRESULT. Possible values include, but are not limited to, those in the following table.

Value | Description
S_OK | The method succeeded.

Expand image Remarks

This method creates an enumerator that contains the same state as the current enumerator.

Expand image See Also

Concepts

IEnumDebugStackFrames Interface


IEnumDebugStackFrames::Next

Microsoft Windows Script Interfaces
IEnumDebugStackFrames::Next
See Also
CollapseAll image DropDown image

Retrieves a specified number of segments in the enumeration sequence.

HRESULT Next(
   ULONG                       celt,
   DebugStackFrameDescriptor*  prgdsfd,
   ULONG*                      pceltFetched
);

Parameters

celt

[in] The number of segments to retrieve.

prgdsfd

[out] Returns an array of DebugStackFrameDescriptor interfaces that represents the segments being retrieved.

pceltFetched

[out] The actual number of segments fetched by the enumerator.

Expand image Return Value

The method returns an HRESULT. Possible values include, but are not limited to, those in the following table.

Value | Description
S_OK | The method succeeded.

Expand image Remarks

This method retrieves a specified number of segments in the enumeration sequence.

Expand image See Also

Reference

DebugStackFrameDescriptor Structure

Concepts

IEnumDebugStackFrames Interface


IEnumDebugStackFrames::Reset

Microsoft Windows Script Interfaces
IEnumDebugStackFrames::Reset
See Also
CollapseAll image DropDown image

Resets an enumeration sequence to the beginning.

HRESULT Reset();

Parameters

This method takes no parameters.

Expand image Return Value

The method returns an HRESULT. Possible values include, but are not limited to, those in the following table.

Value | Description
S_OK | The method succeeded.

Expand image Remarks

This method resets an enumeration sequence to the beginning.

Expand image See Also

Concepts

IEnumDebugStackFrames Interface


IEnumDebugStackFrames::Skip

Microsoft Windows Script Interfaces
IEnumDebugStackFrames::Skip
See Also
CollapseAll image DropDown image

Skips a specified number of segments in an enumeration sequence.

HRESULT Skip(
   ULONG  celt
);

Parameters

celt

[in] Number of segments in the enumeration sequence to skip.

Expand image Return Value

The method returns an HRESULT. Possible values include, but are not limited to, those in the following table.

Value | Description
S_OK | The method succeeded.

Expand image Remarks

This method skips a specified number of segments in an enumeration sequence.

Expand image See Also

Concepts

IEnumDebugStackFrames Interface


IEnumRemoteDebugApplications Interface

Microsoft Windows Script Interfaces
IEnumRemoteDebugApplications Interface
DropDown image

Enumerates application objects. This interface can be used to enumerate the running applications on a machine for an "attach to application" dialog box.

In addition to the methods inherited from IUnknown, the IEnumRemoteDebugApplications interface exposes the following methods.

Methods in Vtable Order

Method | Description
IEnumRemoteDebugApplications::Clone | Creates an enumerator that contains the same state as the current enumerator.
IEnumRemoteDebugApplications::Next | Retrieves a specified number of segments in an enumeration sequence.
IEnumRemoteDebugApplications::Reset | Resets an enumeration sequence to the beginning.
IEnumRemoteDebugApplications::Skip | Skips a specified number of segments in an enumeration sequence.


IEnumRemoteDebugApplications::Clone

Microsoft Windows Script Interfaces
IEnumRemoteDebugApplications::Clone
See Also
CollapseAll image DropDown image

Creates an enumerator that contains the same state as the current enumerator.

HRESULT Clone(
   IEnumRemoteDebugApplications**  ppessd
);

Parameters

ppessd

[out] A clone of the enumerator.

Expand image Return Value

The method returns an HRESULT. Possible values include, but are not limited to, those in the following table.

Value | Description
S_OK | The method succeeded.

Expand image Remarks

This method creates an enumerator that contains the same state as the current enumerator.

Expand image See Also

Concepts

IEnumRemoteDebugApplications Interface


IEnumRemoteDebugApplications::Next

Microsoft Windows Script Interfaces
IEnumRemoteDebugApplications::Next
See Also
CollapseAll image DropDown image

The Next method retrieves a specified number of segments in the enumeration sequence.

HRESULT Next(
   ULONG                      celt,
   IRemoteDebugApplication**  ppda,
   ULONG*                     pceltFetched
);

Parameters

celt

[in] The number of segments to retrieve.

ppda

[out] Returns an array of IRemoteDebugApplication interfaces that represents the segments being retrieved.

pceltFetched

[out] The actual number of segments fetched by the enumerator.

Expand image Return Value

The method returns an HRESULT. Possible values include, but are not limited to, those in the following table.

Value | Description
S_OK | The method succeeded.

Expand image Remarks

This method retrieves a specified number of segments in the enumeration sequence.

Expand image See Also

Concepts

IEnumRemoteDebugApplications Interface


IEnumRemoteDebugApplications::Reset

Microsoft Windows Script Interfaces
IEnumRemoteDebugApplications::Reset
See Also
CollapseAll image DropDown image

Resets an enumeration sequence to the beginning.

HRESULT Reset();

Parameters

This method takes no parameters.

Expand image Return Value

The method returns an HRESULT. Possible values include, but are not limited to, those in the following table.

Value | Description
S_OK | The method succeeded.

Expand image Remarks

This method resets an enumeration sequence to the beginning.

Expand image See Also

Concepts

IEnumRemoteDebugApplications Interface


IEnumRemoteDebugApplications::Skip

Microsoft Windows Script Interfaces
IEnumRemoteDebugApplications::Skip
See Also
CollapseAll image DropDown image

Skips a specified number of segments in an enumeration sequence.

HRESULT Skip(
   ULONG  celt
);

Parameters

celt

[in] Number of segments in the enumeration sequence to skip.

Expand image Return Value

The method returns an HRESULT. Possible values include, but are not limited to, those in the following table.

Value | Description
S_OK | The method succeeded.

Expand image Remarks

This method skips a specified number of segments in an enumeration sequence.

Expand image See Also

Concepts

IEnumRemoteDebugApplications Interface


IEnumRemoteDebugApplicationThreads Interface

Microsoft Windows Script Interfaces
IEnumRemoteDebugApplicationThreads Interface
DropDown image

Enumerates the running threads in an application.

In addition to the methods inherited from IUnknown, the IEnumRemoteDebugApplicationThreads interface exposes the following methods.

Methods in Vtable Order

Method | Description
IEnumRemoteDebugApplicationThreads::Next | Retrieves a specified number of segments in an enumeration sequence.
IEnumRemoteDebugApplicationThreads::Skip | Skips a specified number of segments in an enumeration sequence.
IEnumRemoteDebugApplicationThreads::Reset | Resets an enumeration sequence to the beginning.
IEnumRemoteDebugApplicationThreads::Clone | Creates an enumerator that contains the same state as the current enumerator.


IEnumRemoteDebugApplicationThreads::Clone

Microsoft Windows Script Interfaces
IEnumRemoteDebugApplicationThreads::Clone
See Also
CollapseAll image DropDown image

Creates an enumerator that contains the same state as the current enumerator.

HRESULT Clone(
   IEnumRemoteDebugApplicationThreads**  pperdat
);

Parameters

pperdat

[out] Returns the IEnumRemoteDebugApplicationThreads interface of the clone of the enumerator.

Expand image Return Value

The method returns an HRESULT. Possible values include, but are not limited to, those in the following table.

Value | Description
S_OK | The method succeeded.

Expand image Remarks

This method creates an enumerator that contains the same state as the current enumerator.

Expand image See Also

Concepts

IEnumRemoteDebugApplicationThreads Interface


IEnumRemoteDebugApplicationThreads::Next

Microsoft Windows Script Interfaces
IEnumRemoteDebugApplicationThreads::Next
See Also
CollapseAll image DropDown image

The Next method retrieves a specified number of segments in the enumeration sequence.

HRESULT Next(
   ULONG                            celt,
   IRemoteDebugApplicationThread**  pprdat,
   ULONG*                           pceltFetched
);

Parameters

celt

[in] The number of segments to retrieve.

pprdat

[out] Returns an array of IRemoteDebugApplicationThread interfaces that represents the segments being retrieved.

pceltFetched

[out] The actual number of segments fetched by the enumerator.

Expand image Return Value

The method returns an HRESULT. Possible values include, but are not limited to, those in the following table.

Value | Description
S_OK | The method succeeded.

Expand image Remarks

This method retrieves a specified number of segments in the enumeration sequence.

Expand image See Also

Concepts

IEnumRemoteDebugApplicationThreads Interface


IEnumRemoteDebugApplicationThreads::Reset

Microsoft Windows Script Interfaces
IEnumRemoteDebugApplicationThreads::Reset
See Also
CollapseAll image DropDown image

Resets an enumeration sequence to the beginning.

HRESULT Reset();

Parameters

This method takes no parameters.

Expand image Return Value

The method returns an HRESULT. Possible values include, but are not limited to, those in the following table.

Value | Description
S_OK | The method succeeded.

Expand image Remarks

This method resets an enumeration sequence to the beginning.

Expand image See Also

Concepts

IEnumRemoteDebugApplicationThreads Interface


IEnumRemoteDebugApplicationThreads::Skip

Microsoft Windows Script Interfaces
IEnumRemoteDebugApplicationThreads::Skip
See Also
CollapseAll image DropDown image

Skips a specified number of segments in an enumeration sequence.

HRESULT Skip(
   ULONG  celt
);

Parameters

celt

[in] Number of segments in the enumeration sequence to skip.

Expand image Return Value

The method returns an HRESULT. Possible values include, but are not limited to, those in the following table.

Value | Description
S_OK | The method succeeded.

Expand image Remarks

This method skips a specified number of segments in an enumeration sequence.

Expand image See Also

Concepts

IEnumRemoteDebugApplicationThreads Interface


IMachineDebugManager Interface

Microsoft Windows Script Interfaces
IMachineDebugManager Interface
See Also
DropDown image

The primary interface to the Machine Debug Manager. This interface is similar to the IMachineDebugManagerCookie interface.

In addition to the methods inherited from IUnknown, the IMachineDebugManager interface exposes the following methods.

Methods in Vtable Order

Method | Description
IMachineDebugManager::AddApplication | Adds an application to the running application list.
IMachineDebugManager::RemoveApplication | Removes an application from the running application list.
IMachineDebugManager::EnumApplications | Returns an enumerator of the current list of running applications.

See Also

Concepts

IMachineDebugManagerCookie Interface


IMachineDebugManager::AddApplication

Microsoft Windows Script Interfaces
IMachineDebugManager::AddApplication
See Also
CollapseAll image DropDown image

Adds an application to the running application list.

HRESULT AddApplication(
   IRemoteDebugApplication*  pda,
   DWORD*                    pdwAppCookie
);

Parameters

pda

[in] Application to the running application list.

pdwAppCookie

[out] A cookie that is used to remove the application from the machine debug manager.

Expand image Return Value

The method returns an HRESULT. Possible values include, but are not limited to, those in the following table.

Value | Description
S_OK | The method succeeded.

Expand image Remarks

This method is called by the process debug manager whenever IProcessDebugManager::AddApplication is called.

Expand image See Also

Reference

IMachineDebugManager::RemoveApplication
IProcessDebugManager::AddApplication

Concepts

IMachineDebugManager Interface


IMachineDebugManager::EnumApplications

Microsoft Windows Script Interfaces
IMachineDebugManager::EnumApplications
See Also
CollapseAll image DropDown image

Returns an enumerator of the current list of running applications.

HRESULT EnumApplications(
   IEnumRemoteDebugApplications**  ppeda
);

Parameters

ppeda

[out] Enumerator containing the current list of running applications.

Expand image Return Value

The method returns an HRESULT. Possible values include, but are not limited to, those in the following table.

Value | Description
S_OK | The method succeeded.

Expand image Remarks

This method returns an enumerator of the current list of running applications. The debugger IDE uses this method to display and attach applications for debugging purposes.

Expand image See Also

Concepts

IMachineDebugManager Interface


IMachineDebugManager::RemoveApplication

Microsoft Windows Script Interfaces
IMachineDebugManager::RemoveApplication
See Also
CollapseAll image DropDown image

Removes an application from the running application list.

HRESULT RemoveApplication(
   DWORD  dwAppCookie
);

Parameters

dwAppCookie

[in] The cookie provided when the application was added to the application list.

Expand image Return Value

The method returns an HRESULT. Possible values include, but are not limited to, those in the following table.

Value | Description
S_OK | The method succeeded.

Expand image Remarks

This method is called by the process debug manager whenever IProcessDebugManager::RemoveApplication is called.

Expand image See Also

Reference

IMachineDebugManager::AddApplication
IProcessDebugManager::RemoveApplication

Concepts

IMachineDebugManager Interface


IMachineDebugManagerCookie Interface

Microsoft Windows Script Interfaces
IMachineDebugManagerCookie Interface
See Also
DropDown image

Similar to the IMachineDebugManager interface, the IMachineDebugManagerCookie interface supports debug cookies.

This interface (along with the IDebugCookie interface) allow scripts to run in a script debugger process without requiring that the debugger keep track of those scripts.

A script debugger calls the IDebugCookie::SetDebugCookie method on the Process Debug Manager (PDM). Then, the PDM sends this cookie along with any request to add or remove a script application to or from the Machine Debug Manager (MDM), using the methods of the IMachineDebugManagerCookie interface. The MDM then notifies every debugger of the change, except for the one that has that cookie.

In addition to the methods inherited from IUnknown, the IMachineDebugManagerCookie interface exposes the following methods.

Methods in Vtable Order

Method | Description
IMachineDebugManagerCookie::AddApplication | Adds an application to the running application list.
IMachineDebugManagerCookie::EnumApplications | Returns an enumerator of the current list of running applications.
IMachineDebugManagerCookie::RemoveApplication | Removes an application from the running application list.

See Also

Concepts

IMachineDebugManager Interface
IDebugCookie Interface


IMachineDebugManagerCookie::AddApplication

Microsoft Windows Script Interfaces
IMachineDebugManagerCookie::AddApplication
See Also
CollapseAll image DropDown image

Adds an application to the running application list.

HRESULT AddApplication(
   IRemoteDebugApplication*  pda,
   DWORD                     dwDebugAppCookie,
   DWORD*                    pdwAppCookie
);

Parameters

pda

[in] Application to the running application list.

dwDebugAppCookie

[in] A cookie that identifies the debug application.

pdwAppCookie

[out] A cookie that is used to remove the application from the machine debug manager.

Expand image Return Value

The method returns an HRESULT. Possible values include, but are not limited to, those in the following table.

Value | Description
S_OK | The method succeeded.

Expand image Remarks

This method is called by the process debug manager whenever IProcessDebugManager::AddApplication is called.

Expand image See Also

Reference

IMachineDebugManagerCookie::RemoveApplication
IProcessDebugManager::AddApplication

Concepts

IMachineDebugManagerCookie Interface


IMachineDebugManagerCookie::EnumApplications

Microsoft Windows Script Interfaces
IMachineDebugManagerCookie::EnumApplications
See Also
CollapseAll image DropDown image

Returns an enumerator of the current list of running applications.

HRESULT EnumApplications(
   IEnumRemoteDebugApplications**  ppeda
);

Parameters

ppeda

[out] Enumerator containing the current list of running applications.

Expand image Return Value

The method returns an HRESULT. Possible values include, but are not limited to, those in the following table.

Value | Description
S_OK | The method succeeded.

Expand image Remarks

This method returns an enumerator of the current list of running applications. The debugger IDE uses this method to display and attach applications for debugging purposes.

Expand image See Also

Concepts

IMachineDebugManagerCookie Interface


IMachineDebugManagerCookie::RemoveApplication

Microsoft Windows Script Interfaces
IMachineDebugManagerCookie::RemoveApplication
See Also
CollapseAll image DropDown image

Removes an application from the running application list.

HRESULT RemoveApplication(
   DWORD  dwDebugAppCookie,
   DWORD  dwAppCookie
);

Parameters

dwDebugAppCookie

[in] A cookie that identifies the debug application.

dwAppCookie

[in] The cookie provided when the application was added to the application list.

Expand image Return Value

The method returns an HRESULT. Possible values include, but are not limited to, those in the following table.

Value | Description
S_OK | The method succeeded.

Expand image Remarks

This method is called by the process debug manager whenever IProcessDebugManager::RemoveApplication is called.

Expand image See Also

Reference

IMachineDebugManagerCookie::AddApplication
IProcessDebugManager::RemoveApplication

Concepts

IMachineDebugManagerCookie Interface


IMachineDebugManagerEvents Interface

Microsoft Windows Script Interfaces
IMachineDebugManagerEvents Interface
DropDown image

Signals changes in the running application list maintained by the machine debug manager. This interface can be used by the debugger IDE to display a dynamic list of applications.

In addition to the methods inherited from IUnknown, the IMachineDebugManagerEvents interface exposes the following methods.

Methods in Vtable Order

Method | Description
IMachineDebugManagerEvents::onAddApplication | Handles the event when an application is added to the running application list.
IMachineDebugManagerEvents::onRemoveApplication | Handles the event when an application is removed from the running application list.


IMachineDebugManagerEvents::onAddApplication

Microsoft Windows Script Interfaces
IMachineDebugManagerEvents::onAddApplication
See Also
CollapseAll image DropDown image

Handles the event when an application is added to the running application list.

HRESULT onAddApplication(
   IRemoteDebugApplication*  pda,
   DWORD                     dwAppCookie
);

Parameters

pda

[in] Application that was added to the running application list.

dwAppCookie

[in] The cookie provided when the application was added to the application list.

Expand image Return Value

The method returns an HRESULT. Possible values include, but are not limited to, those in the following table.

Value | Description
S_OK | The method succeeded.

Expand image Remarks

This method indicates that an application was added to the running application list.

Expand image See Also

Reference

IMachineDebugManagerEvents::onRemoveApplication

Concepts

IMachineDebugManagerEvents Interface


IMachineDebugManagerEvents::onRemoveApplication

Microsoft Windows Script Interfaces
IMachineDebugManagerEvents::onRemoveApplication
See Also
CollapseAll image DropDown image

Handles the event when an application is removed from the running application list.

HRESULT onRemoveApplication(
   IRemoteDebugApplication*  pda,
   DWORD                     dwAppCookie
);

Parameters

pda

[in] Application that was removed from the running application list.

dwAppCookie

[in] The cookie provided when the application was added from the application list.

Expand image Return Value

The method returns an HRESULT. Possible values include, but are not limited to, those in the following table.

Value | Description
S_OK | The method succeeded.

Expand image Remarks

This method indicates that an application was removed from the running application list.

Expand image See Also

Reference

IMachineDebugManagerEvents::onAddApplication

Concepts

IMachineDebugManagerEvents Interface


IProcessDebugManager Interface

Microsoft Windows Script Interfaces
IProcessDebugManager Interface
DropDown image

Primary interface to the process debug manager. This interface can create, add, or remove a virtual application from a process. It can enumerate stack frames and application threads.

In addition to the methods inherited from IUnknown, the IProcessDebugManager interface exposes the following methods.

Methods in Vtable Order

Method | Description
IProcessDebugManager::CreateApplication | Creates a new debug application object for this application.
IProcessDebugManager::GetDefaultApplication | Returns a default application object for the current process.
IProcessDebugManager::AddApplication | Adds an application to the machine debug manager's list of running applications.
IProcessDebugManager::RemoveApplication | Removes an application from the running application list.
IProcessDebugManager::CreateDebugDocumentHelper | Creates a new debug document helper for this application.


IProcessDebugManager::AddApplication

Microsoft Windows Script Interfaces
IProcessDebugManager::AddApplication
See Also
CollapseAll image DropDown image

Adds an application to the machine debug manager's list of running applications.

HRESULT AddApplication(
   IDebugApplication*  pda,
   DWORD*              pdwAppCookie
);

Parameters

pda

[in] The debug application to add to the list of running applications.

pdwAppCookie

[out] A cookie that is used to remove the application from the machine debug manager.

Expand image Return Value

The method returns an HRESULT. Possible values include, but are not limited to, those in the following table.

Value | Description
S_OK | The method succeeded.

Expand image Remarks

This method adds an application to the running application list in the machine debug manager.

Expand image See Also

Reference

IProcessDebugManager::RemoveApplication

Concepts

IProcessDebugManager Interface


IProcessDebugManager::CreateApplication

Microsoft Windows Script Interfaces
IProcessDebugManager::CreateApplication
See Also
CollapseAll image DropDown image

Creates a new debug application object for this application.

HRESULT CreateApplication(
   IDebugApplication**  ppda
);

Parameters

ppda

[out] The debug application object for this application.

Expand image Return Value

The method returns an HRESULT. Possible values include, but are not limited to, those in the following table.

Value | Description
S_OK | The method succeeded.

Expand image Remarks

The object created by this method has no name and is not added to the running application list. Use the IProcessDebugManager::AddApplication to add the debug application to the application list.

Expand image See Also

Reference

IProcessDebugManager::AddApplication

Concepts

IProcessDebugManager Interface


IProcessDebugManager::CreateDebugDocumentHelper

Microsoft Windows Script Interfaces
IProcessDebugManager::CreateDebugDocumentHelper
See Also
CollapseAll image DropDown image

Creates a new debug document helper for this application.

HRESULT CreateDebugDocumentHelper(
   IUnknown*               punkOuter,
   IDebugDocumentHelper**  pddh
);

Parameters

punkOuter

[in] If the returned object is to be aggregated, punkOuter is an interface pointer to the controlling IUnknown. Otherwise, it is a null pointer.

pddh

[out] The debug document helper object for this application.

Expand image Return Value

The method returns an HRESULT. Possible values include, but are not limited to, those in the following table.

Value | Description
S_OK | The method succeeded.

Expand image Remarks

This method creates a new debug document helper for this application.

Expand image See Also

Concepts

IProcessDebugManager Interface


IProcessDebugManager::GetDefaultApplication

Microsoft Windows Script Interfaces
IProcessDebugManager::GetDefaultApplication
See Also
CollapseAll image DropDown image

Returns a default application object for the current process.

HRESULT GetDefaultApplication(
   IDebugApplication**  ppda
);

Parameters

ppda

[out] The debug application object for this application.

Expand image Return Value

The method returns an HRESULT. Possible values include, but are not limited to, those in the following table.

Value | Description
S_OK | The method succeeded.

Expand image Remarks

This method creates a new debug application object and adds it to the running application list, if necessary.

Language engines should use the application specified by the GetDefaultApplication method if they are running on a host that does not provide an application.

Expand image See Also

Concepts

IProcessDebugManager Interface


IProcessDebugManager::RemoveApplication

Microsoft Windows Script Interfaces
IProcessDebugManager::RemoveApplication
See Also
CollapseAll image DropDown image

Removes an application from the running application list.

HRESULT RemoveApplication(
   DWORD  dwAppCookie
);

Parameters

dwAppCookie

[in] The cookie provided by IProcessDebugManager::AddApplication when the application was added to the application list.

Expand image Return Value

The method returns an HRESULT. Possible values include, but are not limited to, those in the following table.

Value | Description
S_OK | The method succeeded.

Expand image Remarks

This method removes an application from the running application list.

Expand image See Also

Reference

IProcessDebugManager::AddApplication

Concepts

IProcessDebugManager Interface


IProvideExpressionContexts Interface

Microsoft Windows Script Interfaces
IProvideExpressionContexts Interface
DropDown image

Provides a way to enumerate expression contexts known by a certain component. Script engines typically implement this interface.

The process debug manager uses this interface to find all global expression contexts associated with a given thread.

Note Note

This interface is called from within the thread of interest. It is up to the implementer to identify the current thread and return an appropriate enumerator.

Methods

In addition to the methods inherited from IUnknown, the IProvideExpressionContexts interface exposes the following methods.

Method | Description
IProvideExpressionContexts::EnumExpressionContexts | Returns an enumerator of expression contexts known by this component.


IProvideExpressionContexts::EnumExpressionContexts

Microsoft Windows Script Interfaces
IProvideExpressionContexts::EnumExpressionContexts
See Also
CollapseAll image DropDown image

Returns an enumerator of expression contexts known by this component.

HRESULT EnumExpressionContexts(
   IEnumDebugExpressionContexts**  ppedec
);

Parameters

ppedec

[out] An enumerator of expression contexts known by this component.

Expand image Return Value

The method returns an HRESULT. Possible values include, but are not limited to, those in the following table.

Value | Description
S_OK | The method succeeded.

Expand image Remarks

The process debug manager uses this method to find all global expression contexts associated with a given thread.

Note Note

This method is called from within the thread of interest. It is up to the implementer to identify the current thread and return an appropriate enumerator.

Expand image See Also

Concepts

IProvideExpressionContexts Interface


IRemoteDebugApplication Interface

Microsoft Windows Script Interfaces
IRemoteDebugApplication Interface
DropDown image

Represents a running application. It does not need to correspond to an operating-system process. Typically, a debugger targets an application for debugging. The Process Debug Manager typically implements the application object.

In addition to the methods inherited from IUnknown, the IRemoteDebugApplication interface exposes the following methods.

Methods in Vtable Order

Method | Description
IRemoteDebugApplication::ResumeFromBreakPoint | Continues an application that is currently in a breakpoint.
IRemoteDebugApplication::CauseBreak | Causes the application to break into the debugger at the earliest opportunity.
IRemoteDebugApplication::ConnectDebugger | Connects a debugger to this application.
IRemoteDebugApplication::DisconnectDebugger | Disconnects the current debugger from the application.
IRemoteDebugApplication::GetDebugger | Returns the current debugger connected to the application.
IRemoteDebugApplication::CreateInstanceAtApplication | Provides a mechanism for the debugger IDE, running out-of-process to the application, to create objects in the application process.
IRemoteDebugApplication::QueryAlive | Indicates if the application is responsive.
IRemoteDebugApplication::EnumThreads | Enumerates all threads known to be associated with the application.
IRemoteDebugApplication::GetName | Returns the name of this application node.
IRemoteDebugApplication::GetRootNode | Returns the application node under which all nodes associated with the application are added.
IRemoteDebugApplication::EnumGlobalExpressionContexts | Enumerates the global expression contexts for all languages running in this application.


IRemoteDebugApplication::CauseBreak

Microsoft Windows Script Interfaces
IRemoteDebugApplication::CauseBreak
See Also
CollapseAll image DropDown image

Causes the application to break into the debugger at the earliest opportunity.

HRESULT CauseBreak();

Parameters

This method takes no parameters.

Expand image Return Value

The method returns an HRESULT. Possible values include, but are not limited to, those in the following table.

Value | Description
S_OK | The method succeeded.

Expand image Remarks

Calling this method does not cause an application to break immediately. If the application is not currently executing script code, a long time may elapse before the application actually breaks.

Expand image See Also

Concepts

IRemoteDebugApplication Interface


IRemoteDebugApplication::ConnectDebugger

Microsoft Windows Script Interfaces
IRemoteDebugApplication::ConnectDebugger
See Also
CollapseAll image DropDown image

Connects a debugger to this application.

HRESULT ConnectDebugger(
   IApplicationDebugger*  pad
);

Parameters

pad

[in] The debugger to attach to this application.

Expand image Return Value

The method returns an HRESULT. Possible values include, but are not limited to, those in the following table.

Value | Description
S_OK | The method succeeded.
E_FAIL | A debugger is already connected to this application.

Expand image Remarks

An application can have only one debugger connected at a time. This method fails if a debugger is already connected.

Expand image See Also

Reference

IRemoteDebugApplication::GetDebugger

Concepts

IRemoteDebugApplication Interface


IRemoteDebugApplication::CreateInstanceAtApplication

Microsoft Windows Script Interfaces
IRemoteDebugApplication::CreateInstanceAtApplication
See Also
CollapseAll image DropDown image

Allows the creation of objects in the application process by code that is out-of-process to the application.

HRESULT CreateInstanceAtApplication(
   REFCLSID    rclsid,
   IUnknown*   pUnkOuter,
   DWORD       dwClsContext,
   REFIID      riid,
   IUnknown**  ppvObject
);

Parameters

rclsid

[in] Class identifier (CLSID) of the object to create.

pUnkOuter

[in] If NULL, the object is not being created as part of an aggregate. Otherwise, pUnkOuter is a pointer to the aggregate object's IUnknown interface (the controlling IUnknown).

dwClsContext

[in] Context for running executable code. The values are taken from the enumeration CLSCTX.

riid

[in] The interface identifier used to communicate with the object.

ppvObject

[out] Address of pointer variable that receives the interface pointer requested in riid. Upon successful return, *ppvObject contains the requested interface pointer. Upon failure, *ppvObject contains NULL.

Expand image Return Value

The method returns an HRESULT. Possible values include, but are not limited to, those in the following table.

Value | Description
S_OK | The method succeeded.

Expand image Remarks

This method delegates to CoCreateInstance.

Expand image See Also

Concepts

IRemoteDebugApplication Interface


IRemoteDebugApplication::DisconnectDebugger

Microsoft Windows Script Interfaces
IRemoteDebugApplication::DisconnectDebugger
See Also
CollapseAll image DropDown image

Disconnects the current debugger from the application.

HRESULT DisconnectDebugger();

Parameters

This method takes no parameters.

Expand image Return Value

The method returns an HRESULT. Possible values include, but are not limited to, those in the following table.

Value | Description
S_OK | The method succeeded.

Expand image Remarks

This method disconnects the current debugger from the application.

Expand image See Also

Concepts

IRemoteDebugApplication Interface


IRemoteDebugApplication::EnumGlobalExpressionContexts

Microsoft Windows Script Interfaces
IRemoteDebugApplication::EnumGlobalExpressionContexts
See Also
CollapseAll image DropDown image

Enumerates the global expression contexts for all languages running in this application.

HRESULT EnumGlobalExpressionContexts(
   IEnumDebugExpressionContexts**  ppedec
);

Parameters

ppedec

[out] Enumerator that lists the global expression contexts for all languages running in this application.

Expand image Return Value

The method returns an HRESULT. Possible values include, but are not limited to, those in the following table.

Value | Description
S_OK | The method succeeded.

Expand image Remarks

This method enumerates the global expression contexts for all languages running in this application.

Expand image See Also

Concepts

IRemoteDebugApplication Interface


IRemoteDebugApplication::EnumThreads

Microsoft Windows Script Interfaces
IRemoteDebugApplication::EnumThreads
See Also
CollapseAll image DropDown image

Enumerates all threads known to be associated with the application.

HRESULT EnumThreads(
   IEnumRemoteDebugApplicationThreads**  pperdat
);

Parameters

pperdat

[out] Enumerator that lists all threads known to be associated with the application.

Expand image Return Value

The method returns an HRESULT. Possible values include, but are not limited to, those in the following table.

Value | Description
S_OK | The method succeeded.

Expand image Remarks

This method enumerates all threads known to be associated with the application. New threads may be added at any time.

Expand image See Also

Concepts

IRemoteDebugApplication Interface


IRemoteDebugApplication::GetDebugger

Microsoft Windows Script Interfaces
IRemoteDebugApplication::GetDebugger
See Also
CollapseAll image DropDown image

Returns the current debugger connected to the application.

HRESULT GetDebugger(
   IApplicationDebugger**  pad
);

Parameters

pad

[out] The current debugger connected to the application.

Expand image Return Value

The method returns an HRESULT. Possible values include, but are not limited to, those in the following table.

Value | Description
S_OK | The method succeeded.

Expand image Remarks

This method returns the current debugger connected to the application.

Expand image See Also

Reference

IRemoteDebugApplication::ConnectDebugger

Concepts

IRemoteDebugApplication Interface


IRemoteDebugApplication::GetName

Microsoft Windows Script Interfaces
IRemoteDebugApplication::GetName
See Also
CollapseAll image DropDown image

Returns the name of this application node.

HRESULT GetName(
   BSTR*  pbstrName
);

Parameters

pbstrName

[out] Name of this application node.

Expand image Return Value

The method returns an HRESULT. Possible values include, but are not limited to, those in the following table.

Value | Description
S_OK | The method succeeded.

Expand image Remarks

This method returns the name of this application node.

Expand image See Also

Concepts

IRemoteDebugApplication Interface


IRemoteDebugApplication::GetRootNode

Microsoft Windows Script Interfaces
IRemoteDebugApplication::GetRootNode
See Also
CollapseAll image DropDown image

Returns the application node under which all nodes associated with the application are added.

HRESULT GetRootNode(
   IDebugApplicationNode**  ppdanRoot
);

Parameters

ppdanRoot

[out] The debug application node under which all nodes associated with the application are added.

Expand image Return Value

The method returns an HRESULT. Possible values include, but are not limited to, those in the following table.

Value | Description
S_OK | The method succeeded.

Expand image Remarks

This method returns the application node under which all nodes associated with the application are added.

Expand image See Also

Concepts

IRemoteDebugApplication Interface


IRemoteDebugApplication::QueryAlive

Microsoft Windows Script Interfaces
IRemoteDebugApplication::QueryAlive
See Also
CollapseAll image DropDown image

Indicates if the application is responsive.

HRESULT QueryAlive();

Parameters

This method takes no parameters.

Expand image Return Value

The method returns an HRESULT. Possible values include, but are not limited to, those in the following table.

Value | Description
S_OK | The method succeeded.

Expand image Remarks

This method indicates if the application is responsive. Implementations of this method should always return S_OK.

If the application process terminates unexpectedly, COM returns an error from the marshalling proxy for calls to this method.

Expand image See Also

Concepts

IRemoteDebugApplication Interface


IRemoteDebugApplication::ResumeFromBreakPoint

Microsoft Windows Script Interfaces
IRemoteDebugApplication::ResumeFromBreakPoint
See Also
CollapseAll image DropDown image

Continues an application that is currently in a breakpoint.

HRESULT ResumeFromBreakPoint(
   IRemoteDebugApplicationThread*  prptFocus,
   BREAKRESUMEACTION               bra,
   ERRORRESUMEACTION               era
);

Parameters

prptFocus

[in] For stepping modes, the thread which is to be affected by the stepping mode.

bra

[in] The action to take upon resuming the application.

era

[in] The action to take in the case that the application stopped because of an error.

Expand image Return Value

The method returns an HRESULT. Possible values include, but are not limited to, those in the following table.

Value | Description
S_OK | The method succeeded.

Expand image Remarks

This method continues an application that is currently in a breakpoint.

Expand image See Also

Reference

BREAKRESUMEACTION Enumeration
ERRORRESUMEACTION Enumeration

Concepts

IRemoteDebugApplication Interface


IRemoteDebugApplicationEvents Interface

Microsoft Windows Script Interfaces
IRemoteDebugApplicationEvents Interface
DropDown image

The IRemoteDebugApplicationEvents interface is the event interface provided by a debug application. This interface is always called from within the debugger thread.

In addition to the methods inherited from IUnknown, the IRemoteDebugApplicationEvents interface exposes the following methods.

Methods in Vtable Order

Method | Description
IRemoteDebugApplicationEvents::OnConnectDebugger | Handles a debugger connect event.
IRemoteDebugApplicationEvents::OnDisconnectDebugger | Handles a debugger disconnect event.
IRemoteDebugApplicationEvents::OnSetName | Handles a set name event.
IRemoteDebugApplicationEvents::OnDebugOutput | Handles a debugger output event.
IRemoteDebugApplicationEvents::OnClose | Handles an application close event.
IRemoteDebugApplicationEvents::OnEnterBreakPoint | Handles an event for entering a breakpoint.
IRemoteDebugApplicationEvents::OnLeaveBreakPoint | Handles an event for leaving a breakpoint.
IRemoteDebugApplicationEvents::OnCreateThread | Handles a create thread event.
IRemoteDebugApplicationEvents::OnDestroyThread | Handles a thread-destroyed event.
IRemoteDebugApplicationEvents::OnBreakFlagChange | Handles an event when the break flags change.


IRemoteDebugApplicationEvents::OnBreakFlagChange

Microsoft Windows Script Interfaces
IRemoteDebugApplicationEvents::OnBreakFlagChange
See Also
CollapseAll image DropDown image

Handles an event when the break flags change.

HRESULT OnBreakFlagChange(
   APPBREAKFLAGS                   abf,
   IRemoteDebugApplicationThread*  prdatSteppingThread
);

Parameters

abf

[in] The current break flags for the application.

prdatSteppingThread

[in] The currently running thread.

Expand image Return Value

The method returns an HRESULT. Possible values include, but are not limited to, those in the following table.

Value | Description
S_OK | The method succeeded.

Expand image Remarks

This method handles the event when the break flag change.

Expand image See Also

Reference

APPBREAKFLAGS Constants

Concepts

IRemoteDebugApplicationEvents Interface


IRemoteDebugApplicationEvents::OnClose

Microsoft Windows Script Interfaces
IRemoteDebugApplicationEvents::OnClose
See Also
CollapseAll image DropDown image

Handles an application close event.

HRESULT OnClose();

Parameters

This method takes no parameters.

Expand image Return Value

The method returns an HRESULT. Possible values include, but are not limited to, those in the following table.

Value | Description
S_OK | The method succeeded.

Expand image Remarks

This method handles an application close event.

Expand image See Also

Concepts

IRemoteDebugApplicationEvents Interface


IRemoteDebugApplicationEvents::OnConnectDebugger

Microsoft Windows Script Interfaces
IRemoteDebugApplicationEvents::OnConnectDebugger
See Also
CollapseAll image DropDown image

Handles a debugger connect event.

HRESULT OnConnectDebugger(
   IApplicationDebugger*  pad
);

Parameters

pad

[in] The newly connected debugger.

Expand image Return Value

The method returns an HRESULT. Possible values include, but are not limited to, those in the following table.

Value | Description
S_OK | The method succeeded.

Expand image Remarks

This method handles the debugger connect event.

Expand image See Also

Concepts

IRemoteDebugApplicationEvents Interface


IRemoteDebugApplicationEvents::OnCreateThread

Microsoft Windows Script Interfaces
IRemoteDebugApplicationEvents::OnCreateThread
See Also
CollapseAll image DropDown image

Handles a create thread event.

HRESULT OnCreateThread(
   IRemoteDebugApplicationThread*  prdat
);

Parameters

prdat

[in] The newly created thread.

Expand image Return Value

The method returns an HRESULT. Possible values include, but are not limited to, those in the following table.

Value | Description
S_OK | The method succeeded.

Expand image Remarks

This method handles the create thread event.

Expand image See Also

Concepts

IRemoteDebugApplicationEvents Interface


IRemoteDebugApplicationEvents::OnDebugOutput

Microsoft Windows Script Interfaces
IRemoteDebugApplicationEvents::OnDebugOutput
See Also
CollapseAll image DropDown image

Handles a debugger output event.

HRESULT OnDebugOutput(
   LPCOLESTR  pstr
);

Parameters

pstr

[in] The debug output string.

Expand image Return Value

The method returns an HRESULT. Possible values include, but are not limited to, those in the following table.

Value | Description
S_OK | The method succeeded.

Expand image Remarks

This method handles the debugger output event.

Expand image See Also

Concepts

IRemoteDebugApplicationEvents Interface


IRemoteDebugApplicationEvents::OnDestroyThread

Microsoft Windows Script Interfaces
IRemoteDebugApplicationEvents::OnDestroyThread
See Also
CollapseAll image DropDown image

Handles a thread-destroyed event.

HRESULT OnDestroyThread(
   IRemoteDebugApplicationThread*  prdat
);

Parameters

prdat

[in] The thread that was destroyed.

Expand image Return Value

The method returns an HRESULT. Possible values include, but are not limited to, those in the following table.

Value | Description
S_OK | The method succeeded.

Expand image Remarks

This method handles the thread-destroyed event.

Expand image See Also

Concepts

IRemoteDebugApplicationEvents Interface


IRemoteDebugApplicationEvents::OnDisconnectDebugger

Microsoft Windows Script Interfaces
IRemoteDebugApplicationEvents::OnDisconnectDebugger
See Also
CollapseAll image DropDown image

Handles a debugger disconnect event.

HRESULT OnDisconnectDebugger();

Parameters

This method takes no parameters.

Expand image Return Value

The method returns an HRESULT. Possible values include, but are not limited to, those in the following table.

Value | Description
S_OK | The method succeeded.

Expand image Remarks

This method handles the debugger disconnect event.

Expand image See Also

Concepts

IRemoteDebugApplicationEvents Interface


IRemoteDebugApplicationEvents::OnEnterBreakPoint

Microsoft Windows Script Interfaces
IRemoteDebugApplicationEvents::OnEnterBreakPoint
See Also
CollapseAll image DropDown image

Handles an event for entering a breakpoint.

HRESULT OnEnterBreakPoint(
   IRemoteDebugApplicationThread*  prdat
);

Parameters

prdat

[in] The application thread that entered the breakpoint.

Expand image Return Value

The method returns an HRESULT. Possible values include, but are not limited to, those in the following table.

Value | Description
S_OK | The method succeeded.

Expand image Remarks

This method handles an event for entering a breakpoint.

Expand image See Also

Concepts

IRemoteDebugApplicationEvents Interface


IRemoteDebugApplicationEvents::OnLeaveBreakPoint

Microsoft Windows Script Interfaces
IRemoteDebugApplicationEvents::OnLeaveBreakPoint
See Also
CollapseAll image DropDown image

Handles an event for leaving a breakpoint.

HRESULT OnLeaveBreakPoint(
   IRemoteDebugApplicationThread*  prdat
);

Parameters

prdat

[in] The application thread that left the breakpoint.

Expand image Return Value

The method returns an HRESULT. Possible values include, but are not limited to, those in the following table.

Value | Description
S_OK | The method succeeded.

Expand image Remarks

This method handles an event for leaving a breakpoint.

Expand image See Also

Concepts

IRemoteDebugApplicationEvents Interface


IRemoteDebugApplicationEvents::OnSetName

Microsoft Windows Script Interfaces
IRemoteDebugApplicationEvents::OnSetName
See Also
CollapseAll image DropDown image

Handles a set name event.

HRESULT OnSetName(
   LPCOLESTR  pstrName
);

Parameters

pstrName

[in] The new name.

Expand image Return Value

The method returns an HRESULT. Possible values include, but are not limited to, those in the following table.

Value | Description
S_OK | The method succeeded.

Expand image Remarks

This method handles a set name event.

Expand image See Also

Concepts

IRemoteDebugApplicationEvents Interface


IRemoteDebugApplicationThread Interface

Microsoft Windows Script Interfaces
IRemoteDebugApplicationThread Interface
DropDown image

Represents a thread of execution within a particular application.

In addition to the methods inherited from IUnknown, the IRemoteDebugApplicationThread interface exposes the following methods.

Methods in Vtable Order

Method | Description
IRemoteDebugApplicationThread::GetSystemThreadId | Returns an operating-system dependent identifier associated with the thread.
IRemoteDebugApplicationThread::GetApplication | Returns the application object associated with this thread.
IRemoteDebugApplicationThread::EnumStackFrames | Returns an enumerator for the stack frames associated with this thread.
IRemoteDebugApplicationThread::GetDescription | Gets the description and state of this thread.
IRemoteDebugApplicationThread::SetNextStatement | Forces execution to continue as close as possible to the given code context, in the context of the given frame.
IRemoteDebugApplicationThread::GetState | Gets the state of this thread.
IRemoteDebugApplicationThread::Suspend | Suspends the thread.
IRemoteDebugApplicationThread::Resume | Resumes the thread.
IRemoteDebugApplicationThread::GetSuspendCount | Returns the suspend count for the thread.


IRemoteDebugApplicationThread::EnumStackFrames

Microsoft Windows Script Interfaces
IRemoteDebugApplicationThread::EnumStackFrames
See Also
CollapseAll image DropDown image

Returns an enumerator for the stack frames associated with this thread.

HRESULT EnumStackFrames(
   IEnumDebugStackFrames**  ppedsf
);

Parameters

ppedsf

[out] An enumerator for the stack frames associated with this thread.

Expand image Return Value

The method returns an HRESULT. Possible values include, but are not limited to, those in the following table.

Value | Description
S_OK | The method succeeded.

Expand image Remarks

This method must be called from within a breakpoint. The stack frame enumerator should return the frames starting at the top of the stack, starting with the most recently pushed frame.

Expand image See Also

Concepts

IRemoteDebugApplicationThread Interface


IRemoteDebugApplicationThread::GetApplication

Microsoft Windows Script Interfaces
IRemoteDebugApplicationThread::GetApplication
See Also
CollapseAll image DropDown image

Returns the application object associated with this thread.

HRESULT GetApplication(
   IRemoteDebugApplication**  pprda
);

Parameters

pprda

[out] The application object associated with this thread.

Expand image Return Value

The method returns an HRESULT. Possible values include, but are not limited to, those in the following table.

Value | Description
S_OK | The method succeeded.

Expand image Remarks

This method returns the application object associated with this thread.

Expand image See Also

Concepts

IRemoteDebugApplicationThread Interface


IRemoteDebugApplicationThread::GetDescription

Microsoft Windows Script Interfaces
IRemoteDebugApplicationThread::GetDescription
See Also
CollapseAll image DropDown image

Gets the description and state of this thread.

HRESULT GetDescription(
   BSTR*  pbstrDescription,
   BSTR*  pbstrState
);

Parameters

pbstrDescription

[out] The description of this thread.

pbstrState

[out] The description of the thread state.

Expand image Return Value

The method returns an HRESULT. Possible values include, but are not limited to, those in the following table.

Value | Description
S_OK | The method succeeded.

Expand image Remarks

This method gets the description and state of this thread.

Expand image See Also

Concepts

IRemoteDebugApplicationThread Interface


IRemoteDebugApplicationThread::GetState

Microsoft Windows Script Interfaces
IRemoteDebugApplicationThread::GetState
See Also
CollapseAll image DropDown image

Gets the state of this thread.

HRESULT GetState(
   DWORD*  pState
);

Parameters

pState

[out] Combination of the following thread state flags:

Constant Value Description

THREAD_STATE_RUNNING

0x00000001

The thread is running.

THREAD_STATE_SUSPENDED

0x00000002

The thread is suspended.

THREAD_BLOCKED

0x00000004

The thread is blocked.

THREAD_OUT_OF_CONTEXT

0x00000008

The thread is out of content.

Expand image Return Value

The method returns an HRESULT. Possible values include, but are not limited to, those in the following table.

Value | Description
S_OK | The method succeeded.

Expand image Remarks

This method gets the state of this thread.

Expand image See Also

Concepts

IRemoteDebugApplicationThread Interface


IRemoteDebugApplicationThread::GetSuspendCount

Microsoft Windows Script Interfaces
IRemoteDebugApplicationThread::GetSuspendCount
See Also
CollapseAll image DropDown image

Returns the suspend count for the thread.

HRESULT GetSuspendCount(
   DWORD*  pdwCount
);

Parameters

pdwCount

[out] The suspend count for the thread.

Expand image Return Value

The method returns an HRESULT. Possible values include, but are not limited to, those in the following table.

Value | Description
S_OK | The method succeeded.

Expand image Remarks

This method returns the suspend count for the thread.

Expand image See Also

Concepts

IRemoteDebugApplicationThread Interface


IRemoteDebugApplicationThread::GetSystemThreadId

Microsoft Windows Script Interfaces
IRemoteDebugApplicationThread::GetSystemThreadId
See Also
CollapseAll image DropDown image

Returns an operating-system-dependent identifier associated with the thread.

HRESULT GetSystemThreadId(
   DWORD*  dwThreadId
);

Parameters

dwThreadId

[out] An operating-system-dependent identifier associated with the thread.

Expand image Return Value

The method returns an HRESULT. Possible values include, but are not limited to, those in the following table.

Value | Description
S_OK | The method succeeded.

Expand image Remarks

The value of dwThreadId does not need to be unique across machines.

Expand image See Also

Concepts

IRemoteDebugApplicationThread Interface


IRemoteDebugApplicationThread::Resume

Microsoft Windows Script Interfaces
IRemoteDebugApplicationThread::Resume
See Also
CollapseAll image DropDown image

Resumes the thread.

HRESULT Resume(
   DWORD*  pdwCount
);

Parameters

pdwCount

[out] The suspend count for the thread.

Expand image Return Value

The method returns an HRESULT. Possible values include, but are not limited to, those in the following table.

Value | Description
S_OK | The method succeeded.

Expand image Remarks

When this method resumes the thread, it decrements the suspend count.

Expand image See Also

Concepts

IRemoteDebugApplicationThread Interface


IRemoteDebugApplicationThread::SetNextStatement

Microsoft Windows Script Interfaces
IRemoteDebugApplicationThread::SetNextStatement
See Also
CollapseAll image DropDown image

Forces execution to continue as close as possible to the given code context, in the context of the given frame.

HRESULT SetNextStatement(
   IDebugStackFrame*   pStackFrame,
   IDebugCodeContext*  pCodeContext
);

Parameters

pStackFrame

[in] The stack frame object. This argument may be NULL, which implies the current stack frame should be used.

pCodeContext

[in] The code context. This argument may be NULL, which implies the current code context should be used.

Expand image Return Value

The method returns an HRESULT. Possible values include, but are not limited to, those in the following table.

Value | Description
S_OK | The method succeeded.

Expand image Remarks

This method forces execution to continue as close as possible to the code context specified by pCodeContext, in the context of the frame specified by pStackFrame. Either of these arguments may be NULL, representing the current frame or context.

Expand image See Also

Concepts

IRemoteDebugApplicationThread Interface


IRemoteDebugApplicationThread::Suspend

Microsoft Windows Script Interfaces
IRemoteDebugApplicationThread::Suspend
See Also
CollapseAll image DropDown image

Suspends the thread.

HRESULT Suspend(
   DWORD*  pdwCount
);

Parameters

pdwCount

[out] The suspend count for the thread.

Expand image Return Value

The method returns an HRESULT. Possible values include, but are not limited to, those in the following table.

Value | Description
S_OK | The method succeeded.

Expand image Remarks

When this method suspends the thread, it increments the suspend count.

Expand image See Also

Concepts

IRemoteDebugApplicationThread Interface


ISimpleConnectionPoint Interface

Microsoft Windows Script Interfaces
ISimpleConnectionPoint Interface
See Also
DropDown image

Provides a simple way for describing and enumerating the events fired on a particular connection point. This interface also makes it easy to hook up an IDispatch object to those events. This interface is implemented by the Process Debug Manager (PDM), and consumed by script engines.

This interface is available from IDebugHelper::CreateSimpleConnectionPoint.

In addition to the methods inherited from IUnknown, the ISimpleConnectionPoint interface exposes the following methods.

Methods in Vtable Order

Method | Description
ISimpleConnectionPoint::Advise | Establishes a connection between the simple connection point object and the client's sink.
ISimpleConnectionPoint::DescribeEvents | Returns the DISPID and name for each event in a specified range of events.
ISimpleConnectionPoint::GetEventCount | Returns the number of events exposed on this interface.
ISimpleConnectionPoint::Unadvise | Terminates an advisory connection previously established through ISimpleConnectionPoint::Advise.

See Also

Concepts

IDebugProperty Interface


ISimpleConnectionPoint::Advise

Microsoft Windows Script Interfaces
ISimpleConnectionPoint::Advise
See Also
CollapseAll image DropDown image

Establishes a connection between the simple connection point object and the client's sink.

HRESULT Advise(
   IDispatch*  pdisp,
   DWORD*      pdwCookie
);

Parameters

pdisp

[in] Pointer to the IDispatch interface on the client's advise sink. The client's sink receives outgoing calls from the simple connection point.

pdwCookie

[out] Pointer to a returned token that uniquely identifies this connection. The caller uses this token later to delete the connection by passing it to the ISimpleConnectionPoint::Unadvise method. If the connection was not successfully established, this value is zero.

Expand image Return Value

The method returns an HRESULT. Possible values include, but are not limited to, those in the following table.

Value | Description
S_OK | The method succeeded.

Expand image Remarks

This method establishes a connection between the simple connection point object and the client's sink.

Expand image See Also

Reference

ISimpleConnectionPoint::Unadvise

Concepts

ISimpleConnectionPoint Interface


ISimpleConnectionPoint::DescribeEvents

Microsoft Windows Script Interfaces
ISimpleConnectionPoint::DescribeEvents
See Also
CollapseAll image DropDown image

Returns the DISPID and name for each event in a specified range of events.

HRESULT DescribeEvents(
   ULONG    iEvent,
   ULONG    cEvents,
   DISPID*  prgid,
   BSTR*    prgbstr,
   ULONG*   pcEventsFetched
);

Parameters

iEvent

[in] Index of the first event to retrieve.

cEvents

[in] Number of events to retrieve.

prgid

[out] Array of event DISPID values.

prgbstr

[out] Array of event names.

pcEventsFetched

[out] The actual number of events fetched.

Expand image Return Value

The method returns an HRESULT. Possible values include, but are not limited to, those in the following table.

Value | Description
S_OK | The method succeeded.
S_FALSE | More events were requested than were available. Unavailable events are represented with DISPID_NULL and a null BSTR.
E_INVALIDARG | No elements could be fetched.

Expand image Remarks

This method returns the DISPID and name for each event in a specified range of events.

Expand image See Also

Concepts

ISimpleConnectionPoint Interface


ISimpleConnectionPoint::GetEventCount

Microsoft Windows Script Interfaces
ISimpleConnectionPoint::GetEventCount
See Also
CollapseAll image DropDown image

Returns the number of events exposed on this interface.

HRESULT GetEventCount(
   ULONG*  pulCount
);

Parameters

pulCount

[out] Number of events exposed on this interface count.

Expand image Return Value

The method returns an HRESULT. Possible values include, but are not limited to, those in the following table.

Value | Description
S_OK | The method succeeded.

Expand image Remarks

This method returns the number of events exposed on this interface.

Expand image See Also

Concepts

ISimpleConnectionPoint Interface


ISimpleConnectionPoint::Unadvise

Microsoft Windows Script Interfaces
ISimpleConnectionPoint::Unadvise
See Also
CollapseAll image DropDown image

Terminates an advisory connection previously established through ISimpleConnectionPoint::Advise.

HRESULT Unadvise(
   DWORD  dwCookie
);

Parameters

dwCookie

[in] Token of the connection to terminate, as returned from ISimpleConnectionPoint::Advise.

Expand image Return Value

The method returns an HRESULT. Possible values include, but are not limited to, those in the following table.

Value | Description
S_OK | The method succeeded.

Expand image Remarks

When an advisory connection is terminated, the connection point calls the Release method on the pointer that was saved for the connection during the ISimpleConnectionPoint::Advise method. That call reverses the AddRef that was performed during the ISimpleConnectionPoint::Advise when the connection point calls the advisory sink's QueryInterface.

Expand image See Also

Concepts

ISimpleConnectionPoint Interface


Active Script Interfaces

Microsoft Windows Script Interfaces
Active Script Interfaces
DropDown image

The ActivScp.h header file provides the interfaces listed in this section.

In This Section

The following interfaces are specific to the Microsoft® Windows® Script Host.

  • IActiveScriptSite Interface

  • IActiveScriptSiteInterruptPoll Interface

  • IActiveScriptSiteWindow Interface

The following interfaces are specific to Windows Script Engines.

  • IActiveScript Interface

  • IActiveScriptError Interface

  • IActiveScriptParse Interface

  • IActiveScriptParseProcedure Interface

  • IActiveScriptParseProcedureOld Interface

  • IActiveScriptStats Interface

  • IBindEventHandler Interface

The following enumerations are specific to Windows Script Engines.

  • SCRIPTSTATE

  • SCRIPTTHREADID

  • SCRIPTTHREADSTATE


Enumerations (Microsoft Windows Script Technologies)

Microsoft Windows Script Interfaces
Enumerations (Microsoft Windows Script Technologies)
DropDown image

This section describes the enumerations used by Windows Script engines.

SCRIPTSTATE

SCRIPTTHREADID

SCRIPTTHREADSTATE


SCRIPTSTATE

Microsoft Windows Script Interfaces
SCRIPTSTATE
See Also
CollapseAll image DropDown image

Contains named constant values that specify the state of a scripting engine. This enumeration is used by the IActiveScript::GetScriptState , IActiveScript::SetScriptState , and IActiveScriptSite::OnStateChange methods.

typedef enum tagSCRIPTSTATE {
    SCRIPTSTATE_UNINITIALIZED = 0,
    SCRIPTSTATE_INITIALIZED   = 5,
    SCRIPTSTATE_STARTED       = 1,
    SCRIPTSTATE_CONNECTED     = 2,
    SCRIPTSTATE_DISCONNECTED  = 3,
    SCRIPTSTATE_CLOSED        = 4
} SCRIPTSTATE;

Expand image Enumeration Values

SCRIPTSTATE_UNINITIALIZED | Script has just been created, but has not yet been initialized using an IPersist* interface and IActiveScript::SetScriptSite .
SCRIPTSTATE_INITIALIZED | Script has been initialized, but is not running (connecting to other objects or sinking events) or executing any code. Code can be queried for execution by calling the IActiveScriptParse::ParseScriptText method.
SCRIPTSTATE_STARTED | Script can execute code, but is not yet sinking the events of objects added by the IActiveScript::AddNamedItem method.
SCRIPTSTATE_CONNECTED | Script is loaded and connected for sinking events.
SCRIPTSTATE_DISCONNECTED | Script is loaded and has a run-time execution state, but is temporarily disconnected from sinking events.
SCRIPTSTATE_CLOSED | Script has been closed. The scripting engine no longer works and returns errors for most methods.

Expand image See Also

Other Resources

Enumerations (Microsoft Windows Script Technologies)


SCRIPTTHREADID

Microsoft Windows Script Interfaces
SCRIPTTHREADID
See Also
CollapseAll image DropDown image

Used to store a thread identifier or signify a special thread or class of threads.

typedef DWORD SCRIPTTHREADID;

Expand image Constants

Constant | Value | Meaning
SCRIPTTHREADID_CURRENT | 0xFFFFFFFD | The currently executing thread.
SCRIPTTHREADID_BASE | 0xFFFFFFFE | The base thread; that is, the thread in which the scripting engine was instantiated.
SCRIPTTHREADID_ALL | 0xFFFFFFFF | All threads.

Expand image Remarks

The SCRIPTTHREADID type is used by IActiveScript::GetCurrentScriptThreadID, IActiveScript::GetScriptThreadID, IActiveScript::GetScriptThreadState, and IActiveScript::InterruptScriptThread, but the constants can only be used by IActiveScript::GetScriptThreadState and IActiveScript::InterruptScriptThread.

Expand image See Also

Reference

IActiveScript::GetCurrentScriptThreadID
IActiveScript::GetScriptThreadID
IActiveScript::GetScriptThreadState
IActiveScript::InterruptScriptThread


SCRIPTTHREADSTATE

Microsoft Windows Script Interfaces
SCRIPTTHREADSTATE
See Also
CollapseAll image DropDown image

Contains named constant values that specify the state of a thread in a scripting engine. This enumeration is used by the IActiveScript::GetScriptThreadState method.

typedef enum tagSCRIPTTHREADSTATE {
    SCRIPTTHREADSTATE_NOTINSCRIPT  = 0,
    SCRIPTTHREADSTATE_RUNNING      = 1
} SCRIPTTHREADSTATE;

Expand image Enumeration Values

SCRIPTTHREADSTATE_NOTINSCRIPT | Specified thread is not currently servicing a scripted event, processing immediately executed script text, or running a script macro.
SCRIPTTHREADSTATE_RUNNING | Specified thread is actively servicing a scripted event, processing immediately executed script text, or running a script macro.

Expand image See Also

Other Resources

Enumerations (Microsoft Windows Script Technologies)


IActiveScript

Microsoft Windows Script Interfaces
IActiveScript
See Also
DropDown image

Provides the methods necessary to initialize the scripting engine. The scripting engine must implement the IActiveScript interface.

Methods in Vtable Order

Method | Description
IActiveScript::SetScriptSite | Informs the scripting engine of the IActiveScriptSite site provided by the host.
IActiveScript::GetScriptSite | Retrieves the site object associated with the Windows Script engine.
IActiveScript::SetScriptState | Places the scripting engine into the specified state.
IActiveScript::GetScriptState | Retrieves the current state of the scripting engine.
IActiveScript::Close | Causes the scripting engine to abandon any currently loaded script, lose its state, and release any interface pointers it has to other objects, thus entering a closed state.
IActiveScript::AddNamedItem | Adds the name of a root-level item to the scripting engine's namespace.
IActiveScript::AddTypeLib | Adds a type library to the namespace for the script.
IActiveScript::GetScriptDispatch | Retrieves the IDispatch interface for the running script.
IActiveScript::GetCurrentScriptThreadID | Retrieves a scripting-engine-defined identifier for the currently executing thread.
IActiveScript::GetScriptThreadID | Retrieves a scripting-engine-defined identifier for the thread associated with the given Microsoft Win32® thread.
IActiveScript::GetScriptThreadState | Retrieves the current state of a script thread.
IActiveScript::InterruptScriptThread | Interrupts the execution of a running script thread.
IActiveScript::Clone | Clones the current scripting engine (minus any current execution state), returning a loaded scripting engine that has no site in the current thread.

See Also

Other Resources

Windows Script Interfaces Reference


IActiveScript::AddNamedItem

Microsoft Windows Script Interfaces
IActiveScript::AddNamedItem
See Also
CollapseAll image DropDown image

Adds the name of a root-level item to the scripting engine's name space. A root-level item is an object with properties and methods, an event source, or all three.

HRESULT AddNamedItem(    LPCOLESTR pstrName,  // address of item name    DWORD dwFlags          // item flags);

Parameters

pstrName

[in] Address of a buffer that contains the name of the item as viewed from the script. The name must be unique and persistable.

dwFlags

[in] Flags associated with an item. Can be a combination of these values:

Value | Meaning
SCRIPTITEM_CODEONLY | Indicates that the named item represents a code-only object, and that the host has no IUnknown to be associated with this code-only object. The host only has a name for this object. In object-oriented languages such as C++, this flag would create a class. Not all languages support this flag.
SCRIPTITEM_GLOBALMEMBERS | Indicates that the item is a collection of global properties and methods associated with the script. Normally, a scripting engine would ignore the object name (other than for the purpose of using it as a cookie for the IActiveScriptSite::GetItemInfo method, or for resolving explicit scoping) and expose its members as global variables and methods. This allows the host to extend the library (run-time functions and so on) available to the script. It is left to the scripting engine to deal with name conflicts (for example, when two SCRIPTITEM_GLOBALMEMBERS items have methods of the same name), although an error should not be returned because of this situation.
SCRIPTITEM_ISPERSISTENT | Indicates that the item should be saved if the scripting engine is saved. Similarly, setting this flag indicates that a transition back to the initialized state should retain the item's name and type information (the scripting engine must, however, release all pointers to interfaces on the actual object).
SCRIPTITEM_ISSOURCE | Indicates that the item sources events that the script can sink. Child objects (properties of the object that are in themselves objects) can also source events to the script. This is not recursive, but it provides a convenient mechanism for the common case, for example, of creating a container and all of its member controls.
SCRIPTITEM_ISVISIBLE | Indicates that the item's name is available in the name space of the script, allowing access to the properties, methods, and events of the item. By convention the properties of the item include the item's children; therefore, all child object properties and methods (and their children, recursively) will be accessible.
SCRIPTITEM_NOCODE | Indicates that the item is simply a name being added to the script's name space, and should not be treated as an item for which code should be associated. For example, without this flag being set, VBScript will create a separate module for the named item, and C++ might create a separate wrapper class for the named item.

Expand image Return Value

Returns one of the following values:

Return Value | Meaning
S_OK | Success.
E_INVALIDARG | An argument was invalid.
E_POINTER | An invalid pointer was specified.
E_UNEXPECTED | The call was not expected (for example, the scripting engine has not yet been loaded or initialized).

Expand image See Also

Concepts

IActiveScript


IActiveScript::AddTypeLib

Microsoft Windows Script Interfaces
IActiveScript::AddTypeLib
See Also
CollapseAll image DropDown image

Adds a type library to the name space for the script. This is similar to the #include directive in C/C++. It allows a set of predefined items such as class definitions, typedefs, and named constants to be added to the run-time environment available to the script.

HRESULT AddTypeLib(
    REFGUID guidTypeLib,  // CLSID of type library
    DWORD dwMaj,          // major version number
    DWORD dwMin,          // minor version number
    DWORD dwFlags         // option flags
);

Parameters

guidTypeLib

[in] CLSID of the type library to add.

dwMaj

[in] Major version number.

dwMin

[in] Minor version number.

dwFlags

[in] Option flags. Can be the following:

Value | Meaning
SCRIPTTYPELIB_ISCONTROL | The type library describes an ActiveX control used by the host.

Expand image Return Value

Returns one of the following values:

Return Value | Meaning
S_OK | Success.
E_INVALIDARG | An argument was invalid.
E_UNEXPECTED | The call was not expected (for example, the scripting engine has not yet been loaded or initialized).
TYPE_E_CANTLOADLIBRARY | The specified type library could not be loaded.

Expand image See Also

Concepts

IActiveScript


IActiveScript::Clone

Microsoft Windows Script Interfaces
IActiveScript::Clone
See Also
CollapseAll image DropDown image

Clones the current scripting engine (minus any current execution state), returning a loaded scripting engine that has no site in the current thread. The properties of this new scripting engine will be identical to the properties the original scripting engine would be in if it were transitioned back to the initialized state.

HRESULT Clone(
    IActiveScript **ppscript  // receives pointer to IActiveScript
);

Parameters

ppscript

[out] Address of a variable that receives a pointer to the IActiveScript interface of the cloned scripting engine. The host must create a site and call the IActiveScript::SetScriptSite method on the new scripting engine before it will be in the initialized state and, therefore, usable.

Expand image Return Value

Returns one of the following values:

Return Value | Meaning
S_OK | Success.
E_NOTIMPL | This method is not supported.
E_POINTER | An invalid pointer was specified.
E_UNEXPECTED | The call was not expected (for example, the scripting engine has not yet been loaded or initialized).

Expand image Remarks

The IActiveScript::Clone method is an optimization of IPersist*::Save, CoCreateInstance, and IPersist*::Load, so the state of the new scripting engine should be the same as if the state of the original scripting engine were saved and loaded into a new scripting engine. Named items are duplicated in the cloned scripting engine, but specific object pointers for each item are forgotten and are obtained with the IActiveScriptSite::GetItemInfo method. This allows an identical object model with per-thread entry points (an apartment model) to be used.

This method is used for multithreaded server hosts that can run multiple instances of the same script. The scripting engine may return E_NOTIMPL, in which case the host can achieve the same result by duplicating the persistent state and creating a new instance of the scripting engine with an IPersist* interface.

This method can be called from non-base threads without resulting in a non-base callout to host objects or to the IActiveScriptSite interface.

Expand image See Also

Concepts

IActiveScript


IActiveScript::Close

Microsoft Windows Script Interfaces
IActiveScript::Close
See Also
CollapseAll image DropDown image

Causes the scripting engine to abandon any currently loaded script, lose its state, and release any interface pointers it has to other objects, thus entering a closed state. Event sinks, immediately executed script text, and macro invocations that are already in progress are completed before the state changes (use IActiveScript::InterruptScriptThread to cancel a running script thread). This method must be called by the creating host before the interface is released to prevent circular reference problems.

HRESULT Close(void);

Expand image Return Value

Returns one of the following values:

Value | Meaning
S_OK | Success.
E_UNEXPECTED | The call was not expected (for example, the scripting engine was already in the closed state).
OLESCRIPT_S_PENDING | The method was queued successfully, but the state has not changed yet. When the state changes, the site is to be called back on the IActiveScriptSite::OnStateChange method.
S_FALSE | The method succeeded, but the script has already been closed.

Expand image See Also

Concepts

IActiveScript


IActiveScript::GetCurrentScriptThreadID

Microsoft Windows Script Interfaces
IActiveScript::GetCurrentScriptThreadID
See Also
CollapseAll image DropDown image

Retrieves a scripting-engine-defined identifier for the currently executing thread. The identifier can be used in subsequent calls to script thread execution-control methods such as the IActiveScript::InterruptScriptThread method.

HRESULT GetCurrentScriptThreadID(
    SCRIPTTHREADID *pstidThread  // receives scripting thread identifier
);

Parameters

pstidThread

[out] Address of a variable that receives the script thread identifier associated with the current thread. The interpretation of this identifier is left to the scripting engine, but it can be just a copy of the Windows thread identifier. If the Win32 thread terminates, this identifier becomes unassigned and can subsequently be assigned to another thread.

Expand image Return Value

Returns S_OK if successful, or E_POINTER if an invalid pointer was specified.

Expand image Remarks

This method can be called from non-base threads without resulting in a non-base callout to host objects or to the IActiveScriptSite interface.

Expand image See Also

Concepts

IActiveScript


IActiveScript::GetScriptDispatch

Microsoft Windows Script Interfaces
IActiveScript::GetScriptDispatch
See Also
CollapseAll image DropDown image

Retrieves the IDispatch interface for the methods and properties associated with the currently running script.

HRESULT GetScriptDispatch(
    LPCOLESTR pstrItemName  // address of item name
    IDispatch **ppdisp      // receives IDispatch pointer
);

Parameters

pstrItemName

[in] Address of a buffer that contains the name of the item for which the caller needs the associated dispatch object. If this parameter is NULL, the dispatch object contains as its members all of the global methods and properties defined by the script. Through the IDispatch interface and the associated ITypeInfo interface, the host can invoke script methods or view and modify script variables.

ppdisp

[out] Address of a variable that receives a pointer to the object associated with the script's global methods and properties. If the scripting engine does not support such an object, NULL is returned.

Expand image Return Value

Returns one of the following values:

Return Value | Meaning
S_OK | Success.
E_INVALIDARG | An argument was invalid.
E_POINTER | An invalid pointer was specified.
E_UNEXPECTED | The call was not expected (for example, the scripting engine has not yet been loaded or initialized).
S_FALSE | The scripting engine does not support a dispatch object; the ppdisp parameter is set to NULL.

Expand image Remarks

Because methods and properties can be added by calling the IActiveScriptParse interface, the IDispatch interface returned by this method can dynamically support new methods and properties. Similarly, the IDispatch::GetTypeInfo method should return a new, unique ITypeInfo interface when methods and properties are added. Note, however, that language engines must not change the IDispatch interface in a way that is incompatible with any previous ITypeInfo interface returned. That implies, for example, that DISPIDs will never be reused.

Expand image See Also

Concepts

IActiveScript


IActiveScript::GetScriptSite

Microsoft Windows Script Interfaces
IActiveScript::GetScriptSite
See Also
CollapseAll image DropDown image

Retrieves the site object associated with the Windows Script engine.

HRESULT GetScriptSite(
    REFIID iid,           // interface identifier
    void **ppvSiteObject  // address of host site interface
);

Parameters

iid

[in] Identifier of the requested interface.

ppvSiteObject

[out] Address of the location that receives the interface pointer to the host's site object.

Expand image Return Value

Returns one of the following values:

Return Value | Meaning
S_OK | Success.
E_INVALIDARG | An argument was invalid.
E_NOINTERFACE | The specified interface is not supported.
E_POINTER | An invalid pointer was specified.
S_FALSE | No site has been set; the ppvSiteObject parameter is set to NULL.

Expand image See Also

Concepts

IActiveScript


IActiveScript::GetScriptState

Microsoft Windows Script Interfaces
IActiveScript::GetScriptState
See Also
CollapseAll image DropDown image

Retrieves the current state of the scripting engine. This method can be called from non-base threads without resulting in a non-base callout to host objects or to the IActiveScriptSite interface.

HRESULT GetScriptState(
    SCRIPTSTATE *pss  // address of structure for state information
);

Parameters

pss

[out] Address of a variable that receives a value defined in the SCRIPTSTATE enumeration. The value indicates the current state of the scripting engine associated with the calling thread.

Expand image Return Value

Returns S_OK if successful, or E_POINTER if an invalid pointer was specified.

Expand image See Also

Concepts

IActiveScript


IActiveScript::GetScriptThreadID

Microsoft Windows Script Interfaces
IActiveScript::GetScriptThreadID
See Also
CollapseAll image DropDown image

Retrieves a scripting-engine-defined identifier for the thread associated with the given Win32 thread.

HRESULT GetScriptThreadID(
    DWORD dwWin32ThreadID,       // Win32 thread identifier.
    SCRIPTTHREADID *pstidThread  // Receives scripting thread. identifier
);

Parameters

dwWin32ThreadID

[in] Thread identifier of a running Win32 thread in the current process. Use the IActiveScript::GetCurrentScriptThreadID function to retrieve the thread identifier of the currently executing thread.

pstidThread

[out] Address of a variable that receives the script thread identifier associated with the given Win32 thread. The interpretation of this identifier is left to the scripting engine, but it can be just a copy of the Windows thread identifier. Note that if the Win32 thread terminates, this identifier becomes unassigned and may subsequently be assigned to another thread.

Expand image Return Value

Returns one of the following values:

Return Value | Meaning
S_OK | Success.
E_POINTER | An invalid pointer was specified.
E_UNEXPECTED | The call was not expected (for example, the scripting engine has not yet been loaded or initialized) and therefore failed.

Expand image Remarks

The retrieved identifier can be used in subsequent calls to script thread execution control methods such as the IActiveScript::InterruptScriptThread method.

This method can be called from non-base threads without resulting in a non-base callout to host objects or to the IActiveScript::InterruptScriptThread interface.

Expand image See Also

Concepts

IActiveScript


IActiveScript::GetScriptThreadState

Microsoft Windows Script Interfaces
IActiveScript::GetScriptThreadState
See Also
CollapseAll image DropDown image

Retrieves the current state of a script thread.

HRESULT GetScriptThreadState(
    SCRIPTTHREADID stidThread,    // identifier of script thread
    SCRIPTTHREADSTATE *pstsState  // receives state flag
);

Parameters

stidThread

[in] Identifier of the thread for which the state is desired, or one of the following special thread identifiers:

Value | Meaning
SCRIPTTHREADID_BASE | The base thread; that is, the thread in which the scripting engine was instantiated.
SCRIPTTHREADID_CURRENT | The currently executing thread.
pstsState

[out] Address of a variable that receives the state of the indicated thread. The state is indicated by one of the named constant values defined by the SCRIPTTHREADSTATE enumeration. If this parameter does not identify the current thread, the state may change at any time.

Expand image Return Value

Returns one of the following values:

Return Value | Meaning
S_OK | Success.
E_POINTER | An invalid pointer was specified.
E_UNEXPECTED | The call was not expected (for example, the scripting engine has not yet been loaded or initialized).

Expand image Remarks

This method can be called from non-base threads without resulting in a non-base callout to host objects or to the IActiveScriptSite interface.

Expand image See Also

Concepts

IActiveScript


IActiveScript::InterruptScriptThread

Microsoft Windows Script Interfaces
IActiveScript::InterruptScriptThread
See Also
CollapseAll image DropDown image

Interrupts the execution of a running script thread (an event sink, an immediate execution, or a macro invocation). This method can be used to terminate a script that is stuck (for example, in an infinite loop). It can be called from non-base threads without resulting in a non-base callout to host objects or to the IActiveScriptSite method.

HRESULT InterruptScriptThread(
    SCRIPTTHREADID   stidThread,  // identifier of thread
    const EXCEPINFO *pexcepinfo,  // receives error information
    DWORD dwFlags
);

Parameters

stidThread

[in] Identifier of the thread to interrupt, or one of the following special thread identifier values:

Value | Meaning
SCRIPTTHREADID_ALL | All threads. The interrupt is applied to all script methods currently in progress. Note that unless the caller has requested that the script be disconnected, the next scripted event causes script code to run again by calling the IActiveScript::SetScriptState method with the SCRIPTSTATE_DISCONNECTED or SCRIPTSTATE_INITIALIZED flag set.
SCRIPTTHREADID_BASE | The base thread; that is, the thread in which the scripting engine was instantiated.
SCRIPTTHREADID_CURRENT | The currently executing thread.
pexcepinfo

[in] Address of an EXCEPINFO structure containing the error information that should be reported to the aborted script.

dwFlags

[in] Option flags associated with the interruption. Can be one of these values:

Value | Meaning
SCRIPTINTERRUPT_DEBUG | If supported, enter the scripting engine's debugger at the current script execution point.
SCRIPTINTERRUPT_RAISEEXCEPTION | If supported by the scripting engine's language, let the script handle the exception. Otherwise, the script method is aborted and the error code is returned to the caller; that is, the event source or macro invoker.

Expand image Return Value

Returns one of the following values:

Return Value | Meaning
S_OK | Success.
E_INVALIDARG | An argument was invalid.
E_POINTER | An invalid pointer was specified.
E_UNEXPECTED | The call was not expected (for example, the scripting engine has not yet been loaded or initialized).

Expand image See Also

Concepts

IActiveScript


IActiveScript::SetScriptSite

Microsoft Windows Script Interfaces
IActiveScript::SetScriptSite
See Also
CollapseAll image DropDown image

Informs the scripting engine of the IActiveScriptSite interface site provided by the host. Call this method before any other IActiveScript interface methods is used.

HRESULT SetScriptSite(
    IActiveScriptSite *pScriptSite  // address of host script site
);

Parameters

pScriptSite

[in] Address of the host-supplied script site to be associated with this instance of the scripting engine. The site must be uniquely assigned to this scripting engine instance; it cannot be shared with other scripting engines.

Expand image Return Value

Returns one of the following values:

Return Value | Meaning
S_OK | Success.
E_FAIL | An unspecified error occurred; the scripting engine was unable to finish initializing the site.
E_INVALIDARG | An argument was invalid.
E_POINTER | An invalid pointer was specified.
E_UNEXPECTED | The call was not expected (for example, a site was already set).

Expand image See Also

Concepts

IActiveScript


IActiveScript::SetScriptState

Microsoft Windows Script Interfaces
IActiveScript::SetScriptState
See Also
CollapseAll image DropDown image

Puts the scripting engine into the given state. This method can be called from non-base threads without resulting in a non-base callout to host objects or to the IActiveScriptSite interface.

HRESULT SetScriptState(
    SCRIPTSTATE ss  // identifier of new state
);

Parameters

ss

[in] Sets the scripting engine to the given state. Can be one of the values defined in the SCRIPTSTATE enumeration.

Expand image Return Value

Returns one of the following values:

Return Value | Meaning
S_OK | Success.
E_FAIL | The scripting engine does not support the transition back to the initialized state. The host must discard this scripting engine and create, initialize, and load a new scripting engine to achieve the same effect.
E_UNEXPECTED | The call was not expected (for example, the scripting engine has not yet been loaded or initialized) and therefore failed.
OLESCRIPT_S_PENDING | The method was queued successfully, but the state has not changed yet. When the state changes, the site will be called back through the IActiveScriptSite::OnStateChange method.
S_FALSE | The method succeeded, but the script was already in the given state.

Expand image Remarks

For more information about scripting engine states, see the Script Engine States section of Windows Script Engines .

Expand image See Also

Reference

IActiveScript::Clone
IActiveScript::GetScriptDispatch
IActiveScript::InterruptScriptThread
IActiveScriptParse::ParseScriptText
IActiveScriptSite::GetItemInfo


IActiveScriptError

Microsoft Windows Script Interfaces
IActiveScriptError
See Also
DropDown image

An object implementing this interface is passed to the IActiveScriptSite::OnScriptError method whenever the scripting engine encounters an unhandled error. The host then calls methods on this object to obtain information about the error that occurred.

Methods in Vtable Order

Method | Description
IActiveScriptError::GetExceptionInfo | Retrieves information about an error.
IActiveScriptError::GetSourcePosition | Retrieves the location in the source code where an error occurred.
IActiveScriptError::GetSourceLineText | Retrieves the line in the source file where an error occurred.

See Also

Other Resources

Active Script Interfaces


IActiveScriptError::GetExceptionInfo

Microsoft Windows Script Interfaces
IActiveScriptError::GetExceptionInfo
See Also
CollapseAll image DropDown image

Retrieves information about an error that occurred while the scripting engine was running a script.

HRESULT GetExceptionInfo(
    EXCEPINFO *pexcepinfo  // structure for exception information
);

Parameters

pexcepinfo

[out] Address of an EXCEPINFO structure that receives error information.

Expand image Return Value

Returns S_OK if successful, or E_FAIL if an error occurred.

Expand image See Also

Concepts

IActiveScriptError


IActiveScriptError::GetSourceLineText

Microsoft Windows Script Interfaces
IActiveScriptError::GetSourceLineText
See Also
CollapseAll image DropDown image

Retrieves the line in the source file where an error occurred while a scripting engine was running a script.

HRESULT GetSourceLineText(
    BSTR *pbstrSourceLine  // address of buffer for source line
);

Expand image Parameter

pbstrSourceLine

[out] Address of a buffer that receives the line of source code in which the error occurred.

Expand image Return Value

Returns S_OK if successful, or E_FAIL if the line in the source file was not retrieved.

Expand image See Also

Concepts

IActiveScriptError


IActiveScriptError::GetSourcePosition

Microsoft Windows Script Interfaces
IActiveScriptError::GetSourcePosition
See Also
CollapseAll image DropDown image

Retrieves the location in the source code where an error occurred while the scripting engine was running a script.

HRESULT GetSourcePosition(
    DWORD *pdwSourceContext,  // context cookie
    ULONG *pulLineNumber,     // line number of error
    LONG *pichCharPosition    // character position of error
);

Parameters

pdwSourceContext

[out] Address of a variable that receives a cookie that identifies the context. The interpretation of this parameter depends on the host application.

pulLineNumber

[out] Address of a variable that receives the line number in the source file where the error occurred.

pichCharPosition

[out] Address of a variable that receives the character position in the line where the error occurred.

Expand image Return Value

Returns S_OK if successful, or E_FAIL if the location was not retrieved.

Expand image See Also

Concepts

IActiveScriptError


IActiveScriptParse

Microsoft Windows Script Interfaces
IActiveScriptParse
See Also
DropDown image

If the Windows Script engine allows raw text code scriptlets to be added to the script or allows expression text to be evaluated at run time, it implements the IActiveScriptParse interface. For interpreted scripting languages that have no independent authoring environment, such as VBScript, this provides an alternate mechanism (other than IPersist*) to get script code into the scripting engine, and to attach script fragments to various object events.

Methods in Vtable Order

Method | Description
IActiveScriptParse::InitNew | Initializes the scripting engine.
IActiveScriptParse::AddScriptlet | Adds a code scriptlet to the script.
IActiveScriptParse::ParseScriptText | Parses the given code scriptlet, adding declarations into the name space and evaluating code as appropriate.

See Also

Other Resources

Active Script Interfaces


IActiveScriptParse::AddScriptlet

Microsoft Windows Script Interfaces
IActiveScriptParse::AddScriptlet
See Also
CollapseAll image DropDown image

Adds a code scriptlet to the script. This method is used in environments where the persistent state of the script is intertwined with the host document and the host is responsible for restoring the script, rather than through an IPersist* interface. The primary examples are HTML scripting languages that allow scriptlets of code embedded in the HTML document to be attached to intrinsic events (for instance, ONCLICK="button1.text='Exit'").

HRESULT AddScriptlet(
    LPCOLESTR pstrDefaultName,       // address of default name of scriptlet
    LPCOLESTR pstrCode,              // address of scriptlet text
    LPCOLESTR pstrItemName,          // address of item name
    LPCOLESTR pstrSubItemName,       // address of subitem name
    LPCOLESTR pstrEventName,         // address of event name
    LPCOLESTR pstrDelimiter,         // address of end-of-scriptlet delimiter
    DWORD_PTR dwSourceContextCookie, // application-defined value for debugging
    ULONG ulStartingLineNumber,      // starting line of the script
    DWORD dwFlags,                   // scriptlet flags
    BSTR *pbstrName,                 // address of actual name of scriptlet
    EXCEPINFO *pexcepinfo            // address of exception information
);

Parameters

pstrDefaultName

[in] Address of a default name to associate with the scriptlet. If the scriptlet does not contain naming information (as in the ONCLICK example above), this name will be used to identify the scriptlet. If this parameter is NULL, the scripting engine manufactures a unique name, if necessary.

pstrCode

[in] Address of the scriptlet text to add. The interpretation of this string depends on the scripting language.

pstrItemName

[in] Address of a buffer that contains the item name associated with this scriptlet. This parameter, in addition to pstrSubItemName, identifies the object for which the scriptlet is an event handler.

pstrSubItemName

[in] Address of a buffer that contains the name of a subobject of the named item with which this scriptlet is associated; this name must be found in the named item's type information. This parameter is NULL if the scriptlet is to be associated with the named item instead of a subitem. This parameter, in addition to pstrItemName, identifies the specific object for which the scriptlet is an event handler.

pstrEventName

[in] Address of a buffer that contains the name of the event for which the scriptlet is an event handler.

pstrDelimiter

[in] Address of the end-of-scriptlet delimiter. When the pstrCode parameter is parsed from a stream of text, the host typically uses a delimiter, such as two single quotation marks (''), to detect the end of the scriptlet. This parameter specifies the delimiter that the host used, allowing the scripting engine to provide some conditional primitive preprocessing (for example, replacing a single quotation mark ['] with two single quotation marks for use as a delimiter). Exactly how (and if) the scripting engine makes use of this information depends on the scripting engine. Set this parameter to NULL if the host did not use a delimiter to mark the end of the scriptlet.

dwSourceContextCookie

[in] Application-defined value that is used for debugging purposes.

ulStartingLineNumber

[in] Zero-based value that specifies which line the parsing will begin at.

dwFlags

[in] Flags associated with the scriptlet. Can be a combination of the following values:

Return Value | Meaning
SCRIPTTEXT_ISVISIBLE | Indicates that the script text should be visible (and, therefore, callable by name) as a global method in the name space of the script.
SCRIPTTEXT_ISPERSISTENT | Indicates that the code added during this call should be saved if the scripting engine is saved (for example, through a call to IPersist*::Save), or if the scripting engine is reset by way of a transition back to the initialized state. For more information about this state, see Script Engine States.
pbstrName

[out] Actual name used to identify the scriptlet. This is to be in order of preference: a name explicitly specified in the scriptlet text, the default name provided in pstrDefaultName, or a unique name synthesized by the scripting engine.

pexcepinfo

[out] Address of a structure containing exception information. This structure should be filled in if DISP_E_EXCEPTION is returned.

Expand image Return Value

Returns one of the following values:

Return Value | Meaning
S_OK | Success.
DISP_E_EXCEPTION | An exception occurred in the parsing of the scriptlet. The pexcepinfo parameter contains information about the exception.
E_INVALIDARG | An argument was invalid.
E_NOTIMPL | This method is not supported; the scripting engine does not support adding event-sinking scriptlets.
E_POINTER | An invalid pointer was specified.
E_UNEXPECTED | The call was not expected (for example, the scripting engine has not yet been loaded or initialized) and therefore failed.
OLESCRIPT_E_INVALIDNAME | The default name supplied is invalid in this scripting language.
OLESCRIPT_E_SYNTAX | An unspecified syntax error occurred in the scriptlet.

Expand image See Also

Concepts

IActiveScriptParse


IActiveScriptParse::InitNew

Microsoft Windows Script Interfaces
IActiveScriptParse::InitNew
See Also
CollapseAll image DropDown image

Initializes the scripting engine.

HRESULT InitNew(void);

Expand image Return Value

Returns S_OK if successful, or E_FAIL if an error occurred during initialization.

Expand image Remarks

Before the scripting engine can be used, one of the following methods must be called: IPersist*::Load, IPersist*::InitNew, or IActiveScriptParse::InitNew. The semantics of this method are identical to IPersistStreamInit::InitNew, in that this method tells the scripting engine to initialize itself. Note that it is not valid to call both IPersist*::InitNew or IActiveScriptParse::InitNew and IPersist*::Load, nor is it valid to call IPersist*::InitNew, IActiveScriptParse::InitNew, or IPersist*::Load more than once.

Expand image See Also

Concepts

IActiveScriptParse


IActiveScriptParse::ParseScriptText

Microsoft Windows Script Interfaces
IActiveScriptParse::ParseScriptText
See Also
CollapseAll image DropDown image

Parses the given code scriptlet, adding declarations into the namespace and evaluating code as appropriate.

HRESULT ParseScriptText(
    LPCOLESTR pstrCode,              // address of scriptlet text
    LPCOLESTR pstrItemName,          // address of item name
    IUnknown *punkContext,           // address of debugging context
    LPCOLESTR pstrDelimiter,         // address of end-of-scriptlet delimiter
    DWORD_PTR dwSourceContextCookie, // application-defined value for debugging
    ULONG ulStartingLineNumber,      // starting line of the script
    DWORD dwFlags,                   // scriptlet flags
    VARIANT *pvarResult,             // address of buffer for results
    EXCEPINFO *pexcepinfo            // address of buffer for error data
);

Parameters

pstrCode | [in] Address of the scriptlet text to evaluate. The interpretation of this string depends on the scripting language.
pstrItemName | [in] Address of the item name that gives the context in which the scriptlet is to be evaluated. If this parameter is NULL, the code is evaluated in the scripting engine's global context.
punkContext | [in] Address of the context object. This object is reserved for use in a debugging environment, where such a context may be provided by the debugger to represent an active run-time context. If this parameter is NULL, the engine uses pstrItemName to identify the context.
pstrDelimiter | [in] Address of the end-of-scriptlet delimiter. When pstrCode is parsed from a stream of text, the host typically uses a delimiter, such as two single quotation marks (''), to detect the end of the scriptlet. This parameter specifies the delimiter that the host used, allowing the scripting engine to provide some conditional primitive preprocessing (for example, replacing a single quotation mark ['] with two single quotation marks for use as a delimiter). Exactly how (and if) the scripting engine makes use of this information depends on the scripting engine. Set this parameter to NULL if the host did not use a delimiter to mark the end of the scriptlet.
dwSourceContextCookie | [in] Application-defined value that is used for debugging purposes.
ulStartingLineNumber | [in] Zero-based value that specifies which line the parsing will begin at.
dwFlags | [in] Flags associated with the scriptlet. Can be a combination of these values:
Value | Meaning
SCRIPTTEXT_ISEXPRESSION | If the distinction between a computational expression and a statement is important but syntactically ambiguous in the script language, this flag specifies that the scriptlet is to be interpreted as an expression, rather than as a statement or list of statements. By default, statements are assumed unless the correct choice can be determined from the syntax of the scriptlet text.
SCRIPTTEXT_ISPERSISTENT | Indicates that the code added during this call should be saved if the scripting engine is saved (for example, through a call to IPersist*::Save), or if the scripting engine is reset by way of a transition back to the initialized state.
SCRIPTTEXT_ISVISIBLE | Indicates that the script text should be visible (and, therefore, callable by name) as a global method in the name space of the script.
pvarResult | [out] Address of a buffer that receives the results of scriptlet processing, or NULL if the caller expects no result (that is, the SCRIPTTEXT_ISEXPRESSION value is not set).
pexcepinfo | [out] Address of a structure that receives exception information. This structure is filled if IActiveScriptParse::ParseScriptText returns DISP_E_EXCEPTION.

Expand image Return Value

Returns one of the following values:

Return Value | Meaning
S_OK | Success.
DISP_E_EXCEPTION | An exception occurred in the processing of the scriptlet. The pexcepinfo parameter contains information about the exception.
E_INVALIDARG | An argument was invalid.
E_POINTER | An invalid pointer was specified.
E_NOTIMPL | This method is not supported. The scripting engine does not support run-time evaluation of expressions or statements.
E_UNEXPECTED | The call was not expected (for example, the scripting engine is in the uninitialized or closed state, or the SCRIPTTEXT_ISEXPRESSION flag was set and the scripting engine is in the initialized state).
OLESCRIPT_E_SYNTAX | An unspecified syntax error occurred in the scriptlet.

Expand image Remarks

If the scripting engine is in the initialized state, no code will actually be evaluated during this call; rather, such code is queued and executed when the scripting engine is transitioned into (or through) the started state. Because execution is not allowed in the initialized state, it is an error to call this method with the SCRIPTTEXT_ISEXPRESSION flag when in the initialized state.

The scriptlet can be an expression, a list of statements, or anything allowed by the script language. For example, this method is used in the evaluation of the HTML <SCRIPT> tag, which allows statements to be executed as the HTML page is being constructed, rather than just compiling them into the script state.

The code passed to this method must be a valid, complete portion of code. For example, in VBScript it is illegal to call this method once with Sub Function(x) and then a second time with End Sub. The parser must not wait for the second call to complete the subroutine, but rather must generate a parse error because a subroutine declaration was started but not completed.

For more information about script states, see the Script Engine States section of Windows Script Engines.

Expand image See Also

Concepts

IActiveScriptParse


IActiveScriptParseProcedure

Microsoft Windows Script Interfaces
IActiveScriptParseProcedure
See Also
DropDown image

If the Windows Script engine allows the source code text for procedures to be added to the script, it implements the IActiveScriptParseProcedure interface. For interpreted scripting languages that have no independent authoring environment, such as VBScript, this provides an alternate mechanism (other than IActiveScriptParse or IPersist*) to add script procedures to the namespace.

Methods in Vtable Order

Method | Description
IActiveScriptParseProcedure::ParseProcedureText | Parses the given code procedure and adds the procedure to the namespace.

See Also

Other Resources

Active Script Interfaces


IActiveScriptParseProcedure::ParseProcedureText

Microsoft Windows Script Interfaces
IActiveScriptParseProcedure::ParseProcedureText
See Also
CollapseAll image DropDown image

Parses the given code procedure and adds the procedure to the name space.

HRESULT ParseProcedureText(
    LPCOLESTR pstrCode,              // address of procedure text
    LPCOLESTR pstrFormalParams,      // address of formal parameter names
    LPCOLESTR pstrProcedureName,     // address of procedure name
    LPCOLESTR pstrItemName,          // address of item name
    IUnknown *punkContext,           // address of debugging context
    LPCOLESTR pstrDelimiter,         // address of end-of-procedure delimiter
    DWORD_PTR dwSourceContextCookie, // application-defined value for debugging
    ULONG ulStartingLineNumber,      // starting line of the script
    DWORD dwFlags,                   // procedure flags
    IDispatch **ppdisp               // receives IDispatch pointer
);

Parameters

pstrCode

[in] Address of the procedure text to evaluate. The interpretation of this string depends on the scripting language.

pstrFormalParams

[in] Address of formal parameter names for the procedure. The parameter names must be separated with the appropriate delimiters for the scripting engine. The names should not be enclosed in parentheses.

pstrProcedureName

[in] Address of procedure name to be parsed.

pstrItemName

[in] Address of the item name that gives the context in which the procedure is to be evaluated. If this parameter is NULL, the code is evaluated in the scripting engine's global context.

punkContext

[in] Address of the context object. This object is reserved for use in a debugging environment, where such a context may be provided by the debugger to represent an active run-time context. If this parameter is NULL, the engine uses pstrItemName to identify the context.

pstrDelimiter

[in] Address of the end-of-procedure delimiter. When pstrCode is parsed from a stream of text, the host typically uses a delimiter, such as two single quotation marks (''), to detect the end of the procedure. This parameter specifies the delimiter that the host used, allowing the scripting engine to provide some conditional primitive preprocessing (for example, replacing a single quotation mark ['] with two single quotation marks for use as a delimiter). Exactly how (and if) the scripting engine makes use of this information depends on the scripting engine. Set this parameter to NULL if the host did not use a delimiter to mark the end of the procedure.

dwSourceContextCookie

[in] Application-defined value that is used for debugging purposes.

ulStartingLineNumber

[in] Zero-based value that specifies which line the parsing will begin at.

dwFlags

[in] Flags associated with the procedure. Can be a combination of these values:

Value | Meaning
SCRIPTPROC_ISEXPRESSION | Indicates that the code in pstrCode is an expression that represents the return value of the procedure. By default, the code can contain an expression, a list of statements, or anything else allowed in a procedure by the script language.
SCRIPTPROC_IMPLICIT_THIS | Indicates that the this pointer is included in the scope of the procedure.
SCRIPTPROC_IMPLICIT_PARENTS | Indicates that the parents of the this pointer are included in the scope of the procedure.
ppdisp

[out] Address of the pointer for the object containing the script's global methods and properties. If the scripting engine does not support such an object, NULL is returned.

Expand image Return Value

Returns one of the following values:

Return Value | Meaning
S_OK | Success.
E_INVALIDARG | An argument was invalid.
E_POINTER | An invalid pointer was specified.
E_NOTIMPL | This method is not supported. The scripting engine does not support run-time addition of procedures to the name space.
E_UNEXPECTED | The call was not expected (for example, the scripting engine is in the uninitialized or closed state).
OLESCRIPT_E_SYNTAX | An unspecified syntax error occurred in the procedure.
S_FALSE | The scripting engine does not support a dispatch object; the ppdisp parameter is set to NULL.

Expand image Remarks

No script code is evaluated during this call; rather, the procedure is compiled into the script state where it can be called by the script later.

Expand image See Also

Concepts

IActiveScriptParseProcedure


IActiveScriptParseProcedureOld Interface

Microsoft Windows Script Interfaces
IActiveScriptParseProcedureOld Interface
See Also
CollapseAll image DropDown image

Allows the source code text for procedures to be added to the script. For interpreted scripting languages that do not have an independent authoring environment, such as VBScript, this provides an alternative mechanism (other than IActiveScriptParse or IPersist*) to add script procedures to the name space.

Note Note

This interface is deprecated in favor of the IActiveScriptParseProcedure interface.

Expand image Methods

In addition to the methods inherited from IUnknown, the IActiveScriptParseProcedureOld interface exposes the following methods.

Method | Description
IActiveScriptParseProcedureOld::ParseProcedureText | Parses the given code procedure and adds the procedure to the name space.

Expand image See Also

Concepts

IActiveScriptParseProcedure


IActiveScriptParseProcedureOld::ParseProcedureText

Microsoft Windows Script Interfaces
IActiveScriptParseProcedureOld::ParseProcedureText
See Also
CollapseAll image DropDown image

Parses the given code procedure and adds an anonymous procedure to the name space.

HRESULT ParseProcedureText(
   LPCOLESTR    pstrCode,
   LPCOLESTR    pstrFormalParams,
   LPCOLESTR    pstrItemName,
   IUnknown*    punkContext,
   LPCOLESTR    pstrDelimiter,
   DWORD_PTR    dwSourceContextCookie,
   ULONG        ulStartingLineNumber,
   DWORD        dwFlags,
   IDispatch**  ppdisp
);

Parameters

pstrCode

[in] The procedure text to evaluate. The interpretation of this string depends on the scripting language.

pstrFormalParams

[in] Formal parameter names for the procedure. The parameter names must be separated with the appropriate delimiters for the scripting engine. The names should not be enclosed in parentheses.

pstrItemName

[in] The name of the named item that gives the context in which the procedure is to be evaluated. If this parameter is NULL, the code is evaluated in the scripting engine's global context.

punkContext

[in] The context object. This object is reserved for use in a debugging environment, where such a context may be provided by the debugger to represent an active run-time context. If this parameter is NULL, the engine uses pstrItemName to identify the context.

pstrDelimiter

[in] The end-of-procedure delimiter. When pstrCode is parsed from a stream of text, the host typically uses a delimiter, such as two single quotation marks (''), to detect the end of the procedure. This parameter specifies the delimiter that the host used, allowing the scripting engine to provide some conditional, primitive preprocessing (for example, replacing a single quotation mark ['] with two single quotation marks for use as a delimiter). Exactly how (and if) the scripting engine uses this information depends on the scripting engine. Set this parameter to NULL if the host did not use a delimiter to mark the end of the procedure.

dwSourceContextCookie

[in] Application-defined value that is used for debugging purposes.

ulStartingLineNumber

[in] Zero-based value that specifies at which line the parsing will begin.

dwFlags

[in] Flags associated with the procedure. Can be a combination of these values.

Constant Value Meaning

SCRIPTPROC_ISEXPRESSION

0x00000020

Indicates that the code in pstrCode is an expression that represents the return value of the procedure.

SCRIPTPROC_IMPLICIT_THIS

0x00000100

Indicates that the this pointer is included in the scope of the procedure.

SCRIPTPROC_IMPLICIT_PARENTS

0x00000200

Indicates that the parents of the this pointer are included in the scope of the procedure.
ppdisp

[out] Returns a dispatch wrapper where the default method is the procedure parsed by this method.

Expand image Return Value

The method returns an HRESULT. Possible values include, but are not limited to, those in the following table.

Value | Description
S_OK | The method succeeded.
E_INVALIDARG | An argument was invalid.
E_POINTER | An invalid pointer was specified.
E_NOTIMPL | This method is not supported. The scripting engine does not support run-time addition of procedures to the name space.
E_UNEXPECTED | The call was not expected (for example, the scripting engine is in the uninitialized or closed state).
OLESCRIPT_E_SYNTAX | An unspecified syntax error occurred in the procedure.
S_FALSE | The scripting engine does not support a dispatch object; the ppdisp parameter is set to NULL.

Expand image Remarks

No script code is evaluated during this call; rather, the procedure is compiled into a method on ppdisp where it can be called by the script later.

This interface is deprecated in favor of the IActiveScriptParseProcedure interface. The IActiveScriptParseProcedure::ParseProcedureText method is similar to this method, but it allows the procedure name to be specified. In all circumstances, IActiveScriptParseProcedure::ParseProcedureText should be used.

Expand image See Also

Reference

IActiveScriptParseProcedureOld Interface
IActiveScriptParseProcedure::ParseProcedureText


IActiveScriptSite

Microsoft Windows Script Interfaces
IActiveScriptSite
See Also
DropDown image

Implemented by the host to create a site for the Windows Script engine. Usually, this site will be associated with the container of all the objects that are visible to the script (for example, the ActiveX Controls). Typically, this container will correspond to the document or page being viewed. Microsoft Internet Explorer, for example, would create such a container for each HTML page being displayed. Each ActiveX control (or other automation object) on the page, and the scripting engine itself, would be enumerable within this container.

Methods in Vtable Order

Method | Description
IActiveScriptSite::GetLCID | Retrieves the locale identifier that the host uses for displaying user-interface elements.
IActiveScriptSite::GetItemInfo | Obtains information about an item that was added to an engine through a call to the IActiveScript::AddNamedItem method.
IActiveScriptSite::GetDocVersionString | Retrieves a host-defined string that uniquely identifies the current document version from the host's point of view.
IActiveScriptSite::OnScriptTerminate | Called when the script has completed execution.
IActiveScriptSite::OnStateChange | Informs the host that the scripting engine has changed states.
IActiveScriptSite::OnScriptError | Informs the host that an execution error occurred while the engine was running the script.
IActiveScriptSite::OnEnterScript | Informs the host that the scripting engine has begun executing the script code.
IActiveScriptSite::OnLeaveScript | Informs the host that the scripting engine has returned from executing script code.

See Also

Other Resources

Active Script Interfaces


IActiveScriptSite::GetDocVersionString

Microsoft Windows Script Interfaces
IActiveScriptSite::GetDocVersionString
See Also
CollapseAll image DropDown image

Retrieves a host-defined string that uniquely identifies the current document version. If the related document has changed outside the scope of Windows Script (as in the case of an HTML page being edited with Notepad), the scripting engine can save this along with its persisted state, forcing a recompile the next time the script is loaded.

HRESULT GetDocVersionString(
    BSTR *pbstrVersionString  // address of document version string
);

Parameters

pstrVersionString

[out] Address of the host-defined document version string.

Expand image Return Value

Returns S_OK if successful, or E_NOTIMPL if this method is not supported.

Expand image Remarks

If E_NOTIMPL is returned, the scripting engine should assume that the script is in sync with the document.

Expand image See Also

Concepts

IActiveScriptSite


IActiveScriptSite::GetItemInfo

Microsoft Windows Script Interfaces
IActiveScriptSite::GetItemInfo
See Also
CollapseAll image DropDown image

Allows the scripting engine to obtain information about an item added with the IActiveScript::AddNamedItem method.

HRESULT GetItemInfo(
    LPCOLESTR pstrName,     // address of item name
    DWORD dwReturnMask,     // bit mask for information retrieval
    IUnknown **ppunkItem,   // address of pointer to item's IUnknown
    ITypeInfo **ppTypeInfo  // address of pointer to item's ITypeInfo
);

Parameters

pstrName

[in] The name associated with the item, as specified in the IActiveScript::AddNamedItem method.

dwReturnMask

[in] A bit mask specifying what information about the item should be returned. The scripting engine should request the minimum amount of information possible because some of the return parameters (for example, ITypeInfo) can take considerable time to load or generate. Can be a combination of the following values:

Value | Meaning
SCRIPTINFO_IUNKNOWN | Returns the IUnknown interface for this item.
SCRIPTINFO_ITYPEINFO | Returns the ITypeInfo interface for this item.
ppunkItem

[out] Address of a variable that receives a pointer to the IUnknown interface associated with the given item. The scripting engine can use the IUnknown::QueryInterface method to obtain the IDispatch interface for the item. This parameter receives NULL if dwReturnMask does not include the SCRIPTINFO_IUNKNOWN value. Also, it receives NULL if there is no object associated with the item name; this mechanism is used to create a simple class when the named item was added with the SCRIPTITEM_CODEONLY flag set in the IActiveScript::AddNamedItem method.

ppTypeInfo

[out] Address of a variable that receives a pointer to the ITypeInfo interface associated with the item. This parameter receives NULL if dwReturnMask does not include the SCRIPTINFO_ITYPEINFO value, or if type information is not available for this item. If type information is not available, the object cannot source events, and name binding must be realized with the IDispatch::GetIDsOfNames method. Note that the ITypeInfo interface retrieved describes the item's coclass (TKIND_COCLASS) because the object may support multiple interfaces and event interfaces. If the item supports the IProvideMultipleTypeInfo interface, the ITypeInfo interface retrieved is the same as the index zero ITypeInfo that would be obtained using the IProvideMultipleTypeInfo::GetInfoOfIndex method.

Expand image Return Value

Returns one of the following values:

Return Value | Meaning
S_OK | Success.
E_INVALIDARG | An argument was invalid.
E_POINTER | An invalid pointer was specified.
TYPE_E_ELEMENTNOTFOUND | An item of the specified name was not found.

Expand image Remarks

This method retrieves only the information indicated by the dwReturnMask parameter; this improves performance. For example, if an ITypeInfo interface is not needed for an item, it is simply not specified in dwReturnMask.

Expand image See Also

Concepts

IActiveScriptSite


IActiveScriptSite::GetLCID

Microsoft Windows Script Interfaces
IActiveScriptSite::GetLCID
See Also
CollapseAll image DropDown image

Retrieves the locale identifier associated with the host's user interface. The scripting engine uses the identifier to ensure that error strings and other user-interface elements generated by the engine appear in the appropriate language.

HRESULT GetLCID(
    LCID *plcid  // address of variable for language identifier
);

Parameters

plcid

[out] Address of a variable that receives the locale identifier for user-interface elements displayed by the scripting engine.

Expand image Return Value

Returns one of the following values:

Return Value | Meaning
S_OK | Success.
E_NOTIMPL | This method is not implemented. Use the system-defined locale.
E_POINTER | An invalid pointer was specified.

Expand image Remarks

If this method returns E_NOTIMPL, the system-defined locale identifier should be used.

Expand image See Also

Concepts

IActiveScriptSite


IActiveScriptSite::OnEnterScript

Microsoft Windows Script Interfaces
IActiveScriptSite::OnEnterScript
See Also
CollapseAll image DropDown image

Informs the host that the scripting engine has begun executing the script code.

HRESULT OnEnterScript(void);

Expand image Return Value

Returns S_OK if successful.

Expand image Remarks

The scripting engine must call this method on every entry or reentry into the scripting engine. For example, if the script calls an object that then fires an event handled by the scripting engine, the scripting engine must call IActiveScriptSite::OnEnterScript before executing the event, and must call the IActiveScriptSite::OnLeaveScript method after executing the event but before returning to the object that fired the event. Calls to this method can be nested. Every call to this method requires a corresponding call to IActiveScriptSite::OnLeaveScript.

Expand image See Also

Concepts

IActiveScriptSite


IActiveScriptSite::OnLeaveScript

Microsoft Windows Script Interfaces
IActiveScriptSite::OnLeaveScript
See Also
CollapseAll image DropDown image

Informs the host that the scripting engine has returned from executing script code.

HRESULT OnLeaveScript(void);

Expand image Return Value

Returns S_OK if successful.

Expand image Remarks

The scripting engine must call this method before returning control to a calling application that entered the scripting engine. For example, if the script calls an object that then fires an event handled by the scripting engine, the scripting engine must call the IActiveScriptSite::OnEnterScript method before executing the event, and must call IActiveScriptSite::OnLeaveScript after executing the event before returning to the object that fired the event. Calls to this method can be nested. Every call to IActiveScriptSite::OnEnterScript requires a corresponding call to this method.

Expand image See Also

Concepts

IActiveScriptSite


IActiveScriptSite::OnScriptError

Microsoft Windows Script Interfaces
IActiveScriptSite::OnScriptError
See Also
CollapseAll image DropDown image

Informs the host that an execution error occurred while the engine was running the script.

HRESULT OnScriptError(
    IActiveScriptError *pase  // address of error interface
);

Parameters

pase

[in] Address of the error object's IActiveScriptError interface. A host can use this interface to obtain information about the execution error.

Expand image Return Value

Returns S_OK if the error was correctly handled, or an OLE defined error code otherwise.

Expand image See Also

Concepts

IActiveScriptSite


IActiveScriptSite::OnScriptTerminate

Microsoft Windows Script Interfaces
IActiveScriptSite::OnScriptTerminate
See Also
CollapseAll image DropDown image

Informs the host that the script has completed execution.

HRESULT OnScriptTerminate(
    VARIANT *pvarResult,   // address of script results
    EXCEPINFO *pexcepinfo  // address of structure with exception information
);

Parameters

pvarResult

[in] Address of a variable that contains the script result, or NULL if the script produced no result.

pexcepinfo

[in] Address of an EXCEPINFO structure that contains exception information generated when the script terminated, or NULL if no exception was generated.

Expand image Return Value

Returns S_OK if successful.

Expand image Remarks

The scripting engine calls this method before the call to the IActiveScriptSite::OnStateChange method, with the SCRIPTSTATE_INITIALIZED flag set, is completed. This method can be used to return completion status and results to the host. Note that many script languages, which are based on sinking events from the host, have life spans that are defined by the host. In this case, this method may never be called.

Expand image See Also

Concepts

IActiveScriptSite


IActiveScriptSite::OnStateChange

Microsoft Windows Script Interfaces
IActiveScriptSite::OnStateChange
See Also
CollapseAll image DropDown image

Informs the host that the scripting engine has changed states.

HRESULT OnStateChange(
    SCRIPTSTATE ssScriptState  // new state of engine
);

Parameters

ssScriptState

[in] Value that indicates the new script state. See the IActiveScript::GetScriptState method for a description of the states.

Expand image Return Value

Returns S_OK if successful.

Expand image See Also

Concepts

IActiveScriptSite


IActiveScriptSiteInterruptPoll Interface

Microsoft Windows Script Interfaces
IActiveScriptSiteInterruptPoll Interface
CollapseAll image DropDown image

The IActiveScriptSiteInterruptPoll interface allows a host to specify that a script should terminate.

Expand image Methods

In addition to the methods inherited from IUnknown, the IActiveScriptSiteInterruptPoll interface exposes the following method.

Method | Description
IActiveScriptSiteInterruptPoll::QueryContinue | Allows a host to specify that a script should terminate.


IActiveScriptSiteInterruptPoll::QueryContinue

Microsoft Windows Script Interfaces
IActiveScriptSiteInterruptPoll::QueryContinue
See Also
CollapseAll image DropDown image

Allows a host to specify that a script should terminate.

HRESULT QueryContinue();

Parameters

This method takes no parameters.

Expand image Return Value

The method returns an HRESULT. Possible values include, but are not limited to, those in the following table.

Value | Description
S_OK | The call succeeded and the host permits the script to continue running.
S_FALSE | The call succeeded and the host requests that the script terminate.

Expand image Remarks

The hosted script should terminate unless the return value of the QueryContinue method is S_OK. A return value of S_FALSE indicates that the host explicitly requests that the script terminate.

A multithreaded host may use the IActiveScript::InterruptScriptThread method to terminate a script.

Expand image See Also

Reference

IActiveScriptSiteInterruptPoll Interface
IActiveScript::InterruptScriptThread


IActiveScriptSiteWindow

Microsoft Windows Script Interfaces
IActiveScriptSiteWindow
See Also
DropDown image

This interface is implemented by hosts that support a user interface on the same object as IActiveScriptSite . Hosts that do not support a user interface, such as servers, would not implement the IActiveScriptSiteWindow interface. The scripting engine accesses this interface by calling QueryInterface from IActiveScriptSite.

Methods in Vtable Order

Method | Description
IActiveScriptSiteWindow::GetWindow | Retrieves the window handle that can act as the owner of a pop-up window that the scripting engine must display.
IActiveScriptSiteWindow::EnableModeless | Causes the host to enable or disable its main window as well as any modeless dialog boxes.

See Also

Other Resources

Active Script Interfaces


IActiveScriptSiteWindow::EnableModeless

Microsoft Windows Script Interfaces
IActiveScriptSiteWindow::EnableModeless
See Also
CollapseAll image DropDown image

Causes the host to enable or disable its main window as well as any modeless dialog boxes.

HRESULT EnableModeless(
    BOOL fEnable  // enable flag
);

Parameters

fEnable

[in] Flag that, if TRUE, enables the main window and modeless dialogs or, if FALSE, disables them.

Expand image Return Value

Returns S_OK if successful, or E_FAIL if an error occurred.

Expand image Remarks

This method is identical to the IOleInPlaceFrame::EnableModeless method.

Calls to this method can be nested.

Expand image See Also

Concepts

IActiveScriptSiteWindow


IActiveScriptSiteWindow::GetWindow

Microsoft Windows Script Interfaces
IActiveScriptSiteWindow::GetWindow
See Also
CollapseAll image DropDown image

Retrieves the handle to a window that can act as the owner of a pop-up window that the scripting engine must display.

HRESULT GetWindow(
    HWND *phwnd  // address of variable for window handle
);

Parameters

phwnd

[out] Address of a variable that receives the window handle.

Expand image Return Value

Returns S_OK if successful, or E_FAIL if an error occurred.

Expand image Remarks

This method is similar to the IOleWindow::GetWindow method.

Expand image See Also

Concepts

IActiveScriptSiteWindow


IActiveScriptStats Interface

Microsoft Windows Script Interfaces
IActiveScriptStats Interface
DropDown image

Allows a host to query the statistics of a running script. The host can use this information to determine if script has taken too long to complete.

In addition to the methods inherited from IUnknown, the IActiveScriptStats interface exposes the following methods.

Methods in Vtable Order

Method | Description
IActiveScriptStats::GetStat | Returns one of the standard script statistics.
IActiveScriptStats::GetStatEx | Returns a custom script statistic.
IActiveScriptStats::ResetStats | Resets the statistics for this script.


IActiveScriptStats::GetStat

Microsoft Windows Script Interfaces
IActiveScriptStats::GetStat
See Also
CollapseAll image DropDown image

Returns one of the standard script statistics.

HRESULT GetStat(
   DWORD   stid,
   ULONG*  pluHi,
   ULONG*  pluLo
);

Parameters

stid

[in] Specifies which statistic to return. Must be the value:

Constant Value Description

SCRIPTSTAT_STATEMENT_COUNT

1

Return the number of statements executed since the script started or the statistics were reset.
pluHi

[out] The high 32 bits of a 64-bit unsigned integer representing the statistic.

pluLo

[out] The low 32 bits of a 64-bit unsigned integer representing the statistic.

Expand image Return Value

The method returns an HRESULT. Possible values include, but are not limited to the values in the following table.

Value | Description
S_OK | The method succeeded.

Expand image Remarks

This method returns one of the standard script statistics.

Expand image See Also

Reference

IActiveScriptStats::GetStatEx

Concepts

IActiveScriptStats Interface


IActiveScriptStats::GetStatEx

Microsoft Windows Script Interfaces
IActiveScriptStats::GetStatEx
See Also
CollapseAll image DropDown image

Returns a custom script statistic.

HRESULT GetStatEx(
   REFGUID  guid,
   ULONG*   pluHi,
   ULONG*   pluLo
);

Parameters

guid

[in] Specifies which statistic to return. The semantics of which statistic corresponds to a particular GUID is entirely engine defined.

pluHi

[out] The high 32 bits of a 64-bit unsigned integer representing the statistic.

pluLo

[out] The low 32 bits of a 64-bit unsigned integer representing the statistic.

Expand image Return Value

The method returns an HRESULT. Possible values include, but are not limited to, those in the following table.

Value | Description
S_OK | The method succeeded.
E_NOTIMPL | The method is not implemented.

Expand image Remarks

This method allows a custom script engine to return statistics meaningful to a custom host.

Note Note

This method is not currently implemented.

Expand image See Also

Reference

IActiveScriptStats::GetStat

Concepts

IActiveScriptStats Interface


IActiveScriptStats::ResetStats

Microsoft Windows Script Interfaces
IActiveScriptStats::ResetStats
See Also
CollapseAll image DropDown image

Resets the statistics for this script.

HRESULT ResetStats();

Parameters

This method takes no parameters.

Expand image Return Value

The method returns an HRESULT. Possible values include, but are not limited to, those in the following table.

Value | Description
S_OK | The method succeeded.

Expand image Remarks

This method resets the statistics for this script.

Expand image See Also

Concepts

IActiveScriptStats Interface


IBindEventHandler Interface

Microsoft Windows Script Interfaces
IBindEventHandler Interface
DropDown image

Enables the caller to provide an object that handles a specified event handler.

Methods

In addition to the methods inherited from IUnknown, the IBindEventHandler interface exposes the following methods.

Method | Description
IBindEventHandler::BindHandler | Binds an event to an object.


IBindEventHandler::BindHandler

Microsoft Windows Script Interfaces
IBindEventHandler::BindHandler
See Also
CollapseAll image DropDown image

Binds an event to an object.

HRESULT BindHandler(
   LPCOLESTR   pstrEvent,
   IDispatch*  pdisp
);

Parameters

pstrEvent

[in] Specifies the event to handle.

pdisp

[in] Specifies the object to handle the event.

Expand image Return Value

The method returns an HRESULT. Possible values include, but are not limited to, those in the following table.

Value | Description
S_OK | The method succeeded.

Expand image Remarks

This method binds an event to an object.

Expand image See Also

Concepts

IBindEventHandler Interface


Debug Property Interfaces

Microsoft Windows Script Interfaces
Debug Property Interfaces
DropDown image

The DbgProp.h header file provides the interfaces listed in this section.

In This Section

The following interfaces, structures, and enumerations describe the hierarchical properties of the application being debugged:

  • IDebugProperty Interface

  • IDebugExtendedProperty Interface

  • IEnumDebugPropertyInfo Interface

  • IEnumDebugExtendedPropertyInfo Interface

  • IPerPropertyBrowsing2 Interface

  • IDebugPropertyEnumType_All Interface

  • DebugPropertyInfo Structure

  • ExtendedDebugPropertyInfo Structure

  • DBGPROP_ATTRIB_FLAGS

  • DBGPROP_INFO_FLAGS

  • EX_DBGPROP_INFO_FLAGS


DBGPROP_ATTRIB_FLAGS

Microsoft Windows Script Interfaces
DBGPROP_ATTRIB_FLAGS
See Also
CollapseAll image DropDown image

Describes various attributes for an IDebugProperty. Member of the DebugPropertyInfo structure.

enum {
DBGPROP_ATTRIB_NO_ATTRIB  =0x00000000,
   DBGPROP_ATTRIB_VALUE_IS_INVALID  =0x00000008,
   DBGPROP_ATTRIB_VALUE_IS_EXPANDABLE  =0x00000010,
   DBGPROP_ATTRIB_VALUE_READONLY  =0x00000800,
   DBGPROP_ATTRIB_ACCESS_PUBLIC  =0x00001000,
   DBGPROP_ATTRIB_ACCESS_PRIVATE  =0x00002000,
   DBGPROP_ATTRIB_ACCESS_PROTECTED  =0x00004000,
   DBGPROP_ATTRIB_ACCESS_FINAL  =0x00008000,
   DBGPROP_ATTRIB_STORAGE_GLOBAL  =0x00010000,
   DBGPROP_ATTRIB_STORAGE_STATIC  =0x00020000,
   DBGPROP_ATTRIB_STORAGE_FIELD  =0x00040000,
   DBGPROP_ATTRIB_STORAGE_VIRTUAL  =0x00080000,
   DBGPROP_ATTRIB_TYPE_IS_CONSTANT  =0x00100000,
   DBGPROP_ATTRIB_TYPE_IS_SYNCHRONIZED  =0x00200000,
   DBGPROP_ATTRIB_TYPE_IS_VOLATILE  =0x00400000,
   DBGPROP_ATTRIB_HAS_EXTENDED_ATTRIBS  =0x00800000
};

Expand image Members

DBGPROP_ATTRIB_NO_ATTRIB

Indicates no attributes.

DBGPROP_ATTRIB_VALUE_IS_INVALID

Indicates that the value in DebugPropertyInfo::bstrValue is not valid.

DBGPROP_ATTRIB_VALUE_IS_EXPANDABLE

Indicates that the reference or property has children.

DBGPROP_ATTRIB_VALUE_READONLY

Indicates that the value is read-only.

DBGPROP_ATTRIB_ACCESS_PUBLIC

Indicates an object that has public access.

DBGPROP_ATTRIB_ACCESS_PRIVATE

Indicates an object that has private access.

DBGPROP_ATTRIB_ACCESS_PROTECTED

Indicates an object that has protected access.

DBGPROP_ATTRIB_ACCESS_FINAL

Indicates an object that has final access.

DBGPROP_ATTRIB_STORAGE_GLOBAL

Indicates global storage.

DBGPROP_ATTRIB_STORAGE_STATIC

Indicates static storage.

DBGPROP_ATTRIB_STORAGE_FIELD

Indicates an object that is a property.

DBGPROP_ATTRIB_STORAGE_VIRTUAL

Indicates virtual storage.

DBGPROP_ATTRIB_TYPE_IS_CONSTANT

Indicates that the type of object is constant.

DBGPROP_ATTRIB_TYPE_IS_SYNCHRONIZED

Indicates that this slot is thread synchronized.

DBGPROP_ATTRIB_TYPE_IS_VOLATILE

Indicates that this slot is volatile with respect to persistent storage.

DBGPROP_ATTRIB_HAS_EXTENDED_ATTRIBS

Indicates that this slot has attributes above and beyond these predefined bits.

Expand image Remarks

These flags are also used to filter children of an object. The values may be combined with a bitwise OR.

Expand image See Also

Reference

DebugPropertyInfo Structure

Concepts

IDebugProperty Interface


DBGPROP_INFO_FLAGS

Microsoft Windows Script Interfaces
DBGPROP_INFO_FLAGS
See Also
CollapseAll image DropDown image

Used to specify DebugPropertyInfo fields

enum {
   DBGPROP_INFO_NAME  =0x001,
   DBGPROP_INFO_TYPE  =0x002,
   DBGPROP_INFO_VALUE  =0x004,
   DBGPROP_INFO_FULLNAME  =0x020,
   DBGPROP_INFO_ATTRIBUTES  =0x008,
   DBGPROP_INFO_DEBUGPROP  =0x010,
   DBGPROP_INFO_AUTOEXPAND  =0x8000000
};

Expand image Members

DBGPROP_INFO_NAME

Initializes the bstrName field.

DBGPROP_INFO_TYPE

Initializes the bstrType field.

DBGPROP_INFO_VALUE

Initializes the bstrValue field.

DBGPROP_INFO_FULLNAME

Initializes the bstrFullName field.

DBGPROP_INFO_ATTRIBUTES

Initializes the dwAttrib field.

DBGPROP_INFO_DEBUGPROP

Initializes the pDebugProp field that contains an IDebugProperty interface.

DBGPROP_INFO_AUTOEXPAND

Specifies that the value field should contain the auto-expanded value, if available, for this type of object.

Expand image See Also

Reference

DebugPropertyInfo Structure

Concepts

IDebugProperty Interface


DebugPropertyInfo Structure

Microsoft Windows Script Interfaces
DebugPropertyInfo Structure
See Also
CollapseAll image DropDown image

Describes an object of a hierarchical nature that has name, type, and value. It is used to describe the debug properties of local variables, parameters, watch variables and expressions, and registers.

typedef struct DebugPropertyInfo{
   DBGPROP_INFO_FLAGS  dwValidFields;
   BSTR  bstrName;
   BSTR  bstrType;
   BSTR  bstrValue;
   BSTR  bstrFullName;
   DBGPROP_ATTRIB_FLAGS  dwAttrib;
   IDebugProperty*  pDebugProp;
};

Expand image Members

dwValidFields

An enumerated data type used to specify which fields are initialized.

bstrName

The property name within a context.

bstrType

The property type, as formatted string.

bstrValue

The property value, as formatted string.

bstrFullName

The full name of the property.

dwAttrib

An enumeration that specifies the flags for the debug property attributes.

pDebugProp

The IDebugProperty described by the information in this DebugPropertyInfo structure.

Expand image See Also

Reference

DBGPROP_ATTRIB_FLAGS
DBGPROP_INFO_FLAGS

Concepts

IDebugProperty Interface


EX_DBGPROP_INFO_FLAGS

Microsoft Windows Script Interfaces
EX_DBGPROP_INFO_FLAGS
See Also
CollapseAll image DropDown image

Used to specify ExtendedDebugPropertyInfo fields.

enum {
   EX_DBGPROP_INFO_ID  =0x0100,
   EX_DBGPROP_INFO_NTYPE  =0x0200,
   EX_DBGPROP_INFO_NVALUE  =0x0400,
   EX_DBGPROP_INFO_LOCKBYTES  =0x0800,
   EX_DBGPROP_INFO_DEBUGEXTPROP  =0x1000
};

Expand image Members

EX_DBGPROP_INFO_ID

Initializes identifier for the property.

EX_DBGPROP_INFO_NTYPE

Initializes type of the property.

EX_DBGPROP_INFO_NVALUE

Initializes value of the property.

EX_DBGPROP_INFO_LOCKBYTES

Initializes the plb field.

EX_DBGPROP_INFO_DEBUGEXTPROP

Initializes the pDebugExtProp field that contains an IDebugExtendedProperty interface.

Expand image See Also

Reference

ExtendedDebugPropertyInfo Structure

Concepts

IDebugExtendedProperty Interface


ExtendedDebugPropertyInfo Structure

Microsoft Windows Script Interfaces
ExtendedDebugPropertyInfo Structure
See Also
CollapseAll image DropDown image

Extends the DebugPropertyInfo structure with additional members to characterize the extended property.

typedef struct ExtendedDebugPropertyInfo{
   DBGPROP_INFO_FLAGS  dwValidFields;
   LPOLESTR  bstrName;
   LPOLESTR  bstrType;
   LPOLESTR  bstrValue;
   LPOLESTR  bstrFullName;
   DBGPROP_ATTRIB_FLAGS  dwAttrib;
   IDebugProperty*  pDebugProp;
   DWORD  nDISPID;
   DWORD  nType;
   VARIANT  varValue;
   ILockBytes*  plbValue;
   IDebugExtendedProperty*  pDebugExtProp;
};

Expand image Members

dwValidFields

An enumerated data type used to specify which fields are initialized.

bstrName

The property name within a context.

bstrType

The property type as formatted string.

bstrValue

The property value as a formatted string.

bstrFullName

The full name of the property.

dwAttrib

An enumeration that specifies the flags for the debug property attributes.

pDebugProp

IDebugProperty object corresponding to this ExtendedDebugPropertyInfo.

nDISPID

The dispatch id.

nType

The extended property type.

varValue

The extended property value if it can fit in VARIANT.

plbValue

The actual data bytes of the property value.

pDebugExtProp

IDebugExtendedProperty object corresponding to this ExtendedDebugPropertyInfo.

Expand image See Also

Reference

DebugPropertyInfo Structure
DBGPROP_ATTRIB_FLAGS
DBGPROP_INFO_FLAGS

Concepts

IDebugProperty Interface
IDebugExtendedProperty Interface


IDebugExtendedProperty Interface

Microsoft Windows Script Interfaces
IDebugExtendedProperty Interface
See Also
DropDown image

Extends IDebugProperty interface.

Methods in Vtable Order

In addition to the methods inherited from IDebugProperty, this interface exposes the following methods.

Method | Description
IDebugExtendedProperty::GetExtendedPropertyInfo | Gets the ExtendedDebugPropertyInfo that describes this IDebugExtendedProperty.
IDebugExtendedProperty::EnumExtendedMembers | Enumerates the members of an extended property.

Requirements

Header: dbgprop.h

See Also

Concepts

IDebugProperty Interface


IDebugExtendedProperty::EnumExtendedMembers

Microsoft Windows Script Interfaces
IDebugExtendedProperty::EnumExtendedMembers
See Also
CollapseAll image DropDown image

Enumerates the members of an extended property.

HRESULT EnumExtendedMembers(
   EX_DBGPROP_INFO_FLAGS  dwFieldSpec,
   UINT  nRadix,
   IEnumDebugExtendedPropertyInfo**  ppeepi
);

Parameters

dwFieldSpec

[in] Specifies the EX_DBGPROP_INFO_FLAGS constants that determine the fields in the enumerated extended debug property structures that are to be filled in.

nRadix

[in] Radix to be used in interpreting any numerical information.

ppeepi

[out] Returns the IEnumDebugExtendedPropertyInfo interface that enumerates the member properties.

Expand image Return Value

Returns a valid HRESULT, typically S_OK.

Expand image See Also

Reference

EX_DBGPROP_INFO_FLAGS
ExtendedDebugPropertyInfo Structure

Concepts

IDebugExtendedProperty Interface


IDebugExtendedProperty::GetExtendedPropertyInfo

Microsoft Windows Script Interfaces
IDebugExtendedProperty::GetExtendedPropertyInfo
See Also
CollapseAll image DropDown image

Fetches extended information for an extended property, which is more information than the simpler IDebugProperty.

HRESULT GetExtendedPropertyInfo(
   EX_DBGPROP_INFO_FLAGS  dwFieldSpec,
   UINT  nRadix,
   ExtendedDebugPropertyInfo*  pExtendedPropertyInfo
);

Parameters

dwFieldSpec

[in] Specifies the EX_DBGPROP_INFO_FLAGS constants that determine the fields to be filled out in the ExtendedDebugPropertyInfo structure.

nRadix

[in] Radix to be used in interpreting any numerical information.

pExtendedPropertyInfo

[out] Returns the ExtendedDebugPropertyInfo structure that describes the property.

Expand image Return Value

Returns a valid HRESULT, typically S_OK.

Expand image See Also

Reference

EX_DBGPROP_INFO_FLAGS
ExtendedDebugPropertyInfo Structure

Concepts

IDebugExtendedProperty Interface


IDebugProperty Interface

Microsoft Windows Script Interfaces
IDebugProperty Interface
DropDown image

Used to describe any hierarchical property of the entity being debugged that has a name, type, and value. Most commonly, IDebugProperty is used to describe the result of expression evaluation, statement evaluation, or register evaluation.

Methods in Vtable Order

The following table shows the methods of the IDebugProperty Interface.

Method | Description
IDebugProperty::GetPropertyInfo | Get the DebugPropertyInfo that describes this IDebugProperty.
IDebugProperty::GetExtendedInfo | Gets the extended information on a property.
IDebugProperty::SetValueAsString | Sets the value of a property from a string.
IDebugProperty::EnumMembers | Enumerates the members of a property.
IDebugProperty::GetParent | Gets the parent of a property.

Requirements

Header: dbgprop.h


IDebugProperty::EnumMembers

Microsoft Windows Script Interfaces
IDebugProperty::EnumMembers
See Also
CollapseAll image DropDown image

Enumerates the members of a property.

HRESULT EnumMembers (
   DBGPROP_INFO_FLAGS dwFieldSpec,
   UINT nRadix,
   REFIID refiid,
   IEnumDebugPropertyInfo** ppEnum
);

Parameters

dwFieldSpec

[in] Specifies the DBGPROP_INFO_FLAGS constants that determine which fields in the enumerated debug property structures are to be filled in.

nRadix

[in] Radix to be used in interpreting any numerical information.

refiid

[in] This IID is passed for filtering the enumerator. The IID is one of the IDebugPropertyEnumType interfaces that inherit from IDebugPropertyEnumType_All.

ppEnum

[out] Returns the IEnumDebugPropertyInfo interface that enumerates the member properties.

Expand image Return Value

Returns a valid HRESULT, typically S_OK.

Expand image See Also

Reference

DBGPROP_INFO_FLAGS
IDebugPropertyEnumType_All Interface

Concepts

IDebugProperty Interface
IEnumDebugPropertyInfo Interface


IDebugProperty::GetExtendedInfo

Microsoft Windows Script Interfaces
IDebugProperty::GetExtendedInfo
See Also
CollapseAll image DropDown image

Gets extended information for the property.

HRESULT GetExtendedInfo (
   ULONG  cInfos,
   GUID*  rgguidExtendedInfo,
   VARIANT* pExtendedInfo
);

Parameters

cInfos

[in] Count of extended information objects.

rgguidExtendedInfo

[in] An array of GUIDs is passed so that multiple items of extended info can be retrieved at the same time.

pExtendedInfo

[out] Returns an array of VARIANTs that can be used to retrieve the extended property information.

Expand image Return Value

Returns a valid HRESULT, typically S_OK.

Expand image Remarks

This interface gets extended info for this object. The API exists only for the purpose of retrieving info that does not lend itself to being retrieved by the use of IDebugProperty::GetPropertyInfo).

Expand image See Also

Concepts

IDebugProperty Interface


IDebugProperty::GetParent

Microsoft Windows Script Interfaces
IDebugProperty::GetParent
See Also
CollapseAll image DropDown image

Gets the parent property of a property.

HRESULT GetParent (
   IDebugProperty** ppParent
);

Parameters

ppParent

[out] Returns the IDebugProperty interface that represents the parent of the property.

Expand image Return Value

Returns a valid HRESULT, typically S_OK.

Expand image See Also

Concepts

IDebugProperty Interface


IDebugProperty::GetPropertyInfo

Microsoft Windows Script Interfaces
IDebugProperty::GetPropertyInfo
See Also
CollapseAll image DropDown image

Gets the value of an IDebugProperty that describes a method or an indexed property.

HRESULT GetPropertyInfo (
   DBGPROP_INFO_FLAGS dwFields,
   UINT nRadix,
   DebugPropertyInfo* pPropertyInfo
);

Parameters

dwFields

[in] Specifies the DBGPROP_INFO_FLAGS constants that determine the fields to be filled out in the DebugPropertyInfo structure.

nRadix

[in] Radix to be used in formatting any numerical information.

pPropertyInfo

[out] Returns the DebugPropertyInfo structure that describes the property.

Expand image Return Value

Returns a valid HRESULT, typically S_OK.

Expand image See Also

Reference

DBGPROP_INFO_FLAGS
DebugPropertyInfo Structure

Concepts

IDebugProperty Interface


IDebugProperty::SetValueAsString

Microsoft Windows Script Interfaces
IDebugProperty::SetValueAsString
See Also
CollapseAll image DropDown image

Sets the value of a property from a given string.

HRESULT SetValueAsString (
   LPCOLESTR pszValue,
   UINT nRadix,
);

Parameters

pszValue

[in] The value to be set.

nRadix

[in] Radix to be used in interpreting any numerical information.

Expand image Return Value

Returns a valid HRESULT, typically S_OK.

Expand image See Also

Concepts

IDebugProperty Interface


IDebugPropertyEnumType_All Interface

Microsoft Windows Script Interfaces
IDebugPropertyEnumType_All Interface
See Also
CollapseAll image DropDown image

The IDebugPropertyEnumType interfaces are defined so that each of their IIDs can be passed as a filter to IDebugProperty::EnumMembers while requesting the appropriate enumerator.

IDebugPropertyEnumType_All : IUnknown

Expand image Methods in Vtable Order

Method | Description
IDebugPropertyEnumType_All::GetName | Returns a text string describing the name

The following interfaces inherit from IDebugPropertyEnumType_All, and have no additional methods.

CopyCode image Copy Code
IDebugPropertyEnumType_Arguments : IDebugPropertyEnumType_All
IDebugPropertyEnumType_Locals : IDebugPropertyEnumType_All
IDebugPropertyEnumType_LocalsPlusArgs : IDebugPropertyEnumType_All
IDebugPropertyEnumType_Registers : IDebugPropertyEnumType_All

Expand image See Also

Reference

IDebugProperty::EnumMembers


IDebugPropertyEnumType_All::GetName

Microsoft Windows Script Interfaces
IDebugPropertyEnumType_All::GetName
See Also
CollapseAll image DropDown image

Returns a BSTR containing the name of the EnumType.

HRESULT GetName(
   BSTR*  pname
);

Parameters

pname

[out] A BSTR containing the name of the EnumType.

Expand image Return Value

Returns a valid HRESULT, typically S_OK.

Expand image See Also

Reference

IDebugPropertyEnumType_All Interface


IEnumDebugExtendedPropertyInfo Interface

Microsoft Windows Script Interfaces
IEnumDebugExtendedPropertyInfo Interface
See Also
CollapseAll image DropDown image

Enumerates ExtendedDebugPropertyInfo structures.

Expand image Methods in Vtable Order

The following table shows the methods of IEnumDebugExtendedPropertyInfo.

Method | Description
IEnumDebugExtendedPropertyInfo::Clone | Creates an enumerator that contains the same enumeration state as the current enumerator.
IEnumDebugExtendedPropertyInfo::GetCount | Gets the number of ExtendedDebugPropertyInfo structures in an enumerator.
IEnumDebugExtendedPropertyInfo::Next | Retrieves a specified number of ExtendedDebugPropertyInfo structures in an enumeration sequence.
IEnumDebugExtendedPropertyInfo::Skip | Skips a specified number of ExtendedDebugPropertyInfo structures in an enumeration sequence.
IEnumDebugExtendedPropertyInfo::Reset | Resets the enumeration sequence to the beginning.

Expand image Requirements

Header: dbgprop.h

Expand image See Also

Reference

ExtendedDebugPropertyInfo Structure


IEnumDebugExtendedPropertyInfo::Clone

Microsoft Windows Script Interfaces
IEnumDebugExtendedPropertyInfo::Clone
See Also
CollapseAll image DropDown image

Creates an enumerator that contains the same enumeration state as the current enumerator.

HRESULT Clone (
   IEnumDebugExtendedPropertyInfo** ppEnum
);

Parameters

ppEnum

[out] Returns the cloned IEnumDebugExtendedPropertyInfo interface.

Expand image Return Value

Returns a valid HRESULT, typically S_OK.

Expand image See Also

Reference

IEnumDebugExtendedPropertyInfo Interface


IEnumDebugExtendedPropertyInfo::GetCount

Microsoft Windows Script Interfaces
IEnumDebugExtendedPropertyInfo::GetCount
See Also
CollapseAll image DropDown image

Gets the number of ExtendedDebugPropertyInfo structures in the enumerator.

HRESULT GetCount (
   ULONG* pcelt
);

Parameters

pcelt

[out] Returns the number of ExtendedDebugPropertyInfo structures in the enumerator.

Expand image Return Value

Returns a valid HRESULT, typically S_OK.

Expand image See Also

Reference

IEnumDebugExtendedPropertyInfo Interface
ExtendedDebugPropertyInfo Structure


IEnumDebugExtendedPropertyInfo::Next

Microsoft Windows Script Interfaces
IEnumDebugExtendedPropertyInfo::Next
See Also
CollapseAll image DropDown image

Retrieves a specified number of ExtendedDebugPropertyInfo structures in an enumeration sequence.

HRESULT Next (
   ULONG celt,
   ExtendedDebugPropertyInfo *rgelt,
   ULONG* pceltFetched
);

Parameters

celt

[in] The number of ExtendedDebugPropertyInfo structures to be retrieved.

rgelt

[out] An array of ExtendedDebugPropertyInfo structures retrieved.

pceltFetched

[out] The number of ExtendedDebugPropertyInfo structures actually retrieved.

Expand image Return Value

Returns a valid HRESULT, typically S_OK.

Expand image See Also

Reference

IEnumDebugExtendedPropertyInfo Interface
ExtendedDebugPropertyInfo Structure


IEnumDebugExtendedPropertyInfo::Reset

Microsoft Windows Script Interfaces
IEnumDebugExtendedPropertyInfo::Reset
See Also
CollapseAll image DropDown image

Resets an enumeration sequence to the beginning.

HRESULT Reset (
void
);

Expand image Return Value

Returns a valid HRESULT, typically S_OK.

Expand image See Also

Reference

IEnumDebugExtendedPropertyInfo Interface


IEnumDebugExtendedPropertyInfo::Skip

Microsoft Windows Script Interfaces
IEnumDebugExtendedPropertyInfo::Skip
See Also
CollapseAll image DropDown image

Skips a specified number of ExtendedDebugPropertyInfo structures in an enumeration sequence.

HRESULT Skip(
   ULONG celt
);

Parameters

celt

[in] The number of ExtendedDebugPropertyInfo structures in the enumeration sequence to skip.

Expand image Return Value

Returns a valid HRESULT, typically S_OK. Returns S_FALSE and sets the current element pointer to the end of the enumeration if celt is greater than the number of elements left in the enumerator.

Expand image See Also

Reference

IEnumDebugExtendedPropertyInfo Interface
ExtendedDebugPropertyInfo Structure


IEnumDebugPropertyInfo Interface

Microsoft Windows Script Interfaces
IEnumDebugPropertyInfo Interface
See Also
DropDown image

Enumerates DebugPropertyInfo structures.

Methods in Vtable Order

The following table shows the methods of IEnumDebugPropertyInfo.

Method | Description
IEnumDebugPropertyInfo::Next | Retrieves a specified number of DebugPropertyInfo structures in an enumeration sequence.
IEnumDebugPropertyInfo::Skip | Skips a specified number of DebugPropertyInfo structures in an enumeration sequence.
IEnumDebugPropertyInfo::Reset | Resets the enumeration sequence to the beginning.
IEnumDebugPropertyInfo::Clone | Creates an enumerator that contains the same enumeration state as the current enumerator.
IEnumDebugPropertyInfo::GetCount | Gets the number of DebugPropertyInfo structures in an enumerator.

Requirements

Header: dbgprop.h

See Also

Reference

DebugPropertyInfo Structure


IEnumDebugPropertyInfo::Clone

Microsoft Windows Script Interfaces
IEnumDebugPropertyInfo::Clone
See Also
CollapseAll image DropDown image

Creates an enumerator that contains the same enumeration state as the current enumerator.

HRESULT Clone (
   IEnumDebugPropertyInfo** ppEnum
);

Parameters

ppEnum

[out] Returns the cloned IEnumDebugPropertyInfo interface.

Expand image Return Value

Returns a valid HRESULT, typically S_OK.

Expand image See Also

Concepts

IEnumDebugPropertyInfo Interface


IEnumDebugPropertyInfo::GetCount

Microsoft Windows Script Interfaces
IEnumDebugPropertyInfo::GetCount
See Also
CollapseAll image DropDown image

Gets the number of DebugPropertyInfo structures in the enumerator.

HRESULT GetCount (
   ULONG* pcelt
);

Parameters

pcelt

[out] Returns the number of DebugPropertyInfo structures in the enumerator.

Expand image Return Value

Returns a valid HRESULT, typically S_OK.

Expand image See Also

Reference

DebugPropertyInfo Structure

Concepts

IEnumDebugPropertyInfo Interface


IEnumDebugPropertyInfo::Next

Microsoft Windows Script Interfaces
IEnumDebugPropertyInfo::Next
See Also
CollapseAll image DropDown image

Retrieves a specified number of DebugPropertyInfo structures in an enumeration sequence.

HRESULT Next (
   ULONG celt,
   DebugPropertyInfo*rgelt,
   ULONG* pceltFetched
);

Parameters

celt

[in] The number of DebugPropertyInfo structures to be retrieved.

rgelt

[out] An array of DebugPropertyInfo structures retrieved.

pceltFetched

[out] Returns the number of DebugPropertyInfo structures actually retrieved.

Expand image Return Value

Returns a valid HRESULT, typically S_OK.

Expand image See Also

Reference

DebugPropertyInfo Structure

Concepts

IEnumDebugPropertyInfo Interface


IEnumDebugPropertyInfo::Reset

Microsoft Windows Script Interfaces
IEnumDebugPropertyInfo::Reset
See Also
CollapseAll image DropDown image

Resets an enumeration sequence to the beginning.

HRESULT Reset (
void
);

Expand image Return Value

Returns a valid HRESULT, typically S_OK.

Expand image See Also

Concepts

IEnumDebugPropertyInfo Interface


IEnumDebugPropertyInfo::Skip

Microsoft Windows Script Interfaces
IEnumDebugPropertyInfo::Skip
See Also
CollapseAll image DropDown image

Skips a specified number of DebugPropertyInfo structures in an enumeration sequence.

HRESULT Skip(
   ULONG celt
);

Parameters

celt

[in] The number of DebugPropertyInfo structures in the enumeration sequence to skip.

Expand image Return Value

Returns a valid HRESULT, typically S_OK. Returns S_FALSE and sets the current element pointer to the end of the enumeration if celt is greater than the number of elements left in the enumerator.

Expand image See Also

Reference

DebugPropertyInfo Structure

Concepts

IEnumDebugPropertyInfo Interface


IPerPropertyBrowsing2 Interface

Microsoft Windows Script Interfaces
IPerPropertyBrowsing2 Interface
CollapseAll image DropDown image

Accesses the information in the property pages offered by an object.

Expand image Methods in Vtable Order

Method | Description
GetDisplayString | Returns a text string describing the specified property.
MapPropertyToPage | Returns the CLSID of the property page that allows manipulation of the specified property.
GetPredefinedStrings | Returns a counted array of strings (LPOLESTR pointers) listing the descriptions of the allowable values that the specified property can accept.
SetPredefinedValue | Sets the value of the property to the predefined value identified by the token dwCookie.

Expand image Requirements

Header: dbgprop.h


IPerPropertyBrowsing2::GetDisplayString

Microsoft Windows Script Interfaces
IPerPropertyBrowsing2::GetDisplayString
See Also
CollapseAll image DropDown image

Gets a string to display types which are not inherently viewable The returned text is a name describing the property and can be displayed in the caller's user interface.

HRESULT GetDisplayString(
   DISPID  dispid,
   BSTR*  pBstr
);

Parameters

dispid

[in] Dispatch identifier of the property whose display name is requested.

pBstr

[out] Pointer to the BSTR containing the display name for the property identified by dispID.

Expand image Return Value

Returns a valid HRESULT, typically S_OK.

Expand image Remarks

The returned string is not a legal value of the property. It is just a string display of the property.

Expand image See Also

Reference

IPerPropertyBrowsing2 Interface


IPerPropertyBrowsing2::GetPredefinedStrings

Microsoft Windows Script Interfaces
IPerPropertyBrowsing2::GetPredefinedStrings
See Also
CollapseAll image DropDown image

Allows the caller to fill a list box with a counted array of string pointers which represent potential values for this property.

HRESULT GetPredefinedStrings(
   DISPID  dispid,
   CALPOLESTR*  pCaStrings,
   CADWORD*  pCaCookies
);

Parameters

dispid

[in] Dispatch identifier of the property for which the caller is requesting the string list.

pCaStrings

[out] Pointer to a caller-allocated, counted array structure that contains the element count and address of a method-allocated array of string pointers. If the method fails, no memory is allocated, and the contents of the structure are undefined.

pCaCookies

[out] Pointer to the caller-allocated, counted array structure that contains the element count and address of a method-allocated array of DWORDs. If the method fails, no memory is allocated, and the contents of the structure are undefined.

Expand image Return Value

Returns a valid HRESULT, typically S_OK.

Expand image See Also

Reference

IPerPropertyBrowsing2 Interface


IPerPropertyBrowsing2::MapPropertyToPage

Microsoft Windows Script Interfaces
IPerPropertyBrowsing2::MapPropertyToPage
See Also
CollapseAll image DropDown image

Returns the CLSID of the property page that can be used to edit this property.

HRESULT MapPropertyToPage(
   DISPID  dispid,
   CLSID*  pClsidPropPage
);

Parameters

dispid

[in] Dispatch identifier of the property of interest.

pClsidPropPage

[out] Pointer to the CLSID identifying the property page associated with the property. If this method fails, *pClsidPropPage is set to CLSID_NULL.

Expand image Return Value

Returns a valid HRESULT, typically S_OK.

Expand image See Also

Reference

IPerPropertyBrowsing2 Interface


IPerPropertyBrowsing2::SetPredefinedValue

Microsoft Windows Script Interfaces
IPerPropertyBrowsing2::SetPredefinedValue
See Also
CollapseAll image DropDown image

Sets the value of the property specified by dispID. The predefined value is identified by the token dwCookie.

HRESULT SetPredefinedValue(
   DISPID  dispid,
   DWORD  dwCookie
);

Parameters

dispid

[in] Dispatch identifier of the property for which a predefined value is being set.

dwCookie

[in] Token identifying the value to set.

Expand image Return Value

Returns a valid HRESULT, typically S_OK.

Expand image See Also

Reference

IPerPropertyBrowsing2 Interface


Dispatch Extension Interfaces

Microsoft Windows Script Interfaces
Dispatch Extension Interfaces
DropDown image

The DispEx.h header file provides the interfaces listed in this section.

In This Section

The following interfaces are for the Microsoft® Windows® Script Host and Windows Script Engines.

  • ICanHandleException Interface

  • IDispatchEx Interface

  • IDispError Interface

  • IVariantChangeType Interface

The following interfaces are specific to the Windows Script Host:

  • IObjectIdentity Interface


ICanHandleException Interface

Microsoft Windows Script Interfaces
ICanHandleException Interface
DropDown image

Allows the caller of a script engine to specify which exceptions the caller handles.

Methods

In addition to the methods inherited from IUnknown, the ICanHandleException interface exposes the following methods.

Method | Description
ICanHandleException::CanHandleException | Determines if the caller of the script engine can handle a specified exception.


ICanHandleException::CanHandleException

Microsoft Windows Script Interfaces
ICanHandleException::CanHandleException
See Also
CollapseAll image DropDown image

Determines if the caller of the script engine can handle a specified exception.

HRESULT CanHandleException(
   EXCEPINFO*  pExcepInfo,
   VARIANT*    pvar
);

Parameters

pExcepInfo

[in] Pointer to an EXCEPINFO structure containing the information that will be reported if no exception handler is found.

pvar

[in] A value associated with the exception, such as the value thrown by a throw statement. This parameter may be NULL.

Expand image Return Value

The method returns an HRESULT. Possible values include, but are not limited to, those in the following table.

Value | Description
S_OK | The caller can handle the exception
E_FAIL | The caller cannot handle the exception.

Expand image Remarks

If a call to IDispatchEx::InvokeEx, or a similar method, results in an exception, the script engine checks for a caller in the script's caller chain that supports the ICanHandleException interface and indicates that it can handle the exception. If no caller can handle the exception, the script engine halts.

Expand image See Also

Reference

IDispatchEx::InvokeEx

Concepts

ICanHandleException Interface


IDispatchEx Interface

Microsoft Windows Script Interfaces
IDispatchEx Interface
DropDown image

IDispatchEx, an extension of the IDispatch interface, supports features appropriate for dynamic languages such as scripting languages. This section describes the IDispatchEx interface itself, the differences between IDispatch and IDispatchEx, and the rationale for the extensions. It is expected that readers are familiar with IDispatch and have access to the IDispatch documentation.

Remarks

IDispatch was developed essentially for Microsoft® Visual Basic®. The primary limitation of IDispatch is that it assumes that objects are static. In other words, since objects do not change during run time, type information can fully describe them at compile time. Dynamic run-time models that are found in scripting languages such as Visual Basic Scripting Edition (VBScript) and JScript and object models such as Dynamic HTML require a more flexible interface.

IDispatchEx was developed to provide all the services of IDispatch as well as some extensions that are appropriate for more dynamic late-bound languages such as scripting languages. The additional features of IDispatchEx beyond those provided by IDispatch are:

  • Add new members to an object ("expando")—use GetDispID with the fdexNameEnsure flag.

  • Delete members of an object—use DeleteMemberByName or DeleteMemberByDispID.

  • Case-sensitive dispatch operations—use fdexNameCaseSensitive or fdexNameCaseInsensitive.

  • Search for member with implicit name—use fdexNameImplicit.

  • Enumerate DISPIDs of an object—use GetNextDispID.

  • Map from DISPID to element name—use GetMemberName.

  • Obtain properties of object members—use GetMemberProperties.

  • Method invocation with this pointer—use InvokeEx with DISPATCH_METHOD.

  • Allow browsers that support the concept of name spaces to obtain the name space parent of an object—use GetNameSpaceParent.

Objects that support IDispatchEx might also support IDispatch for backward compatibility. The dynamic nature of objects that support IDispatchEx has a few implications for the IDispatch interface of those objects. For example, IDispatch makes the following assumption:

  • The member and parameter DISPIDs must remain constant for the lifetime of the object. This allows a client to obtain DISPIDs once and cache them for later use.

Since IDispatchEx allows the addition and deletion of members, the set of valid DISPIDs does not remain constant. However, IDispatchEx requires that the mapping between DISPID and member name remain constant. This means that if a member is deleted:

  • The DISPID cannot be reused until a member with the same name is created.

  • The DISPID must remain valid for GetNextDispID.

  • The DISPID must be accepted gracefully by any of the IDispatch or IDispatchEx methods—they must recognize the member as deleted and return an appropriate error code (usually DISP_E_MEMBERNOTFOUND or S_FALSE).

Examples

This JScript code in the function test() does the following:

  • Creates a new object by calling the Object constructor and assigns a pointer to the new object to the variable Obj.

  • Creates a new element named Elem in the object and assigns to this element a pointer to the function cat.

  • Calls this function. Since it is being called as a method, the this pointer refers to the object Obj. The function adds a new element, Bar, to the object.

The full HTML code is:

CopyCode image Copy Code
   <HTML>
   <BODY>
   <SCRIPT LANGUAGE="JScript">
   function cat()
   {
      // Create new element and assign the value 10
      this.Bar = 10;
   }

   function test()
   {
      // Construct new object
      Obj = new Object();

      // Create new element and assign function pointer
      Obj.Elem = cat;

      // Call Elem method ("this" == Obj)
      Obj.Elem();

      // Obj.Bar now exists
   }
   test();
   </SCRIPT>
   </BODY>
   </HTML>

A control placed on this same Web page could obtain a dispatch pointer to the script engines from the browser. The control could then implement the function test():

CopyCode image Copy Code
   <HTML>
   <BODY>
   <SCRIPT LANGUAGE="JScript">
   function cat()
   {
      // Create new element and assign the value 10
      this.Bar = 10;
   }
   </SCRIPT>
   <OBJECT ID="test" <CLASSID="CLSID:9417DB5D-FA2A-11D0-8CB3-00C04FC2B085">>
   </OBJECT>
   </BODY>
   </HTML>

Code from the control, test, does the same thing as the JScript function test(). Note that these dispatch calls are made into the running JScript engine and change the state of the engine:

  • Obtains the dispatch pointer to the cat function using GetDispID().

  • Obtains the dispatch pointer to the Object function using GetDispID().

  • Constructs an object by calling the Object function with InvokeEx() and obtains a dispatch pointer to the newly constructed object.

  • Creates a new element, Elem, in the object using GetDispID() with the fdexNameEnsure flag.

  • Puts the dispatch pointer to cat in the element using InvokeEx().

  • Calls the dispatch pointer to cat as a method by calling InvokeEx() and passing in the dispatch pointer to the constructed object as the this pointer.

  • The cat method creates a new element, Bar, on the current this object.

  • Verifies that the new element, Bar, was created in the constructed object by enumerating through the elements using GetNextDispID().

The code for the test control:

CopyCode image Copy Code
   BOOL test(IDispatchEx *pdexScript)
   {
      HRESULT hr;
      VARIANT var;
      DISPID dispid, putid;
      BOOL retval = FALSE;
      BSTR bstrName = NULL;
      IDispatch   *pdispObj = NULL, *pdispCat = NULL;
      IDispatchEx *pdexObj = NULL;
      DISPPARAMS dispparams, dispparamsNoArgs = {NULL, NULL, 0, 0};

      // Get dispatch pointer for "cat"
      bstrName = SysAllocString(OLESTR("cat"));
         if (bstrName == NULL) goto LDone;
      hr = pdexScript->GetDispID(bstrName, 0, &dispid);
         if (FAILED(hr)) goto LDone;
      SysFreeString(bstrName);
         bstrName = NULL;
      hr = pdexScript->InvokeEx(dispid, LOCALE_USER_DEFAULT,
         DISPATCH_PROPERTYGET, &dispparamsNoArgs,
         &var, NULL, NULL);
         if (FAILED(hr)) goto LDone;
      pdispCat = var.pdispVal;

      // Create object by calling "Object" constructor
      bstrName = SysAllocString(OLESTR("Object"));
         if (NULL == bstrName) goto LDone;
      hr = pdexScript->GetDispID(bstrName, 0, &dispid);
         if (FAILED(hr)) goto LDone;
      SysFreeString(bstrName);
         bstrName = NULL;
      hr = pdexScript->InvokeEx(dispid, LOCALE_USER_DEFAULT,
         DISPATCH_CONSTRUCT, &dispparamsNoArgs,
         &var, NULL, NULL);
         if (FAILED(hr)) goto LDone;
      pdispObj = var.pdispVal;
      hr = pdispObj->QueryInterface(IID_IDispatchEx, (void **)&pdexObj);
         if (FAILED(hr)) goto LDone;

      // Create new element in object
      bstrName = SysAllocString(OLESTR("Elem"));
         if (NULL == bstrName) goto LDone;
      hr = pdexObj->GetDispID(bstrName, fdexNameEnsure, &dispid);
         if (FAILED(hr)) goto LDone;
      SysFreeString(bstrName);
         bstrName = NULL;

      // Assign "cat" dispatch pointer to element
      putid = DISPID_PROPERTYPUT;
      var.vt = VT_DISPATCH;
      var.pdispVal = pdispCat;
      dispparams.rgvarg = &var;
      dispparams.rgdispidNamedArgs = &putid;
      dispparams.cArgs = 1;
      dispparams.cNamedArgs = 1;
      hr = pdexObj->InvokeEx(dispid, LOCALE_USER_DEFAULT,
         DISPATCH_PROPERTYPUTREF, &dispparams,
         NULL, NULL, NULL);
         if (FAILED(hr)) goto LDone;

      // Invoke method with "this" pointer
      putid = DISPID_THIS;
      var.vt = VT_DISPATCH;
      var.pdispVal = pdispObj;
      dispparams.rgvarg = &var;
      dispparams.rgdispidNamedArgs = &putid;
      dispparams.cArgs = 1;
      dispparams.cNamedArgs = 1;
      hr = pdexObj->InvokeEx(dispid, LOCALE_USER_DEFAULT,
         DISPATCH_METHOD, &dispparams,
            NULL, NULL, NULL);
         if (FAILED(hr)) goto LDone;

      // Confirm that new element "Bar" is in object
      hr = pdexObj->GetNextDispID(fdexEnumAll, DISPID_STARTENUM, &dispid);
      while (hr == NOERROR)
      {
            hr = pdexObj->GetMemberName(dispid, &bstrName);
            if (FAILED(hr)) goto LDone;
            retval = !wcscmp(bstrName, OLESTR("Bar"));
            SysFreeString(bstrName);
            bstrName = NULL;
            if (retval) goto LDone;
         hr = pdexObj->GetNextDispID(fdexEnumAll, dispid, &dispid);
      }
LDone:
   SysFreeString(bstrName);
   if (pdispCat != NULL)
      pdispCat->Release();
   if (pdispObj != NULL)
      pdispObj->Release();
   if (pdexObj != NULL)
      pdexObj->Release();

   return retval;
   }

Methods

IDispatchEx Methods


IDispatchEx Methods

Microsoft Windows Script Interfaces
IDispatchEx Methods
DropDown image

The following are IDispatchEx methods.

In This Section

IDispatchEx::DeleteMemberByDispID

Deletes a member by DISPID.

IDispatchEx::DeleteMemberByName

Deletes a member by name.

IDispatchEx::GetDispID

Maps a single member name to its corresponding DISPID, which can then be used on subsequent calls to IDispatchEx::InvokeEx.

IDispatchEx::GetMemberName

Retrieves the name of a member.

IDispatchEx::GetMemberProperties

Retrieves a member's properties.

IDispatchEx::GetNameSpaceParent

Retrieves the interface for the namespace parent of an object.

IDispatchEx::GetNextDispID

Enumerates the members of the object.

IDispatchEx::InvokeEx

Provides access to properties and methods exposed by an IDispatchEx object.

Related Sections

IDispatchEx Interface


IDispatchEx::DeleteMemberByDispID

Microsoft Windows Script Interfaces
IDispatchEx::DeleteMemberByDispID
See Also Example
CollapseAll image DropDown image

Deletes a member by DISPID.

HRESULT DeleteMemberByDispID(
    DISPID id
);

Parameters

id

Member identifier. Uses GetDispID or GetNextDispID to obtain the dispatch identifier.

Expand image Return Value

Returns one of the following values:

S_OK | Success.
S_FALSE | Member exists but cannot be deleted.

Expand image Remarks

If the member is deleted, the DISPID needs to remain valid for GetNextDispID.

If a member with a given name is deleted and later a member with the same name is recreated, the DISPID should be the same. (Whether member names that differ only by case are the "same" is object-dependent.)

Expand image Example

CopyCode image Copy Code
BSTR bstrName;
DISPID dispid;
IDispatchEx *pdex;

// Assign to pdex and bstrName
if (SUCCEEDED(pdex->GetDispID(bstrName, fdexNameCaseSensitive, &dispid)))
    pdex->DeleteMemberByDispID(dispid);

Expand image See Also

Reference

IDispatchEx::GetDispID
IDispatchEx::GetNextDispID

Concepts

IDispatchEx Interface


IDispatchEx::DeleteMemberByName

Microsoft Windows Script Interfaces
IDispatchEx::DeleteMemberByName
See Also Example
CollapseAll image DropDown image

Deletes a member by name.

HRESULT DeleteMemberByName(
   BSTR bstrName,
   DWORD grfdex

Parameters

bstrName

Name of member to be deleted.

grfdex

Determines if the member name is case sensitive. This can be one of the following values:

Value Meaning

fdexNameCaseSensitive

Requests that the name lookup be done in a case-sensitive manner. Can be ignored by object that does not support case-sensitive lookup.

fdexNameCaseInsensitive

Requests that the name lookup be done in a case-insensitive manner. Can be ignored by object that does not support case-insensitive lookup.

Expand image Return Value

Returns one of the following values:

S_OK | Success.
S_FALSE | Member exists but cannot be deleted.

Expand image Remarks

If the member is deleted, the DISPID needs to remain valid for GetNextDispID.

If a member with a given name is deleted and later a member with the same name is recreated, the DISPID should be the same. (Whether members that differ only by case are the "same" is object-dependent.)

Expand image Example

CopyCode image Copy Code
BSTR bstrName;
IDispatchEx *pdex;

// Assign to pdex and bstrName
pdex->DeleteMemberByName(bstrName, fdexNameCaseSensitive);

Expand image See Also

Concepts

IDispatchEx Interface


IDispatchEx::GetDispID

Microsoft Windows Script Interfaces
IDispatchEx::GetDispID
See Also Example
CollapseAll image DropDown image

Maps a single member name to its corresponding DISPID, which can then be used on subsequent calls to IDispatchEx::InvokeEx.

 HRESULT GetDispID(
   BSTR bstrName,
   DWORD grfdex,
   DISPID *pid
);

Parameters

bstrName

Passed in name to be mapped.

grfdex

Determines the options for obtaining the member identifier. This can be a combination of the following values:

Value Meaning

fdexNameCaseSensitive

Requests that the name lookup be done in a case-sensitive manner. May be ignored by object that does not support case-sensitive lookup.

fdexNameEnsure

Requests that the member be created if it does not already exist. The new member should be created with the value VT_EMPTY.

fdexNameImplicit

Indicates that the caller is searching object(s) for a member of a particular name when the base object is not explicitly specified.

fdexNameCaseInsensitive

Requests that the name lookup be done in a case-insensitive manner. May be ignored by object that does not support case-insensitive lookup.
pid

Pointer to caller-allocated location to receive DISPID result. If an error occurs, pid contains DISPID_UNKNOWN.

Expand image Return Value

Returns one of the following values:

S_OK | Success.
E_OUTOFMEMORY | Out of Memory.
DISP_E_UNKNOWNNAME | The name was not known.

Expand image Remarks

GetDispID can be used instead of GetIDsOfNames to obtain the DISPID for a given member.

Because IDispatchEx allows the addition and deletion of members, the set of DISPIDs does not remain constant for the lifetime of an object.

The unused riid parameter in IDispatch::GetIDsOfNames has been removed.

Expand image Example

CopyCode image Copy Code
BSTR bstrName;
   DISPID dispid;
   IDispatchEx *pdex;

   // Assign to pdex and bstrName
   pdex->GetDispID(bstrName, fdexNameCaseSensitive, &dispid);
   // Use dispid

Expand image See Also

Concepts

IDispatchEx Interface


IDispatchEx::GetMemberName

Microsoft Windows Script Interfaces
IDispatchEx::GetMemberName
See Also Example
CollapseAll image DropDown image

Retrieves the name of a member.

HRESULT GetMemberName(
   DISPID id,
   BSTR *pbstrName
);

Parameters

id

Identifies the member. Uses GetDispID or GetNextDispID to obtain the dispatch identifier.

pbstrName

Address of a BSTR that receives the name of the member. The calling application is responsible for freeing this value.

Expand image Return Value

Returns one of the following values:

S_OK | Success.
DISP_E_UNKNOWNNAME | The name was not known.

Expand image Example

CopyCode image Copy Code
HRESULT hr;
   BSTR bstrName;
   DISPID dispid;
   IDispatchEx *pdex;

   // Assign to pdex
   hr = pdex->GetNextDispID(fdexEnumAll, DISPID_STARTENUM, &dispid);
   while (hr == NOERROR)
   {
      hr = pdex->GetMemberName(dispid, &bstrName);
      if (!wcscmp(bstrName, OLESTR("Bar")))
      {
         SysFreeString(bstrName);
         return TRUE;
      }
   SysFreeString(bstrName);
   hr = pdex->GetNextDispID(fdexEnumAll, dispid, &dispid);
   }

Expand image See Also

Reference

IDispatchEx::GetDispID
IDispatchEx::GetNextDispID

Concepts

IDispatchEx Interface


IDispatchEx::GetMemberProperties

Microsoft Windows Script Interfaces
IDispatchEx::GetMemberProperties
See Also Example
CollapseAll image DropDown image

Retrieves a member's properties.

HRESULT GetMemberProperties(
   DISPID id,
   DWORD grfdexFetch,
   DWORD *pgrfdex
);

Parameters

id

Identifies the member. Uses GetDispID or GetNextDispID to obtain the dispatch identifier.

grfdexFetch

Determines which properties to retrieve. This can be a combination of the values listed under pgrfdex and/or a combination of the following values:

Value Meaning

grfdexPropCanAll

Combines fdexPropCanGet, fdexPropCanPut, fdexPropCanPutRef, fdexPropCanCall, fdexPropCanConstruct and fdexPropCanSourceEvents.

grfdexPropCannotAll

Combines fdexPropCannotGet, fdexPropCannotPut, fdexPropCannotPutRef, fdexPropCannotCall, fdexPropCannotConstruct and fdexPropCannotSourceEvents.

grfdexPropExtraAll

Combines fdexPropNoSideEffects and fdexPropDynamicType.

grfdexPropAll

Combines grfdexPropCanAll, grfdexPropCannotAll and grfdexPropExtraAll.
pgrfdex

Address of a DWORD that receives the requested properties. This can be a combination of the following values:

Value Meaning

fdexPropCanGet

The member can be obtained using DISPATCH_PROPERTYGET.

fdexPropCannotGet

The member cannot be obtained using DISPATCH_PROPERTYGET.

fdexPropCanPut

The member can be set using DISPATCH_PROPERTYPUT.

fdexPropCannotPut

The member cannot be set using DISPATCH_PROPERTYPUT.

fdexPropCanPutRef

The member can be set using DISPATCH_PROPERTYPUTREF.

fdexPropCannotPutRef

The member cannot be set using DISPATCH_PROPERTYPUTREF.

fdexPropNoSideEffects

The member does not have any side effects. For example, a debugger could safely get/set/call this member without changing the state of the script being debugged.

fdexPropDynamicType

The member is dynamic and can change during the lifetime of the object.

fdexPropCanCall

The member can be called as a method using DISPATCH_METHOD.

fdexPropCannotCall

The member cannot be called as a method using DISPATCH_METHOD.

fdexPropCanConstruct

The member can be called as a constructor using DISPATCH_CONSTRUCT.

fdexPropCannotConstruct

The member cannot be called as a constructor using DISPATCH_CONSTRUCT.

fdexPropCanSourceEvents

The member can fire events.

fdexPropCannotSourceEvents

The member cannot fire events.

Expand image Return Value

Returns one of the following values:

S_OK | Success.
DISP_E_UNKNOWNNAME | The name was not known.

Expand image Example

CopyCode image Copy Code
BSTR bstrName;
   DISPID dispid;
   IDispatchEx *pdex;
   DWORD dwProps;

   // Assign to pdex and bstrName
   if (SUCCEEDED(pdex->GetDispID(bstrName, fdexNameCaseSensitive, &dispid)) &&
      SUCCEEDED(pdex->GetMemberProperties(dispid, grfdexPropAll, &dwProps)) &&
         (dwProps & fdexPropCanPut))
   {
      // Assign to member
   }

Expand image See Also

Reference

IDispatchEx::GetDispID
IDispatchEx::GetNextDispID

Concepts

IDispatchEx Interface


IDispatchEx::GetNameSpaceParent

Microsoft Windows Script Interfaces
IDispatchEx::GetNameSpaceParent
See Also
CollapseAll image DropDown image

Retrieves the interface for the namespace parent of an object.

HRESULT GetNameSpaceParent(
   IUnknown **ppunk
);

Parameters

ppunk

Address of an IUnknown interface pointer that receives the namespace parent's interface.

Expand image Return Value

Returns S_OK if successful or an OLE-defined error code otherwise.

Expand image See Also

Concepts

IDispatchEx Interface


IDispatchEx::GetNextDispID

Microsoft Windows Script Interfaces
IDispatchEx::GetNextDispID
See Also Example
CollapseAll image DropDown image

Enumerates the members of the object.

HRESULT GetNextDispID(
   DWORD grfdex,
   DISPID id,
   DISPID *pid
);

Parameters

grfdex

Determines which set of items are to be enumerated. This can be a combination of the following values:

Value Meaning

fdexEnumDefault

Requests that the object enumerates the default elements. The object is allowed to enumerate any set of elements.

fdexEnumAll

Requests that the object enumerates all of the elements. The object is allowed to enumerate any set of elements.
id

Identifies the current member. GetNextDispID retrieves the item in the enumeration after this one. Uses GetDispID or a previous call to GetNextDispID to obtain this identifier. Uses the DISPID_STARTENUM value to obtain the first identifier of the first item.

pid

Address of a DISPID variable that receives the identifier of the next item in the enumeration.

If a member is deleted by DeleteMemberByName or DeleteMemberByDispID, the DISPID needs to remain valid for GetNextDispID.

Expand image Return Value

Returns one of the following values:

S_OK | Success.
S_FALSE | Enumeration is done.

Expand image Example

CopyCode image Copy Code
HRESULT hr;
   BSTR bstrName;
   DISPID dispid;
   IDispatchEx *pdex;

   // Assign to pdex
   hr = pdex->GetNextDispID(fdexEnumAll, DISPID_STARTENUM, &dispid);
   while (hr == NOERROR)
   {
      hr = pdex->GetMemberName(dispid, &bstrName);
      if (!wcscmp(bstrName, OLESTR("Bar")))
      {
         SysFreeString(bstrName);
         return TRUE;
      }
      SysFreeString(bstrName);
      hr = pdex->GetNextDispID(fdexEnumAll, dispid, &dispid);
   }

Expand image See Also

Reference

IDispatchEx::GetDispID
IDispatchEx::GetNextDispID
IDispatchEx::DeleteMemberByName
IDispatchEx::DeleteMemberByDispID

Concepts

IDispatchEx Interface


IDispatchEx::InvokeEx

Microsoft Windows Script Interfaces
IDispatchEx::InvokeEx
See Also Example
CollapseAll image DropDown image

Provides access to properties and methods exposed by an IDispatchEx object.

HRESULT InvokeEx(
   DISPID id,
   LCID lcid,
   WORD wFlags,
   DISPARAMS *pdp,
   VARIANT *pVarRes,
   EXCEPINFO *pei,
   IServiceProvider *pspCaller
);

Parameters

id

Identifies the member. Uses GetDispID or GetNextDispID to obtain the dispatch identifier.

lcid

The locale context in which to interpret arguments. The lcid is passed to InvokeEx to allow the object to interpret its arguments specific to a locale.

wFlags

The legal values for wFlags are:

DISPATCH_PROPERTYGET | DISPATCH_METHOD | DISPATCH_PROPERTYPUT | DISPATCH_PROPERTYPUTREF | DISPATCH_CONSTRUCT

Flags describing the context of the InvokeEx call:

Value Meaning

DISPATCH_METHOD

The member is invoked as a method. If a property has the same name, both this and the DISPATCH_PROPERTYGET flag may be set (defined by IDispatch).

DISPATCH_PROPERTYGET

The member is retrieved as a property or data member (defined by IDispatch).

DISPATCH_PROPERTYPUT

The member is changed as a property or data member (defined by IDispatch).

DISPATCH_PROPERTYPUTREF

The member is changed by a reference assignment rather than a value assignment. This flag is valid only when the property accepts a reference to an object (defined by IDispatch).

DISPATCH_CONSTRUCT

The member is being used as a constructor. (This is a new value defined by IDispatchEx). The legal values for wFlags are:

DISPATCH_PROPERTYGET DISPATCH_METHOD DISPATCH_PROPERTYPUT DISPATCH_PROPERTYPUTREF DISPATCH_CONSTRUCT
pdp

Pointer to a structure containing an array of arguments, an array of argument DISPIDs for named arguments, and counts for the number of elements in the arrays. See the IDispatch documentation for a full description of the DISPPARAMS structure.

pVarRes

Pointer to the location where the result is to be stored or Null if the caller expects no result. This argument is ignored if DISPATCH_PROPERTYPUT or DISPATCH_PROPERTYPUTREF is specified.

pei

Pointer to a structure that contains exception information. This structure should be filled in if DISP_E_EXCEPTION is returned. Can be Null. See the IDispatch documentation for a full description of the EXCEPINFO structure.

pspCaller

Pointer to a service provider object supplied by the caller, which allows the object to obtain services from the caller. Can be Null.

IDispatchEx::InvokeEx provides all of the same features as IDispatch::Invoke and adds a few extensions:

DISPATCH_CONSTRUCT | Indicates that the item is being used as a constructor.
pspCaller | The pspCaller allows the object access to services provided by the caller. Specific services may be handled by the caller itself or delegated to callers further up the call chain. For example, if a script engine inside a browser makes an InvokeEx call to an external object, the object can follow the pspCaller chain to obtain services from the script engine or browser. (Note that the call chain is not the same as the creation chain—also known as container chain or site chain. The creation chain may be available through some other mechanism such as IObjectWithSite.)
this pointer | When DISPATCH_METHOD is set in wFlags, there may be a "named parameter" for the "this" value. The DISPID will be DISPID_THIS and it must be the first named parameter.

The unused riid parameter in IDispatch::Invoke has been removed.

The puArgArr parameter in IDispatch::Invoke has been removed.

See the IDispatch::Invoke documentation for the following examples:

"Calling a method with no arguments"

"Getting and setting properties"

"Passing parameters"

"Indexed Properties"

"Raising exceptions during Invoke"

"Returning errors"

Expand image Return Value

Returns one of the following values:

S_OK | Success.
DISP_E_BADPARAMCOUNT | The number of elements provided to DISPPARAMS is different from the number of arguments accepted by the method or property.
DISP_E_BADVARTYPE | One of the arguments in rgvarg is not a valid variant type.
DISP_E_EXCEPTION | The application needs to raise an exception. In this case, the structure passed in pei should be filled in.
DISP_E_MEMBERNOTFOUND | The requested member does not exist, or the call to InvokeEx tried to set the value of a read-only property.
DISP_E_NONAMEDARGS | This implementation of IDispatch does not support named arguments.
DISP_E_OVERFLOW | One of the arguments in rgvarg could not be coerced to the specified type.
DISP_E_PARAMNOTFOUND | One of the parameter DISPIDs does not correspond to a parameter on the method.
DISP_E_TYPEMISMATCH | One or more of the arguments could not be coerced.
DISP_E_UNKNOWNLCID | The member being invoked interprets string arguments according to the LCID, and the LCID is not recognized. If the LCID is not needed to interpret arguments, this error should not be returned.
DISP_E_PARAMNOTOPTIONAL | A required parameter was omitted.

Expand image Example

CopyCode image Copy Code
VARIANT var;
   BSTR bstrName;
   DISPID dispid;
   IDispatchEx *pdex;
   DISPPARAMS dispparamsNoArgs = {NULL, NULL, 0, 0};

   // Assign to pdex and bstrName
   if (SUCCEEDED(pdex->GetDispID(bstrName, fdexNameCaseSensitive, &dispid)))
   {
      pdex->InvokeEx(dispid, LOCALE_USER_DEFAULT,
         DISPATCH_PROPERTYGET, &dispparamsNoArgs,
         &var, NULL, NULL);
   }

Expand image See Also

Reference

IDispatchEx::GetDispID
IDispatchEx::GetNextDispID

Concepts

IDispatchEx Interface


IDispError Interface

Microsoft Windows Script Interfaces
IDispError Interface
DropDown image

Provides detailed contextual error information.

Note Note

This interface is not implemented.

In addition to the methods inherited from IUnknown, the IDispError interface exposes the following methods.

Methods in Vtable Order

Method | Description
IDispError::QueryErrorInfo | Retrieves a particular type of error information.
IDispError::GetNext | Retrieves the next IDispError object.
IDispError::GetHresult | Retrieves the error code from the IDispError object.
IDispError::GetSource | Returns the language-dependent programmatic identifier for the class or application that raised the error.
IDispError::GetHelpInfo | Returns the path of the Help file and the context ID of the topic that explains the error, if possible.
IDispError::GetDescription | Returns a textual description of the error.


IDispError::GetDescription

Microsoft Windows Script Interfaces
IDispError::GetDescription
See Also
CollapseAll image DropDown image

Returns a textual description of the error.

HRESULT GetDescription(
   BSTR*  pbstrDescription
);

Parameters

pbstrDescription

[out] String containing a brief description of the error.

Expand image Return Value

The method returns an HRESULT. Possible values include, but are not limited to, those in the following table.

Value | Description
S_OK | The method succeeded.

Expand image Remarks

The text is returned in the language specified by the locale identifier (LCID) that was passed to IDispatchEx::InvokeEx for the method that encountered the error.

Note Note

This method is not implemented.

Expand image See Also

Reference

IDispatchEx::InvokeEx

Concepts

IDispError Interface


IDispError::GetHelpInfo

Microsoft Windows Script Interfaces
IDispError::GetHelpInfo
See Also
CollapseAll image DropDown image

Returns the path of the Help file and the context ID of the topic that explains the error, if possible.

HRESULT GetHelpInfo(
   BSTR*  pbstrFileName,
   DWORD*  pdwContext
);

Parameters

pbstrFileName

[out] String containing the fully qualified path of the Help file. If there is no Help file or an error occurs, the return value is NULL.

pdwContext

[out] The Help context ID for the error. If there is no Help file (if pbstrFileName is NULL), this parameter has no meaning.

Expand image Return Value

The method returns an HRESULT. Possible values include, but are not limited to, those in the following table.

Value | Description
S_OK | The method succeeded.
E_FAIL | A provider-specific error occurred.
E_INVALIDARG | pbstrFileName or pdwContext was NULL.
E_OUTOFMEMORY | The provider was unable to allocate sufficient memory in which to return the Help file path.

Expand image Remarks

This method returns the path of the Help file and the context ID of the topic that explains the error, if possible.

Note Note

This method is not implemented.

Expand image See Also

Concepts

IDispError Interface


IDispError::GetHresult

Microsoft Windows Script Interfaces
IDispError::GetHresult
See Also
CollapseAll image DropDown image

Retrieves the error code from the IDispError object.

HRESULT GetHresult(
   HRESULT*  phr
);

Parameters

phr

[out] Specifies the error code.

Expand image Return Value

The method returns an HRESULT. Possible values include, but are not limited to, those in the following table.

Value | Description
S_OK | The method succeeded.

Expand image Remarks

This method retrieves the error code from the IDispError object.

Note Note

This method is not implemented.

Expand image See Also

Concepts

IDispError Interface


IDispError::GetNext

Microsoft Windows Script Interfaces
IDispError::GetNext
See Also
CollapseAll image DropDown image

Retrieves the next IDispError object.

HRESULT GetNext(
   IDispError**  ppde
);

Parameters

ppde

[out] Specifies next IDispError object.

Expand image Return Value

The method returns an HRESULT. Possible values include, but are not limited to, those in the following table.

Value | Description
S_OK | The method succeeded.

Expand image Remarks

This method retrieves the next IDispError object. If this is the last IDispError object, this method returns NULL.

Note Note

This method is not implemented.

Expand image See Also

Concepts

IDispError Interface


IDispError::GetSource

Microsoft Windows Script Interfaces
IDispError::GetSource
See Also
CollapseAll image DropDown image

Returns the language-dependent programmatic identifier for the class or application that raised the error.

HRESULT GetSource(
   BSTR*  pbstrSource
);

Parameters

pbstrSource

[out] String that contains a programmatic identifier, in the form progname.objectname.

Expand image Return Value

The method returns an HRESULT. Possible values include, but are not limited to, those in the following table.

Value | Description
S_OK | The method succeeded.

Expand image Remarks

This method is used to determine the class or application where the exception occurred. The programmatic identifier may be returned in the language specified by the locale identifier (LCID) supplied at the time of invocation.

Note Note

This method is not implemented.

Expand image See Also

Concepts

IDispError Interface


IDispError::QueryErrorInfo

Microsoft Windows Script Interfaces
IDispError::QueryErrorInfo
See Also
CollapseAll image DropDown image

Retrieves a particular type of error information.

HRESULT QueryErrorInfo(
   GUID  guidErrorType,
   IDispError**  ppde
);

Parameters

guidErrorType

[in] GUID specifying error type.

ppde

[out] Specifies the IDispError object.

Expand image Return Value

The method returns an HRESULT. Possible values include, but are not limited to, those in the following table.

Value | Description
S_OK | The method succeeded.

Expand image Remarks

The QueryErrorInfo method retrieves a particular type of error information.

Note Note

This method is not implemented.

Expand image See Also

Concepts

IDispError Interface


IObjectIdentity Interface

Microsoft Windows Script Interfaces
IObjectIdentity Interface
DropDown image

In addition to the methods inherited from IUnknown, the IObjectIdentity interface exposes the following methods.

Methods

Method | Description
IObjectIdentity::IsEqualObject | Determines if an object is equal to the current object.


IObjectIdentity::IsEqualObject

Microsoft Windows Script Interfaces
IObjectIdentity::IsEqualObject
See Also
CollapseAll image DropDown image

Determines if an object is equal to the current object.

HRESULT IsEqualObject(
  IUnknown*  punk
);

Parameters

punk

[in] Address of the object to compare with the current object.

Expand image Return Value

The method returns an HRESULT. Possible values include, but are not limited to, those in the following table.

Value | Description
S_OK | The objects are equal.
S_FALSE | The objects are not equal.

Expand image Remarks

An implementation of the IsEqualObject method should return S_OK only if the objects are identical.

Expand image See Also

Concepts

IObjectIdentity Interface


IVariantChangeType Interface

Microsoft Windows Script Interfaces
IVariantChangeType Interface
CollapseAll image DropDown image

Allows the caller to convert a VARIANT value from one type to another.

Expand image Methods

In addition to the methods inherited from IUnknown, the IVariantChangeType interface exposes the following methods.

Method | Description
IVariantChangeType::ChangeType | Takes a variant value and creates a new variant with a specified type.


IVariantChangeType::ChangeType

Microsoft Windows Script Interfaces
IVariantChangeType::ChangeType
See Also
CollapseAll image DropDown image

Takes a variant value and creates a new variant with a specified type.

HRESULT ChangeType(
   VARIANT*  pvarDst,
   VARIANT*  pvarSrc,
   LCID  lcid,
   VARTYPE  vtNew
);

Parameters

pvarDst

[in, out] A variant to contain the value represented by pvarSrc, but with the type specified by vtNew.

pvarSrc

[in] A variant value to change into a new type.

lcid

[in] The locale context to use when converting the arguments to or from strings.

vtNew

[in] Specifies the type for pvarDst to become.

Expand image Return Value

The method returns an HRESULT. Possible values include, but are not limited to, those in the following table.

Value | Description
S_OK | The method succeeded.

Expand image Remarks

The pvarDst and pvarSrc arguments may be equal, in which case the original value is overwritten. This method passes pvarDst to the VariantClear function, and consequently pvarDst should be initialized to a valid value.

Expand image See Also

Reference

IVariantChangeType Interface


Object variable not set

Visual Basic Scripting Edition
Object variable not set
See Also

You attempted to use an object property without a valid object. If you leave out the Set statement, an error will be generated on the reference to the object.

To correct this error

  • Specify a reference for the object variable.

See Also

Reference

Property Set Statement


Expected literal constant

Visual Basic Scripting Edition
Expected literal constant
See Also

You declared a constant, but assigned it a variable expression (a value that can change). Constants cannot contain runtime code.

To correct this error

  • Do not use expressions when declaring constants.

See Also

Reference

Const Statement (VBScript)

Concepts

Constants (VBScript)
VBScript Constants


Out of stack space

Visual Basic Scripting Edition
Out of stack space

You have too many deeply nested procedures. Every time your code jumps to a procedure, the contents of its local variables are pushed onto the stack. The stack is a working area of memory that grows and shrinks in size dynamically with the demands of your executing script.

To correct this error

  • Check that procedures are not deeply nested.

  • Make sure recursive (reentrant) procedures do not call themselves extremely often.

  • Make sure recursive procedures terminate properly.


Array length must be a finite positive integer

JScript
Array length must be a finite positive integer
See Also

You are calling the Array constructor with an argument that is not a whole number (whole numbers consist of zero plus the set of positive integers).

To correct this error

  • Use positive integers only when creating a new Array object. If you want to create an array with a single element that is not an integer, do it in a two-step process. First create an array with one element, then place the value in the first element (array[0]). The following is an example that generates this error.

    CopyCode image Copy Code
    var piArray = new Array(3.14159);

    The following example demonstrates the correct way to specify an array with a single numeric element.

    CopyCode image Copy Code
    var piArray = new Array(1);
piArray [0] = 3.14159;

    There is no upper limit for the size of an array, other than the maximum integer value (approximately 4 billion).

See Also

Concepts

Using Arrays (JScript 5.6)


Expected 'While' or 'Until'

Visual Basic Scripting Edition
Expected 'While' or 'Until'
See Also

You created a Do loop, but did not include the associated While or Until keywords. The test condition of a Do loop requires either a While or an Until keyword in the test condition statement. The following demonstrates the correct structure of a Do loop.

CopyCode image Copy Code
      Do [{While | Until} condition]
   [statements]
   [Exit Do]
   [statements]
Loop

Or, you can use this syntax:

CopyCode image Copy Code
      Do
   [statements]
   [Exit Do]
   [statements]
Loop [{While | Until} condition]

To correct this error

  • Make sure that the Do loop includes all the necessary parts.

See Also

Reference

Do...Loop Statement
For...Next Statement
For...Next Statement
While...Wend Statement
Exit Statement

Concepts

Looping Through Code


Expected ']' in regular expression (JScript)

JScript
Expected ']' in regular expression (JScript)
See Also

You attempted to create a character class for a regular expression match, but did not include the right bracket. Individual literal character combinations can be assembled into character classes by placing them within brackets. A character class matches any one character it contains. For example, /[abc]/ matches any one of the letters "a", "b", or "c".

To correct this error

  • Add the right bracket to the regular expression.

    Note Note

    If you want to match a single bracket, escape it with a backslash - \[ - so it is not interpreted as a special character by JScript.

See Also

Reference

Regular Expression Object (JScript 5.6)
Regular Expression Syntax (Scripting)


Object not safe for scripting

Visual Basic Scripting Edition
Object not safe for scripting

You attempted to use an object that has not been marked safe for scripting. The set of objects that are safe to create is determined by the host. Generally, objects that allow untrusted scripts to do harmful actions (like access the hard disk) are considered unsafe.

For example, the FileSystemObject is not safe to run using Microsoft Internet Explorer as your client, but you can use this object on your local machine with Windows Script Host.

To correct this error

  • Make sure you are using a safe object.

  • Contact the developer of the object to see if there is a safe version.

  • You can find out if an object is safe by reading the object's documentation.


Class not defined

Visual Basic Scripting Edition
Class not defined
See Also

You made a reference to a class (with a New or Set statement) without first defining the class.

To correct this error

  • Make sure you define the class before you reference it.

See Also

Reference

Set Statement


Unknown runtime error

Visual Basic Scripting Edition
Unknown runtime error

An error occurred that was not recognized.

To correct this error

  • There is no course of action you can take to correct this error.


Invalid 'for' loop control variable

Visual Basic Scripting Edition
Invalid 'for' loop control variable
See Also

You created a For...Next loop that has the same control variable as a loop it is nested inside. Alternately, you may have created a For...Next loop with an illegal control variable. The following demonstrates the correct structure of a For...Next loop.

CopyCode image Copy Code
      For counter = start To end [Step step]
    [statements]
    [Exit For]
    [statements]
Next

To correct this error

  • Rename the control variable in your For...Next loop to something unique within the scope of the outermost loop.

See Also

Reference

For...Next Statement
Do...Loop Statement
Exit Statement
For Each...Next Statement
While...Wend Statement

Concepts

Looping Through Code


Expected ')' (JScript)

JScript
Expected ')' (JScript)

You attempted to enclose an expression within a set of parentheses, but did not include the closing parenthesis. Some expression must be enclosed within a set of opening and closing parentheses. Notice the use of parentheses in the following example.

CopyCode image Copy Code
for (initialize; test; increment) {
statement;
}

To correct this error

  • Add the right parentheses to the evaluation expression.


Object member expected

JScript
Object member expected
See Also

You attempted to perform an operation on an object's data member, but the member does not exist.

To correct this error

  • Ensure you typed the name of the data member correctly.

See Also

Reference

Object Object (JScript 5.6)

Concepts

Objects (JScript 5.6)


Operator Summary (JScript 5.6)

JScript
Operator Summary (JScript 5.6)
DropDown image

The following tables list JScript operators in their respective categories.

Computational Operators

Operator | Symbol
Addition | +
Decrement | --
Division | /
Increment | ++
Modulus | %
Multiplication | *
Subtraction | -
Unary negation | -

Logical Operators

Operator | Symbol
Comma | ,
Conditional (Ternary) | ?:
Equality | ==
Greater than | >
Greater than or equal to | >=
Identity | ===
Inequality | !=
Less than | <
Less than or equal to | <=
Logical AND | &&
Logical NOT | !
Logical Or | ||
Nonidentity | !==

Bitwise Operators

Operator | Symbol
Bitwise AND | &
Bitwise Left Shift | <<
Bitwise NOT | ~
Bitwise Or | |
Bitwise Right Shift | >>
Bitwise XOR | ^
Unsigned Right Shift | >>>

Assignment Operators

Assignment Operators

Compound Assignment Operators

Miscellaneous Operators

delete

instanceof

new

typeof

void

Requirements

Version 1


Class initialize or terminate do not have arguments

Visual Basic Scripting Edition
Class initialize or terminate do not have arguments
See Also

Your script has a class definition with the Class_Initialize event, or the Class_Terminate event. You specified one or more parameters for either of these procedures. Never specify parameters for either one of these procedures.

To correct this error

  • Remove the parameters from the class definition.

See Also

Reference

Initialize Event
Terminate Event


Name redefined

Visual Basic Scripting Edition
Name redefined

You declared an identifier with a name you have already used somewhere else in your script.

To correct this error

  • Rename the identifier to something unique within the global scope of your script.


Identifier too long

Visual Basic Scripting Edition
Identifier too long
See Also

You created a variable or function name that contains too many characters. The limit is 255 characters.

To correct this error

  • Choose a shorter name.

See Also

Reference

Dim Statement
Public Statement
Private Statement

Concepts

VBScript Variables
VBScript Data Types


String expected

JScript
String expected
See Also

You attempted to invoke the String.prototype.toString or String.prototype.valueOf method on an object of a type other than String. The object of this type of invocation must be of type String.

To correct this error

  • Only invoke the String.prototype.toString or String.prototype.valueOf methods on objects of type String.

See Also

Reference

String Object (JScript 5.6)
toString Method (JScript 5.6)


Invalid range in character set (VBScript)

Visual Basic Scripting Edition
Invalid range in character set (VBScript)
See Also

You attempted to create a regular expression with invalid characters. Regular expressions are composed of alphanumeric and meta characters.

To correct this error

  • Use only valid regular expression characters to compose your regular expression.

See Also

Concepts

Regular Expression (RegExp) Object


Expected 'To'

Visual Basic Scripting Edition
Expected 'To'
See Also

You created a For...Next loop, but did not include the To keyword in the first line. The first line of a For...Next loop must include the To keyword. The following demonstrates the correct structure of a For...Next loop.

CopyCode image Copy Code
      For counter = start To end [Step step]
    [statements]
    [Exit For]
    [statements]
Next

To correct this error

  • Make sure that the For...Next loop includes all the necessary parts.

See Also

Reference

For...Next Statement
For Each...Next Statement
Do...Loop Statement
Exit Statement
For...Next Statement
While...Wend Statement


Object expected

JScript
Object expected
See Also

You attempted to invoke the Object.prototype.toString or Object.prototype.valueOf method on an object of a type other than Object. The object of this type of invocation must be of type Object.

To correct this error

  • Only invoke the Object.prototype.toString or Object.prototype.valueOf methods on objects of type Object.

See Also

Reference

Object Object (JScript 5.6)

Concepts

Objects (JScript 5.6)


An exception occurred

Visual Basic Scripting Edition
An exception occurred
See Also

Your script made a call to a COM object, which in turn, threw an exception.

To correct this error

  • Unless this call was generated by the Raise method, contact the developer of the COM object generating the error.

  • Contact Microsoft Product Support Services to report the conditions under which this error message appeared.

See Also

Reference

Raise Method

Concepts

Err Object (VBScript)


Nothing Keyword

Visual Basic Scripting Edition
Nothing Keyword
See Also
DropDown image

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:

CopyCode image Copy Code
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

Reference

Dim Statement
Set Statement


Expected 'Property'

Visual Basic Scripting Edition
Expected 'Property'
See Also

You created a Property procedure (Property Let, Property Set, or Property Get), but did not terminate the procedure with the End Property statement. Property procedures must be terminated with an End Property statement.

To correct this error

  • Make sure you terminate your Property procedure with the End Property statement.

See Also

Reference

Property Let Statement
Property Set Statement
Property Get Statement


Label redefined

JScript
Label redefined
See Also

You created a new label, but gave it the name of an existing label. Labels can be used to mark blocks of code, but within a specified scope, they must be unique.

To correct this error

  • Ensure that all labels you use in your programs are unique within their respective scopes.

See Also

Reference

Labeled Statement (JScript 5.6)
switch Statement (JScript 5.6)
break Statement (JScript 5.6)
continue Statement (JScript 5.6)


Expected ']'

JScript
Expected ']'
See Also

You made a reference to an array element, but did not include the right bracket. Any expression that refers to an array element must include both opening and closing brackets.

To correct this error

  • Add the right bracket to the expression that refers to the array element.

See Also

Reference

Array Object (JScript 5.6)

Concepts

Using Arrays (JScript 5.6)


Undefined identifier

JScript
Undefined identifier
See Also

You attempted to use an identifier that the JScript compiler does not recognize. The undefined value is returned whenever you use:

  • a variable that does not exist,

  • a variable that has been declared, but never had a value assigned to it,

  • an object property that does not exist.

To correct this error

  • Declare the variable with a var statement (as in var x;).

See Also

Concepts

JScript Variables
Variable Scope


Expected 'Case'

Visual Basic Scripting Edition
Expected 'Case'
See Also

You created a SelectEnd Select construct, but did not include any Case statements. The following demonstrates the correct usage of the SelectEnd Select construct.

CopyCode image Copy Code
      Select Case testexpression
   [Case expressionlist-n
      [statements-n]] . . .
   [Case Else expressionlist-n
      [elsestatements-n]]
End Select

To correct this error

  • Make sure that the SelectEnd Select construct includes all the necessary parts.

See Also

Reference

Select Case Statement


Expected constant

JScript
Expected constant
See Also

You attempted to use a (non-conditional compilation) variable in a conditional compilation test statement. Conditional compilation test statements must evaluate to a constant.

To correct this error

  • Replace the variable with a literal.

  • Replace the variable with a conditional compilation variable.

See Also

Concepts

Conditional Compilation (JScript 5.6)
Conditional Compilation Variables (JScript 5.6)


Illegal assignment (VBScript)

Visual Basic Scripting Edition
Illegal assignment (VBScript)
See Also

You attempted to use a read-only identifier in the left-hand side of an assignment operation. You cannot assign a value to a read-only identifier.

To correct this error

  • Use read-only identifiers in the right-hand side of an assignment operation only.

See Also

Reference

Assignment Operator (=) (VBScript)
Comparison Operators (VBScript)
Operator Precedence (VBScript)
Set Statement

Other Resources

Operator Summary (VBScript)


Can't have 'break' outside of loop

JScript
Can't have 'break' outside of loop
See Also

You attempted to use the break keyword outside of a loop. The break keyword is used to terminate a loop or switch statement. It must be embedded in the body of a loop or switch statement. However, a label can follow the break keyword.

CopyCode image Copy Code
break labelname;

You only need the labeled form of the break keyword when you are using nested loops or switch statements and need to break out of a loop that is not the innermost one.

To correct this error

  • Make sure the break keyword appears inside an enclosing loop or switch statement.

See Also

Reference

break Statement (JScript 5.6)

Concepts

Controlling Program Flow
Troubleshooting Your Scripts (JScript 5.6)


Array or arguments object expected

JScript
Array or arguments object expected
See Also

You did not supply an array as an argument. This error applies to the Function.prototype.apply method only. If specified, the second argument to this function must be either an Array object or an Arguments object.

To correct this error

  • Specify either an Array or an Arguments object as the second argument.

See Also

Reference

apply Method (JScript 5.6)

Concepts

Using Arrays (JScript 5.6)
Functions (JScript 5.6)


Variable is undefined

Visual Basic Scripting Edition
Variable is undefined
See Also

You used the Option Explicit statement at the beginning of your script, but later attempted to use an undeclared variable name. When you use the Option Explicit statement, you must explicitly declare all variables using the Dim, Private, Public, or ReDim statements.

To correct this error

  • When using the Option Explicit statement, make sure you declare all variables using the Dim, Private, Public, or ReDim statement.

See Also

Reference

Option Explicit Statement

Concepts

VBScript Variables


No Topics for Index Entry

Visual Studio
No Topics for Index Entry
See Also
DropDown image

The index entry you selected has no target topics associated with it.

To view topics related to the index entry

  • Click one of the child items listed below the index entry.

See Also

Other Resources

Index Search Tips


The URI to be decoded is not a valid encoding

JScript
The URI to be decoded is not a valid encoding
See Also

You attempted to decode an improperly formed URI (Uniform Resource Identifier). URIs have a special syntax; most non-alphanumeric characters must be encoded before they can be used in a URI. You can use the encodeURI and encodeURIComponent methods to create a URI from a normal JScript string.

A complete URI is composed of a sequence of components and separators. The general form is:

CopyCode image Copy Code
<Scheme>:<first>/<second>;<third>?<fourth>

The names in angle brackets represent components, and the ":", "/", ";" and "?" are reserved characters used as separators.

To correct this error

  • Ensure you are trying to decode valid URIs only. You cannot decode normal JScript strings, as they may contain invalid characters.

See Also

Reference

decodeURI Method (JScript 5.6)
decodeURIComponent Method (JScript 5.6)


Expected ']' in regular expression (VBScript)

Visual Basic Scripting Edition
Expected ']' in regular expression (VBScript)
See Also

You attempted to create a character class for a regular expression match, but did not include the right bracket. Individual literal character combinations can be assembled into character classes by placing them within brackets. A character class matches any one character it contains. For example, /[abc]/ matches any one of the letters "a", "b", or "c".

To correct this error

  • Add the right bracket to your regular expression.

See Also

Concepts

Regular Expression (RegExp) Object


Boolean expected

JScript
Boolean expected
See Also

You attempted to invoke the Boolean.prototype.toString or Boolean.prototype.valueOf method on an object of a type other than Boolean. The object of this type of invocation must be of type Boolean. For example:

CopyCode image Copy Code
var o = new Object;
o.f = Boolean.prototype.toString;
o.f();

To correct this error

  • Only invoke the Boolean.prototype.toString or Boolean.prototype.valueOf methods on objects of type Boolean.

See Also

Reference

Boolean Object (JScript 5.6)

Concepts

Data Types (JScript 5.6)
Controlling Program Flow
Copying, Passing, and Comparing Data (JScript 5.6)


Unexpected 'Next'

Visual Basic Scripting Edition
Unexpected 'Next'
See Also

You created a For...Next or a For Each...Next construct, but did not include the For statement. For example, you could have attempted to remove a For...Next construct, but did not remove the Next statement. The following demonstrates the correct usage of the For...Next construct.

CopyCode image Copy Code
      For counter = start To end [Step step]
    [statements]
    [Exit For]
    [statements]
Next

To correct this error

  • Add the For statement (the loop control statement).

  • Remove the extra Next statement.

See Also

Reference

For...Next Statement
For Each...Next Statement
Exit Statement

Concepts

Looping Through Code


Expected '=' (VBScript)

Visual Basic Scripting Edition
Expected '=' (VBScript)
See Also

You used the Set statement, but did not include the =.

To correct this error

  • Use the full syntax of the Set statement.

See Also

Reference

Set Statement


Expected ')' (VBScript)

Visual Basic Scripting Edition
Expected ')' (VBScript)
See Also

You attempted to enclose an expression within a set of parentheses, but did not include the closing parenthesis). Some expressions must be enclosed within a set of opening and closing parentheses.

To correct this error

  • Add the right (closing) parenthesis) to the evaluation expression.

See Also

Reference

Operator Precedence (VBScript)


Object not safe for creating

Visual Basic Scripting Edition
Object not safe for creating

You attempted to use an object that has not been marked safe for creation. The set of objects that are safe to create is determined by the host. Generally, objects that allow untrusted scripts to do harmful actions (like access the hard disk) are considered unsafe.

For example, the FileSystemObject is not safe to run using Microsoft Internet Explorer as your client, but you can use this object on your local machine with Windows Script Host.

To correct this error

  • Make sure you are using a safe object.

  • Contact the developer of the object to see if there is a safe version.

  • You can find out if an object is safe by reading the object's documentation.


Conditional compilation is turned off

JScript
Conditional compilation is turned off
See Also

You attempted to use a conditional compilation variable without first turning conditional compilation on. Turning on conditional compilation tells the JScript compiler to interpret identifiers beginning with @ as conditional compilation variables. You do this by beginning your conditional code with the statement:

CopyCode image Copy Code
/*@cc_on @*/

To correct this error

  • Add the following statement to the beginning of your conditional code:

    CopyCode image Copy Code
    /*@cc_on @*/

See Also

Reference

@cc_on Statement (JScript 5.6)
@if Statement
@set Statement (JScript 5.6)

Concepts

Conditional Compilation (JScript 5.6)
Conditional Compilation Variables (JScript 5.6)


Expected hexadecimal digit

JScript
Expected hexadecimal digit
See Also

You created an incorrect Unicode escape sequence. Unicode escape sequences begin with \u, followed by exactly four hexadecimal digits (no more and no less). Unicode hexadecimal digits can contain only the numbers 0-9, the upper case letters A-F, and the lower case letters a-f. The following example demonstrates a correctly formed Unicode escape sequence.

CopyCode image Copy Code
z = "\u1A5F";

To correct this error

  • Be sure your Unicode hexadecimal digits begin with \u, contains only the numbers 0-9, the upper case letters A-F, the lower case letters a-f; and are grouped into four digits.

    Note Note

    If you want to use the literal text \u in a string, then use two backslashes - (\\u) - one to escape the first backslash.

See Also

Concepts

Data Types (JScript 5.6)


Expected statement

Visual Basic Scripting Edition
Expected statement
See Also

The string you passed as an argument to the Execute statement cannot be parsed as a statement. The Execute statement can be used to dynamically execute VBScript code. For example, consider the following VBScript code.

CopyCode image Copy Code
Execute "msgbox 1"  'This works because msgbox is a statement.
Execute "5*4"       'This fails because 5*4 cannot be interpreted as a statement.

The Expected statement error is also generated during the compilation of any script code that expects a statement, not just by Execute and Eval. For example, the following code causes this error in Internet Explorer,

CopyCode image Copy Code
<html>
<script language=vbscript>
    5*4
</script>
</html>

Notice that there are two distinct and unrelated Execute statements in VBScript,

  • the Execute statement that compiles and executes statements on the fly,

  • the Regular Expression Execute method.

To correct this error

  • Confirm that the string being passed to Execute is a statement.

  • If the string you want to evaluate is an expression, use Eval.

See Also

Reference

Execute Statement
Eval Function


Sub or function not defined (VBScript)

Visual Basic Scripting Edition
Sub or function not defined (VBScript)
See Also

You attempted to invoke a procedure that does not exist.

To correct this error

  • Check the spelling of the procedure and make sure it is typed correctly.

See Also

Reference

Sub Statement
Function Statement (VBScript)


Argument not optional (VBScript)

Visual Basic Scripting Edition
Argument not optional (VBScript)
See Also

You invoked a procedure, but used the wrong number of arguments. The number of arguments passed to a procedure must match the number of parameters in the procedure's definition.

To correct this error

  • Check the function signature to make sure you supplied all the necessary arguments.

See Also

Concepts

VBScript Procedures


Object not a collection

Visual Basic Scripting Edition
Object not a collection

You attempted to perform an operation that is exclusive to Collection objects, on an object that is not a Collection object. Some properties, methods, and operations only apply to Collection objects. A Collection object is an object that contains a set of related objects. An object's position within a Collection object can change whenever a change occurs in the collection; therefore, the position of any one object in the Collection object may vary.

To correct this error

  • Check the spelling of the object or property name.

  • Verify that the object is a Collection object.

  • Look at the Add method used to add the object to the collection to be sure the syntax is correct and that any identifiers were spelled correctly.


Label not found

JScript
Label not found
See Also

You made a reference to a label that does not exist. Labels can be used to mark blocks of code, but within a specified scope, must be unique.

To correct this error

  • Check to make sure you did not misspell the label name.

  • Ensure all label references are made to labels that have been defined in the current scope (this includes forward definitions).

See Also

Reference

Labeled Statement (JScript 5.6)
switch Statement (JScript 5.6)
break Statement (JScript 5.6)
continue Statement (JScript 5.6)


This array is fixed or temporarily locked

Visual Basic Scripting Edition
This array is fixed or temporarily locked
See Also

You attempted to use ReDim to change the number of elements in an array of constant size. Arrays declared as dynamic, or arrays within Variant variables can be temporarily locked.

To correct this error

  • If the array is declared within a procedure, use the function ReDim to change it from static to dynamic.

  • If the array is declared at the module level, declare the array without specifying the number of elements.

See Also

Reference

Array Function
Dim Statement
ReDim Statement
Set Statement
Private Statement
Public Statement


For loop not initialized (VBScript)

Visual Basic Scripting Edition
For loop not initialized (VBScript)
See Also

The sequence of execution in your script jumped into the middle of a For...Next loop. This causes an error because For...Next loop counters must be initialized. The following demonstrates the correct structure of a For...Next loop.

CopyCode image Copy Code
      For counter = start To end [Step step]
    [statements]
    [Exit For]
    [statements]
Next

To correct this error

  • Remove the jump into the For...Next loop.

  • Make sure that the For...Next loop includes all the necessary parts.

See Also

Reference

For...Next Statement
Do...Loop Statement
Exit Statement
For Each...Next Statement
While...Wend Statement

Concepts

Looping Through Code


Expected '@'

JScript
Expected '@'
See Also

You attempted to create a variable to be used with conditional compilation statements using the @set statement, but did not place an at sign "@" before the variable name.

To correct this error

  • Add an at sign "@" immediately before the variable name. For example:

    CopyCode image Copy Code
    @set @myvar = 1

See Also

Reference

@set Statement (JScript 5.6)

Concepts

Conditional Compilation (JScript 5.6)
Conditional Compilation Variables (JScript 5.6)


Wrong number of arguments or invalid property assignment

Visual Basic Scripting Edition
Wrong number of arguments or invalid property assignment
See Also

You invoked a procedure, but used either the wrong procedure name, the wrong number of arguments for this procedure, or wrong argument types.

The number of arguments passed to a procedure must match the number of parameters in the procedure's definition.

To correct this error

  • Check to see that the argument list you are passing to the procedure matches that in the procedure declaration or definition.

See Also

Reference

Function Statement (VBScript)
Sub Statement
Call Statement


Expected identifier (JScript)

JScript
Expected identifier (JScript)
See Also

You used something other than an identifier in a context where one was required. An identifier can be:

  • a variable,

  • a property,

  • an array,

  • or a function name.

To correct this error

  • Change the expression so an identifier appears to the left of the equal sign.

See Also

Concepts

Using Arrays (JScript 5.6)


Expected 'End'

Visual Basic Scripting Edition
Expected 'End'
See Also

You created a construct, but did not properly terminate it. The following table lists the VBScript constructs that must end with an End statement.

Construct | Terminating Statement
Sub | End Sub
Function | End Function
If | End If
Class | End Class
With | End With
Select | End Select

To correct this error

  • Terminate a Sub procedure with an associated End Sub statement.

  • Terminate a Function procedure with an associated End Function statement.

  • Terminate an If statement with an associated End If statement.

  • Terminate a Class statement with an associated End Class statement.

  • Terminate a With statement with an associated End With statement.

  • Terminate a Select Statement with an associated End Select statement.

See Also

Reference

Sub Statement
Function Statement (VBScript)


Class doesn't support Automation

Visual Basic Scripting Edition
Class doesn't support Automation
See Also

You attempted to access a property or method of an object that does not support Automation. You can create and pass a pointer to an object that does not support Automation, but you cannot access its properties and methods.

To correct this error

  • Check the documentation of the application that created the object for limitations on the use of Automation with this class.

    Note

    Note The object may have been created using CreateObject, but it also may have been introduced by way of the host object model.

See Also

Reference

CreateObject Function


Expected ')' in regular expression (VBScript)

Visual Basic Scripting Edition
Expected ')' in regular expression (VBScript)
See Also

You attempted to create a regular expression sub expression, but did not include the closing parenthesis ")". Parentheses have several purposes in regular expressions. Primarily, they group separate items into a single sub expression, so that the items can be treated as a single unit by *, +, ?, and so on.

To correct this error

  • Add the right (closing) parenthesis ")" to your regular expression sub expression.

See Also

Concepts

Regular Expression (RegExp) Object


Expected 'While,' 'Until,' or end of statement

Visual Basic Scripting Edition
Expected 'While,' 'Until,' or end of statement
See Also

You created a Do loop, but did not include the associated While or Until keywords. The test condition of a Do loop requires either a While or an Until keyword in the test condition statement. The following demonstrates the correct structure of a Do loop.

CopyCode image Copy Code
      Do [{While | Until} condition]
   [statements]
   [Exit Do]
   [statements]
Loop

Or, you can use this syntax:

CopyCode image Copy Code
      Do
   [statements]
   [Exit Do]
   [statements]
Loop [{While | Until} condition]

To correct this error

  • Make sure that the Do loop includes all the necessary parts.

  • Terminate the Do loop with either the While or Until keywords.

See Also

Reference

Do...Loop Statement
For...Next Statement
For...Next Statement
While...Wend Statement
Exit Statement

Concepts

Looping Through Code


Type mismatch

Visual Basic Scripting Edition
Type mismatch
See Also

You attempted to compare values of incompatible data types. For example, comparing a string and a numeric value.

To correct this error

  • Make sure the data types match when performing comparisons.

  • Cast one of the values to the data type of the other, and try the comparison again.

See Also

Concepts

VBScript Variables


Object doesn't support this action

Visual Basic Scripting Edition
Object doesn't support this action
See Also

You attempted to reference a method or property that is not supported by this object. Not all objects support all actions.

To correct this error

  • Check the properties and methods to ensure there were no typing errors.

  • See the object's documentation for more information.

See Also

Reference

CreateObject Function
GetObject Function

Concepts

Using VBScript with Objects


ActiveX component can't create object

Visual Basic Scripting Edition
ActiveX component can't create object
See Also

The VBScript 5.5 runtime could not instantiate the object for you because the object's class is not registered in the system registry, or one or more of the associated dynamic-link libraries (DLLs) are not available. Alternately, a DLL required by the object may be unusable, either because it can't be found, or it is corrupted.

To correct this error

  • Make sure all associated DLLs are available. For example, the Data Access Object (DAO) requires supporting DLLs that vary among platforms. You may have to rerun the setup program for such an object.

  • Internet Explorer may be trying to create an object for you, but you do not have the correct security permissions set in Internet Explorer. Reset the Internet Explorer security setting and try again.

See Also

Concepts

Using VBScript with Objects


'Default' specification must also specify 'Public'

Visual Basic Scripting Edition
'Default' specification must also specify 'Public'
See Also

You defined a property as Default, but not as Public. If you define a property as Default, you must define it as Public as well.

To correct this error

  • Define all Default properties as Public.

See Also

Reference

Function Statement (VBScript)


Out of Memory

Visual Basic Scripting Edition
Out of Memory
See Also

You allocated as much memory as is available in this computer system. This could be a result of a dynamically allocated array growing too large, or the instantiation of a large number of objects.

To correct this error

  • Use the Erase statement to reallocate dynamic-array storage space.

  • Use the ReDim statement to reallocate storage space.

  • Close any unnecessary applications, documents, or source files that are open.

See Also

Reference

Erase Statement
Dim Statement
ReDim Statement
CreateObject Function

Concepts

Nothing Keyword


Expected 'Then'

Visual Basic Scripting Edition
Expected 'Then'
See Also

You created a If...Then...Else construct, but did not include the Then keyword in the first line. The following demonstrates the correct structure of a If...Then...Else construct.

CopyCode image Copy Code
      If condition Then statements [Else elsestatements ]

Or, you can use the block form syntax:

CopyCode image Copy Code
      If condition Then
   [statements]
[ElseIf condition-n Then
   [elseifstatements]] . . .
[Else
   [elsestatements]]
End If

To correct this error

  • Make sure that the If...Then...Else construct includes all the necessary parts.

See Also

Reference

If...Then...Else Statement
Select Case Statement

Concepts

Using Conditional Statements


Cannot use parentheses when calling a Sub

Visual Basic Scripting Edition
Cannot use parentheses when calling a Sub
See Also

You invoked a subroutine without the Call statement, but used parentheses (). When calling a subroutine without the Call statement, do not use parentheses.

To correct this error

  • Remove the parentheses from the subroutine invocation.

  • Use the Call statement to invoke the subroutine instead.

See Also

Reference

Call Statement
Sub Statement


Expected '(' (VBScript)

Visual Basic Scripting Edition
Expected '(' (VBScript)
See Also

You did not include the opening parenthesis "(" when you created a procedure declaration,

CopyCode image Copy Code
Sub mysample x // x should be enclosed within parentheses.
End Sub

or used the redim statement.

CopyCode image Copy Code
Redim x // x should be enclosed within parentheses.

To correct this error

  • Add the left (opening) parenthesis "(".

See Also

Reference

Operator Precedence (VBScript)


Expected 'Wend'

Visual Basic Scripting Edition
Expected 'Wend'
See Also

You created a While...Wend loop, but did not properly terminate the loop. A While...Wend loop must be terminated with an associated Wend statement. The following demonstrates the correct structure of a While...Wend loop.

CopyCode image Copy Code
      While condition
   Version [statements]
Wend

To correct this error

  • Make sure that the While...Wend loop includes all the necessary parts.

See Also

Reference

While...Wend Statement
Do...Loop Statement
For...Next Statement
For Each...Next Statement
Exit Statement

Concepts

Looping Through Code


Expected 'while'

JScript
Expected 'while'
See Also

You did not include the while condition in a do...while loop. A do statement must have a corresponding while test at the end of the code block.

To correct this error

  • Include the while test statement after the closing curly brace.

See Also

Reference

while Statement (JScript 5.6)

Concepts

Controlling Program Flow


Expected Let or Set or Get in property declaration

Visual Basic Scripting Edition
Expected Let or Set or Get in property declaration
See Also

You created a Property Let, Property Set, or Property Get statement, but did not include the keywords Let, Set, or Get. The Property statement must be followed by Let, Set, or Get.

To correct this error

  • Make sure the Property statement is followed by Let, Set, or Get.

See Also

Reference

Property Let Statement
Property Set Statement
Property Get Statement


Invalid range in character set (JScript)

JScript
Invalid range in character set (JScript)
See Also

You attempted to create a regular expression with an invalid character set range. Character sets must range from single characters only, such as a-z or 0-9; you cannot include character classes such as \w in a character set. The first character in the range must also come before the second character in the range. For example:

CopyCode image Copy Code
var good = /[a-z]/;     // A valid character range - a comes before z.
var notGood = /[z-a]/;  // An invalid character range - z does not come before a.

To correct this error

  • Use only single characters to compose your regular expression character set, and make sure they are in the correct order.

See Also

Reference

Regular Expression Object (JScript 5.6)
Regular Expression Syntax (Scripting)


File name or class name not found during Automation operation (VBScript)

Visual Basic Scripting Edition
File name or class name not found during Automation operation (VBScript)
See Also

You used the GetObject or the LoadPicture function, but supplied an unrecognizable class or file name as a parameter. The GetObject function requires either a full path and name of the file containing the object to retrieve, or the name of a class that is registered with the system. The LoadPicture function requires the full path and name of the picture file to retrieve.

To correct this error

  • Check the names for typing mistakes, and try again.

  • Make sure the name used for the class parameter matches one registered with the system.

See Also

Reference

GetObject Function
CreateObject Function
LoadPicture Function


Named argument not found

Visual Basic Scripting Edition
Named argument not found
See Also

You invoked a procedure, specifying a particular argument, but the procedure was not defined to accept an argument by that name. A named argument cannot be used in a procedure invocation unless it appears in the procedure definition.

To correct this error

  • Check to see that the argument name is spelled correctly, and try invoking the procedure again.

See Also

Concepts

VBScript Coding Conventions


Expected ')' in regular expression (JScript)

JScript
Expected ')' in regular expression (JScript)
See Also

You attempted to create a regular expression capture, assertion, or group, but did not include the closing parenthesis. Parentheses have several purposes in regular expressions. Primarily, they are used to capture sub-expressions, to specify assertions, or to group patterns together so that the items can be treated as a single unit by *, +, ?, and so on.

To correct this error

  • Add the rightmost closing parentheses.

    Note Note

    If you want to match a single parenthesis, escape it with a backslash - \( - so that it is not interpreted as a special character by JScript.

See Also

Reference

Regular Expression Object (JScript 5.6)
Regular Expression Syntax (Scripting)


Can't perform requested operation (VBScript)

Visual Basic Scripting Edition
Can't perform requested operation (VBScript)

The execution of your script cannot continue because the host halted the script engine. The host did not specify an explicit error code to return.

To correct this error

  • The resolution of this error is host dependent.


Expected ';'

JScript
Expected ';'
See Also

You attempted to place more than one statement on a line, but did not separate them with semicolons. Semicolons are used to terminate statements. Although you can place several statements on a single line, each one must be delimited from the next with a semicolon.

To correct this error

  • Mark the end of each statement with a semicolon.

  • Make sure your function calls use parentheses properly.

  • Make sure you did not forget the semicolons inside the header of a for loop.

See Also

Concepts

Writing JScript Code


'return' statement outside of function

JScript
'return' statement outside of function
See Also

You used a return statement in the global scope of your code. The return statement should only appear within the body of a function.

Invoking a function with the () operator is an expression. All expressions have values; the return statement is used to specify the value retuned by a function. The general form is:

CopyCode image Copy Code
      return [ expression ];

When the return statement is executed, expression is evaluated and returned as the value of the function. If there is no expression, undefined is returned.

Execution of the function stops when the return statement is executed, even if there are other statements still remaining in the function body. The exception to this rule is if the return statement occurs within a try block, and there is a corresponding finally block, the code in the finally block will execute before the function returns.

If a function returns because it reaches the end of the function body without executing a return statement, the value returned is the undefined value (this means the function result cannot be used as part of a larger expression).

To correct this error

  • Remove the return statement from the main body of your code (the global scope).

See Also

Reference

return Statement (JScript 5.6)
Function Object (JScript 5.6)
caller Property (JScript 5.6)


Cannot have multiple default property/method in a Class

Visual Basic Scripting Edition
Cannot have multiple default property/method in a Class
See Also

In your class definition, you marked more than one property or method as the default. There can only be one default property and one default method in a class.

To correct this error

  • Make sure there is only one default property and one default method for this class.

See Also

Reference

Function Statement (VBScript)


Expected 'If'

Visual Basic Scripting Edition
Expected 'If'
See Also

You created an If...Then...Else block, but did not properly terminate the block. A block If statement must be the first statement on a line, and must end with an End If statement. The following demonstrates the correct structure of a If...Then...Else block.

CopyCode image Copy Code
      If condition Then
   [statements]
[ElseIf condition-n Then
   [elseifstatements]] . . .
[Else
   [elsestatements]]
End If

To correct this error

  • Check to see if you ended your block If statement with an End statement. If so, change it to an End If statement.

See Also

Reference

If...Then...Else Statement


Syntax error in regular expression (JScript)

JScript
Syntax error in regular expression (JScript)
See Also

The structure of your search string violates one or more of the grammatical rules of a JScript regular expression.

To correct this error

  • Ensure the structure of your regular expression search string adheres to the JScript regular expression syntax.

See Also

Reference

Regular Expression Object (JScript 5.6)
Regular Expression Syntax (Scripting)
compile Method (JScript 5.6)


Invalid number

Visual Basic Scripting Edition
Invalid number
See Also

A value in your expression is too large, or out of range.

To correct this error

  • Use a smaller value.

See Also

Reference

VarType Function

Concepts

VBScript Data Types


'Default' specification can only be on Property Get

Visual Basic Scripting Edition
'Default' specification can only be on Property Get
See Also

You used the Default reserved word on a Property Let or Property Set. You can only specify the Default reserved word for a Property Get.

To correct this error

  • Specify the Default reserved word on a Property Get only.

See Also

Reference

Property Let Statement
Property Set Statement
Property Get Statement


True Keyword

Visual Basic Scripting Edition
True Keyword
See Also
DropDown image

The True keyword has a value equal to -1.

See Also

Concepts

False (Windows Script Technologies)


Invalid use of 'Me' keyword

Visual Basic Scripting Edition
Invalid use of 'Me' keyword

You attempted to use Set to assign a value to the identifier Me. Me is a reserved identifier, and cannot be set.

To correct this error

  • Rename the variable to something other than Me.


Property Set or Let must have at least one argument

Visual Basic Scripting Edition
Property Set or Let must have at least one argument
See Also

You specified a property accessor to the handle Set of Let for a class with no arguments.

To correct this error

  • Add an argument to the property accessor.

See Also

Reference

Property Let Statement
Property Set Statement
Property Get Statement
Class Statement (VBScript)


Expected '(' (JScript)

JScript
Expected '(' (JScript)

You attempted to enclose an expression within a set of parentheses, but did not include the opening parenthesis. Some expressions must be enclosed within a set of opening and closing parentheses. Notice the use of parentheses in the following example.

CopyCode image Copy Code
for (initialize; test; increment) {
statement;
}

To correct this error

  • Add the left parenthesis to the evaluation expression.


Expected 'Sub'

Visual Basic Scripting Edition
Expected 'Sub'
See Also

You created a Sub procedure, but terminated it with the End keyword instead of the End Sub statement. A Sub procedure must include a terminating End Sub statement.

To correct this error

  • Terminate your Sub procedure with the End Sub statement.

See Also

Reference

Sub Statement
Call Statement
Dim Statement
Exit Statement
Function Statement (VBScript)


Object required

Visual Basic Scripting Edition
Object required

The object you supplied is not valid (or is not recognized as an object). References to properties and methods often require an explicit object qualifier.

To correct this error

  • Supply an object qualifier.

  • Check the spelling of the object qualifier.


Unterminated string constant (JScript)

JScript
Unterminated string constant (JScript)
See Also

You did not end your string constant with a closing quotation mark. String constants must be enclosed within a pair of quotation marks.

Note Note

You can use matching pairs of single or double quotation marks. Double quotation marks can be contained within strings surrounded by single quotation marks, and single quotation marks can be contained within strings surrounded by double quotation marks.

To correct this error

  • Add the closing quotation mark to the end of the string.

See Also

Reference

String Object (JScript 5.6)
toString Method (JScript 5.6)


Expected identifier (VBScript)

Visual Basic Scripting Edition
Expected identifier (VBScript)

You declared a variable, but used a VBScript reserved word for the name.

To correct this error

  • Choose another variable name (one that is not a VBScript reserved word).

  • Enclose the reserved word in [ ].


Syntax error in regular expression (VBScript)

Visual Basic Scripting Edition
Syntax error in regular expression (VBScript)
See Also

The structure of your search string violates one or more of the grammatical rules of a VBScript regular expression.

To correct this error

  • Ensure the structure of your regular expression search string adheres to the Perl regular expression syntax.

See Also

Concepts

Regular Expression (RegExp) Object


The URI to be encoded contains an invalid character

JScript
The URI to be encoded contains an invalid character
See Also

You attempted to encode a string as a URI (Uniform Resource Identifier), but it contained invalid characters. Although most characters are valid inside strings to be converted to URIs, some Unicode character sequences are illegal.

To correct this error

  • Ensure the string to be encoded contains only valid Unicode sequences. A complete URI is composed of a sequence of components and separators. The names in angle brackets represent components, and the ":", "/", ";" and "?" are reserved characters used as separators. The general form is:

    CopyCode image Copy Code
    <Scheme>:<first>/<second>;<third>?<fourth>

See Also

Reference

encodeURI Method (JScript 5.6)
encodeURIComponent Method (JScript 5.6)


Expected '=' (JScript)

JScript
Expected '=' (JScript)
See Also

You attempted to create a variable to be used with conditional compilation statements, but did not place an equal sign between the variable and the value you want to assign to it.

To correct this error

  • Add an equal sign. For example:

    CopyCode image Copy Code
    @set @myvar1 = 1

See Also

Concepts

Conditional Compilation (JScript 5.6)
Conditional Compilation Variables (JScript 5.6)


Expected '/'

JScript
Expected '/'
See Also

You attempted to create a regular expression literal, but did not include one of the slashes (/). Just as string literals are written as characters within a pair of quotation marks, regular expression literals are expressed as characters within a pair of slash (/) characters.

To correct this error

  • Insert a terminating forward slash to mark the end of the regular expression.

See Also

Reference

Regular Expression Object (JScript 5.6)
Regular Expression Syntax (Scripting)


Object doesn't support this property or method

Visual Basic Scripting Edition
Object doesn't support this property or method

You specified a property or method that does not exist for this automation object. Not all objects support all properties and methods.

To correct this error

  • Check the properties and methods to ensure there were no typing errors.

  • See the object's documentation for more information.


Expected end of statement

Visual Basic Scripting Edition
Expected end of statement
See Also

Text appears beyond the end of one of your statements.

To correct this error

  • Remove the extra text.

  • If you intended to comment your line of code, insert an apostrophe "'" at the end of the statement.

See Also

Concepts

VBScript Coding Conventions


Invalid or unqualified reference

Visual Basic Scripting Edition
Invalid or unqualified reference
See Also

You attempted to use the With statement on something other than an object. The With statement can only be used with non-null object values. The following demonstrates the correct structure of a With block.

CopyCode image Copy Code
      With object
   statements
End With

To correct this error

  • Specify an object for the With statement.

See Also

Reference

With Statement (VBScript)


Procedure call or argument is not valid

Visual Basic Scripting Edition
Procedure call or argument is not valid
See Also

One of the arguments you passed to a procedure exceeds the range of permitted values. Alternately, you may have attempted to call a procedure that is not valid on the current platform.

To correct this error

  • Check the procedure's range of permissible for arguments.

  • Check platform-specific information about the procedure.

See Also

Reference

Function Statement (VBScript)
Sub Statement
Call Statement

Concepts

VBScript Variables


'default' can only appear once in a 'switch' statement

JScript
'default' can only appear once in a 'switch' statement
See Also

You attempted to use the default statement more than once within a switch statement. The default case is always the last case statement in a switch statement (it is the fall-through case).

To correct this error

  • Remove any extra default case statements from your switch statement (use at most one default case statement in your switch statement).

See Also

Reference

switch Statement (JScript 5.6)

Concepts

Controlling Program Flow
JScript Reserved Words (JScript 5.6)


Syntax error (VBScript)

Visual Basic Scripting Edition
Syntax error (VBScript)
See Also

You created a statement that violates one or more of the grammatical rules of VBScript.

To correct this error

  • Double-check the number of elements that make up an expression.

  • Look for misdirected brackets.

See Also

Concepts

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


Variable uses an Automation type not supported in VBScript

Visual Basic Scripting Edition
Variable uses an Automation type not supported in VBScript
See Also

You attempted to use an unsupported data type from a type or object library. You cannot use all variables appearing in type or object libraries, in every programming language.

To correct this error

  • Only use variable types recognized by VBScript.

See Also

Concepts

VBScript Variables
VarType Constants


Illegal assignment (JScript)

JScript
Illegal assignment (JScript)
See Also

You attempted to assign a value to a read-only identifier. You cannot assign a value to a read-only identifier. For example, host defined objects and external COM objects.

To correct this error

  • Do not assign values to read-only identifiers.

See Also

Reference

Assignment Operator (=) (JScript 5.6)


Expected 'Next'

Visual Basic Scripting Edition
Expected 'Next'
See Also

You created a For...Next loop construct, but did not properly terminate the loop. A For...Next loop construct must end with a Next statement. The following demonstrates the correct structure of a For...Next loop construct.

CopyCode image Copy Code
      For counter = start To end [Step step]
    [statements]
    [Exit For]
    [statements]
Next

To correct this error

  • Make sure that the For...Next loop construct includes all the necessary parts.

See Also

Reference

For...Next Statement
Do...Loop Statement
Exit Statement
For Each...Next Statement
While...Wend Statement


Invalid character (VBScript)

Visual Basic Scripting Edition
Invalid character (VBScript)

You attempted to use Double Byte Character Set (DBCS) or other unsupported characters in an expression.

To correct this error

  • Enclose the unsupported characters in brackets [].


script56hxs {2DDA7CF9-E8CF-4df1-98E8-521EDE1C5FC7}
DropDown image

script56hxs {2DDA7CF9-E8CF-4df1-98E8-521EDE1C5FC7}

{2DDA7CF9-E8CF-4df1-98E8-521EDE1C5FC7}

{2DDA7CF9-E8CF-4df1-98E8-521EDE1C5FC7}

Full Text Search and Index Debug Topic graphic


Throw must be followed by an expression on the same source line

JScript
Throw must be followed by an expression on the same source line
See Also

You used the throw keyword, but did not follow it with an expression on the same source line. A throw statement consists of two parts: the throw keyword, followed by the expression to be thrown. For example:

CopyCode image Copy Code
if (denominator == 0) {
 throw new DivideByZeroException();
}

You cannot split these two components up.

To correct this error

  • Make sure that the throw keyword and the expression to be thrown appears on the same line.

See Also

Reference

Error Object (JScript 5.6)
throw Statement (JScript 5.6)
try...catch...finally Statement (JScript 5.6)


Invalid character (JScript)

JScript
Invalid character (JScript)
See Also

You composed an identifier using a character (or characters) not recognized as valid by the JScript compiler. Valid characters use the following rules:

  • The first character must be an ASCII letter (either uppercase or lowercase) or an underscore (_).

  • Subsequent characters can be ASCII letters, numbers, or underscores.

  • The identifier name cannot be a reserved word.

To correct this error

  • Avoid using characters that are not part of the JScript language definition.

See Also

Concepts

JScript Variables
Special Characters (JScript 5.6)
Data Types (JScript 5.6)


Division by zero (VBScript)

Visual Basic Scripting Edition
Division by zero (VBScript)

You created an expression that attempts to divide a number by zero. Division by zero yields an infinite (unusable) result.

To correct this error

  • Check the expression for typing or case mistakes.


Function does not have a valid prototype object

JScript
Function does not have a valid prototype object
See Also

You attempted to use instanceof to determine if an object was derived from a particular function class, but you redefined the object's prototype property as either null, or an external object type (both not valid JScript objects). An external object can be an object from the host object model (for example, Internet Explorer's document or window object), or an external COM object.

To correct this error

  • Ensure the function's prototype property refers to a valid JScript object.

See Also

Reference

Function Object (JScript 5.6)
prototype Property (JScript 5.6)


Internal error (VBScript)

Visual Basic Scripting Edition
Internal error (VBScript)
See Also

An internal fault occurred.

To correct this error

  • Unless this call was generated by the Raise method, contact Microsoft Product Support Services to report the conditions under which the message appeared.

See Also

Reference

Raise Method


Expected 'In'

Visual Basic Scripting Edition
Expected 'In'
See Also

You created a For EachNext block, but did not include the In keyword in the first line. The following demonstrates the correct structure of a For EachNext block.

CopyCode image Copy Code
      For Each element In group
   [statements]
   [Exit For]
   [statements]
Next [element]

To correct this error

  • Make sure that the For EachNext block includes all the necessary parts.

See Also

Reference

For Each...Next Statement
Do...Loop Statement
Exit Statement
For...Next Statement
While...Wend Statement


Number expected

JScript
Number expected
See Also

You attempted to invoke the Number.prototype.toString or Number.prototype.valueOf method on an object of a type other than Number. The object of this type of invocation must be of type Number.

To correct this error

  • Only invoke the Number.prototype.toString or Number.prototype.valueOf methods on objects of type Number.

See Also

Reference

Number Object (JScript 5.6)
number Property (JScript 5.6)


Expected 'Class'

Visual Basic Scripting Edition
Expected 'Class'
See Also

You created a Class procedure, but ended it with the End keyword, instead of the End Class statement. Always terminate a Class procedure with an End Class statement.

To correct this error

  • Terminate your Class procedure with the End Class statement.

See Also

Reference

Class Statement (VBScript)


Exception thrown and not caught

JScript
Exception thrown and not caught
See Also

You included a throw statement in your code, but it was not enclosed within a try block, or there was no associated catch block to trap the error. Exceptions are thrown from within the try block using the throw statement, and caught outside the try block with a catch statement.

To correct this error

  • Enclose code that can throw an exception in a try block, and ensure there is a corresponding catch block.

  • Make sure your catch statement expects the correct form of exception.

  • If the exception is rethrown, make sure there is another corresponding catch statement.

See Also

Reference

Error Object (JScript 5.6)
throw Statement (JScript 5.6)
try...catch...finally Statement (JScript 5.6)


Cannot assign to 'this'

JScript
Cannot assign to 'this'
See Also

You attempted to assign a value to this. this is a JScript keyword that refers to either:

  • the object currently executing a method,

  • the global object if there is no current method (or the method does not belong to any other object).

A method is a JScript function that is invoked through an object. Inside a method, the this keyword is a reference to the object the method was invoked through (which happens to be the object created by invoking the class constructor with the new operator).

Inside a method, you can use this to refer to the current object, but you cannot assign a new value to this.

To correct this error

  • Do not attempt to assign to this. To access a property or method of an instantiated object, use the dot operator (e.g., circle.radius).

    Note Note

    You cannot name a user-created variable this; it is a JScript reserved word.

See Also

Reference

this Statement (JScript 5.6)

Concepts

Troubleshooting Your Scripts (JScript 5.6)


Unexpected quantifier (JScript)

JScript
Unexpected quantifier (JScript)
See Also

When composing your regular expression search pattern, you created a pattern element with an illegal repetition factor. For example, the pattern

CopyCode image Copy Code
/^+/

is illegal because the element ^ (beginning of input) cannot have a repetition factor. The following table lists the elements that cannot have repetition factors.

Element | Description
^ | Beginning of input
$ | End of input
\b | Word boundary
\B | Non-word boundary
* | Zero or more repetitions
+ | One or more repetitions
? | Zero or one repetitions
{n} | n repetitions
{n,} | n or more repetitions
{n,m} | From n to m repetitions, inclusive

To correct this error

  • Ensure your search pattern element contains legal repetition factors only.

See Also

Reference

Regular Expression Object (JScript 5.6)
Regular Expression Syntax (Scripting)


Subscript out of range (Microsoft Windows Script Technologies)

Visual Basic Scripting Edition
Subscript out of range (Microsoft Windows Script Technologies)
See Also

The array you are trying to access contains fewer elements than you expect. For example, attempting to access the 11th element of an array dimensioned for ten elements.

To correct this error

  • Make sure your code contains bounds checking that ensures elements beyond the scope of the array are not referenced.

  • Re-dimension the array to a larger size that meets your needs.

See Also

Reference

UBound Function
LBound Function
Dim Statement
ReDim Statement


Expected 'Select'

Visual Basic Scripting Edition
Expected 'Select'
See Also

You created a Select...End Select construct, but did not include the terminating End Select statement. The following demonstrates the correct usage of the Select...End Select construct.

CopyCode image Copy Code
      Select Case testexpression
   [Case expressionlist-n
      [statements-n]] . . .
   [Case Else expressionlist-n
      [elsestatements-n]]
End Select

To correct this error

  • Make sure the SelectEnd Select construct includes all the necessary parts.

See Also

Reference

Select Case Statement
If...Then...Else Statement


Expected 'Function'

Visual Basic Scripting Edition
Expected 'Function'
See Also

You created a Function procedure, but terminated it with the End keyword, instead of the End Function statement. A Function procedure must include a terminating End Function statement.

To correct this error

  • Terminate your Function procedure with the End Function statement.

See Also

Reference

Function Statement (VBScript)
Call Statement
Dim Statement
Exit Statement
Set Statement
Sub Statement


Expected 'With'

Visual Basic Scripting Edition
Expected 'With'
See Also

You created a With block, but terminated it with the End keyword instead of the End With statement. A With block must be terminated with an associated End With statement. The following demonstrates the correct composition of a With block.

CopyCode image Copy Code
      With object
   statements
End With

To correct this error

  • If you ended your With block with an End keyword, change it to the End With statement.

  • Make sure that the With control structure includes all the necessary parts.

See Also

Reference

With Statement (VBScript)
Set Statement
If...Then...Else Statement
Select Case Statement

Concepts

Using Conditional Statements


Array length must be assigned a finite positive number

JScript
Array length must be assigned a finite positive number
See Also

When setting the length property of an existing Array object, you specified an array length that was not a positive number or zero. This error occurs when you assign a value to the length property of an Array object that is negative or not a number (NaN). Note that JScript automatically converts fractional numbers to whole integers.

To correct this error

  • Assign a positive whole number to the length property. There is no upper limit for the size of an array, other than the maximum integer value (approximately 4 billion). The following example demonstrates the correct way to set the length property of an Array object.

    CopyCode image Copy Code
    var my_array = new Array();
my_array.length = 99;

See Also

Concepts

Using Arrays (JScript 5.6)


Number of arguments must be consistent across properties specification

Visual Basic Scripting Edition
Number of arguments must be consistent across properties specification
See Also

The number of arguments you specified is too few. When using Property Let or Property Set, the number of arguments must be one greater than the number returned by the corresponding Property Get.

To correct this error

  • Make sure Property Let and Property Set have at least one more argument than that returned by Property Get.

See Also

Reference

Property Let Statement
Property Set Statement
Property Get Statement


The precision is out of range

JScript
The precision is out of range
See Also

You attempted to pass an invalid argument to the function Number.prototype.toPrecision. The argument to toPrecision must between 1 and 21 (inclusive).

To correct this error

  • Ensure the argument to toPrecision is not too large or too small.

See Also

Reference

toPrecision Method (JScript 5.6)


Expected '@end'

JScript
Expected '@end'
See Also

You attempted to create a conditionally compiled block of code, but did not include the @end statement at the end. JScript statements can be conditionally compiled by enclosing them within an @if/@end block.

To correct this error

  • Add the corresponding @end statement.

See Also

Concepts

Conditional Compilation (JScript 5.6)
Conditional Compilation Variables (JScript 5.6)


Must be first statement on the line

Visual Basic Scripting Edition
Must be first statement on the line
See Also

Your multi-statement line of code contained an If...Then...Else statement, but the If...Then...Else statement was not the first statement on the line. If...Then...Else statements must be the first statement on a line.

To correct this error

  • Move the If or Else statement to a new line.

See Also

Reference

If...Then...Else Statement


Expected ':'

JScript
Expected ':'
See Also

You attempted to create an expression using the ternary conditional operator, but did not include the colon between the second and third operands. The ternary (three operands) conditional operator requires a colon between the second (true) and third (false) operands.

To correct this error

  • Insert a colon between the second and third operands.

See Also

Reference

Conditional (Ternary) Operator (?:) (JScript 5.6)

Concepts

Operators (JScript 5.6)


JScript object expected

JScript
JScript object expected
See Also

You attempted to pass a non-JScript object to a built-in function that expects a JScript object. Various built-in functions require objects defined in JScript (as opposed to objects defined by the host, or an external component like a control).

To correct this error

  • Ensure that the object you are passing in as a parameter is of the correct type.

See Also

Concepts

Objects (JScript 5.6)
Using Arrays (JScript 5.6)


Must be defined inside a Class

Visual Basic Scripting Edition
Must be defined inside a Class
See Also

You created a Property procedure (Property Let, Property Set, or Property Get), but defined it outside of a Class definition. You can only create Property procedures inside classes.

To correct this error

  • Make sure all Property Let, Property Set, and Property Gets are defined inside a Class definition.

See Also

Reference

Property Let Statement
Property Set Statement
Property Get Statement


Copyright (Microsoft Windows Script Technologies)

Microsoft Windows Script Technologies
Copyright (Microsoft Windows Script Technologies)
DropDown image

Information in this document, including URL and other Internet Web site references, is subject to change without notice. Unless otherwise noted, the example companies, organizations, products, domain names, e-mail addresses, logos, people, places and events depicted herein are fictitious, and no association with any real company, organization, product, domain name, e-mail address, logo, person, place or event is intended or should be inferred. Complying with all applicable copyright laws is the responsibility of the user. Without limiting the rights under copyright, no part of this document may be reproduced, stored in or introduced into a retrieval system, or transmitted in any form or by any means (electronic, mechanical, photocopying, recording, or otherwise), or for any purpose, without the express written permission of Microsoft Corporation.

Microsoft may have patents, patent applications, trademarks, copyrights, or other intellectual property rights covering subject matter in this document. Except as expressly provided in any written license agreement from Microsoft, the furnishing of this document does not give you any license to these patents, trademarks, copyrights, or other intellectual property.

© 1987-2002 Microsoft Corporation. All rights reserved.

Microsoft, MS-DOS, Windows, Windows NT, Microsoft Press, Active Accessibility, Active Channel, Active Client, Active Desktop, Active Directory, ActiveMovie, Active Platform, ActiveStore, ActiveSync, ActiveX, Authenticode, BackOffice, BizTalk, C#, Chromeffects, ClearType, CodeView, DataTips, Developer Studio, Direct3D, DirectAnimation, DirectDraw, DirectInput, DirectMusic, DirectPlay, DirectShow, DirectSound, DirectX, DirectXJ, FoxPro, the Fox head design, FrontPage, IntelliMouse, IntelliSense, J/Direct, JScript, Liquid Motion, Microsoft QuickBasic, Mobile Explorer, MSDN, MSN, Outlook, PivotChart, PivotTable, PowerPoint, QuickAssembler, Rushmore, SourceSafe, Visual Basic, the Visual Basic logo, Visual C++, Visual FoxPro, Visual InterDev, Visual J++, Visual SourceSafe, Visual Studio, the Visual Studio logo, the Visual Tools logo, Verdana, Win32, Win32s, and Win64 are either registered trademarks or trademarks of Microsoft Corporation in the United States and/or other countries.

The names of actual companies and products mentioned herein may be the trademarks of their respective owners.


Error in loading DLL (VBScript)

Visual Basic Scripting Edition
Error in loading DLL (VBScript)

Your application references a DLL that cannot be found. Alternately, a DLL may have referenced another DLL that cannot be found.

To correct this error

  • Make sure the DLL is present.

  • Use the entire Path name when referring to the DLL.

  • Obtain the referenced DLL and make it available to the other DLL.


Expected expression

Visual Basic Scripting Edition
Expected expression
See Also

You created a SelectEnd Select construct, but included a Case clause that contains one or more values along with a Case Else statement. The Case Else statement (the fall-through case) must appear on its own line. The following demonstrates the correct usage of the SelectEnd Select construct.

CopyCode image Copy Code
      Select Case testexpression
   [Case expressionlist-n
      [statements-n]] . . .
   [Case Else expressionlist-n
      [elsestatements-n]]
End Select

To correct this error

  • Create a new line for the Case Else statement.

See Also

Reference

Select Case Statement


Can't have 'continue' outside of loop

JScript
Can't have 'continue' outside of loop
See Also

You attempted to use the continue statement outside of a loop. The continue statement can be used only within the body of a:

  • do-while loop,

  • while loop,

  • for loop,

  • for/in loop.

To correct this error

  • Make sure the continue statement appears within the body of a:

    • do-while loop,

    • while loop,

    • for loop,

    • for/in loop.

See Also

Reference

continue Statement (JScript 5.6)

Concepts

Controlling Program Flow
Troubleshooting Your Scripts (JScript 5.6)


Expected integer constant

Visual Basic Scripting Edition
Expected integer constant
See Also

You attempted to create an array using a nonconstant in the Dim statement. In VBScript, the value of size in a Dim statement must be a constant. For example,

CopyCode image Copy Code
Dim a(10)   ' is valid.
Dim a(x)    ' is not valid.
Dim a(1=2)  ' is not valid.

To correct this error

  • Use the ReDim statement.

See Also

Reference

Dim Statement
ReDim Statement


Date object expected

JScript
Date object expected
See Also

You attempted to invoke the Date.prototype.toString or Date.prototype.valueOf method on an object of a type other than Date. The object of this type of invocation must be of type Date. For example:

CopyCode image Copy Code
var o = new Object;
o.f = Date.prototype.toString;
o.f();

To correct this error

  • Only invoke the Date.prototype.toString or Date.prototype.valueOf methods on objects of type Date.

See Also

Reference

Date Object (JScript 5.6)
getDate Method (JScript 5.6)

Concepts

Intrinsic Objects (JScript 5.6)


Invalid procedure call or argument

Visual Basic Scripting Edition
Invalid procedure call or argument

You passed an invalid parameter in your procedure call. This could be because the parameter was out of range, or contained invalid data. Alternately, you may have invoked a procedure at an unexpected time.

To correct this error

  • Verify that the parameters being passed to the procedure are valid.

  • Verify that you are calling the function at an appropriate time.


Null Keyword

Visual Basic Scripting Edition
Null Keyword
See Also
DropDown image

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

See Also

Concepts

Empty Keyword


Unterminated string constant (VBScript)

Visual Basic Scripting Edition
Unterminated string constant (VBScript)
See Also

You did not end your string constant with a closing quotation mark. String constants must be enclosed within a pair of quotation marks.

To correct this error

  • Add the closing quotation mark to the end of the string.

See Also

Concepts

VBScript Constants


Unterminated comment

JScript
Unterminated comment
See Also

You began a multi-line comment block, but did not properly terminate it. Multi-line comments begin with a "/*" combination, and end with the reverse "*/" combination. The following is an example:

CopyCode image Copy Code
/* This is a comment
This is another part of the same comment.*/

To correct this error

  • Be sure to terminate multi-line comments with "*/".

See Also

Reference

Comment Statements (JScript 5.6)


Invalid 'exit' statement

Visual Basic Scripting Edition
Invalid 'exit' statement
See Also

You used an Exit statement inside one of the following program control constructs:

  • With Statement.

  • If...Then...Else Statement.

  • Select Case Statement.

You can legally use an Exit statement to leave these structures only:

  • Do...While loop (Exit Do).

  • For...Next loop (Exit For).

  • For Each...Next loop (Exit For).

  • Function procedure (Exit Function).

  • Sub procedure (Exit Sub).

To correct this error

  • You may have improperly used Exit If, Exit With, or Exit Select.

  • Do not use Exit with If, With, or Select statements.

See Also

Reference

Exit Statement
Do...Loop Statement
For Each...Next Statement
For...Next Statement
Function Statement (VBScript)
Sub Statement


The number of fractional digits is out of range

JScript
The number of fractional digits is out of range
See Also

You attempted to pass an invalid argument to the function Number.prototype.toExponential. The argument to the function toExponential() must be between 0 and 20 (inclusive).

To correct this error

  • Ensure the argument to toExponential() is not too large or too small.

See Also

Reference

toExponential Method (JScript 5.6)


Enumerator object expected

JScript
Enumerator object expected
See Also

You attempted to invoke the Enumerator.prototype.atEnd, Enumerator.prototype.item, Enumerator.prototype.moveFirst, or Enumerator.prototype.moveNext method on an object of a type other than Enumerator. The object of this type of invocation must be of type Enumerator. Here is an example of code that breaks this rule:

CopyCode image Copy Code
var o = new Object;
o.f = Enumerator.prototype.atEnd;
o.f();

To correct this error

  • Only invoke the Enumerator.prototype.atEnd, Enumerator.prototype.item, Enumerator.prototype.moveFirst, or Enumerator.prototype.moveNext methods on objects of type Enumerator. To find out if your object is an Enumerator object, use:

    CopyCode image Copy Code
    if(x instanceof Enumerator)

See Also

Reference

Enumerator Object (JScript 5.6)


Invalid picture

Visual Basic Scripting Edition
Invalid picture
See Also

The graphic file you attempted to load is in an unrecognizable format. Valid formats include bitmap (*.bmp), icon (*.ico), and Windows metafile (*.wmf).

To correct this error

  • Make sure the graphic file you want to load is in a valid graphic format.

See Also

Reference

LoadPicture Function


Invalid use of Null

Visual Basic Scripting Edition
Invalid use of Null
See Also

You attempted to obtain the value of a Variant variable that is Null. You can only obtain the value of Variant variables that contain valid values. Null is a Variant subtype used to indicate that a data item contains no valid data.

To correct this error

  • Make sure the variable contains a valid value.

See Also

Reference

IsNull Function


Expected '}'

JScript
Expected '}'
See Also

You did not include the right brace that marks the end of the function body, loop, block of code, or object initializer. An example of this error would be a for loop with only the left brace marking the body of the loop.

To correct this error

  • Add the right brace that marks the ending of the function, loop, block, or object initializer.

See Also

Reference

Function Object (JScript 5.6)

Concepts

Controlling Program Flow


The remote server machine does not exist or is unavailable

Visual Basic Scripting Edition
The remote server machine does not exist or is unavailable

You used the function CreateObject to create an object on a remote machine, but the call failed. This occurred because the remote server was either not reachable, or did not contain the specified class.

To correct this error

  • Verify that the remote server name is correct.

  • Verify that the remote server has DCOM enabled.

  • Using the application dcomcnfg, verify that security permissions allow the object to be created.


Syntax error (JScript)

JScript
Syntax error (JScript)
See Also

You created a statement that violates one or more of the grammatical rules of JScript.

To correct this error

  • Double-check the syntax of your program on the line number indicated.

  • Look for misdirected parentheses or braces.

See Also

Reference

Error Object (JScript 5.6)


False (Windows Script Technologies)

Visual Basic Scripting Edition
False (Windows Script Technologies)
See Also
DropDown image

The False keyword has a value equal to 0.

See Also

Concepts

True Keyword


Object doesn't support current locale setting

Visual Basic Scripting Edition
Object doesn't support current locale setting
See Also

You attempted to access an abject that does not support your current locale settings. A locale setting is a set of information that corresponds to a given language and country/region. A locale affects the language of predefined programming terms and locale-specific settings. There are two contexts where locale information is important:

  • The code locale affects the language of terms such as keywords, and defines locale-specific settings such as the decimal and list separators, date formats, and character sorting order.

  • The system locale affects the way locale-aware functionality behaves. For example, when you display numbers, or convert strings to dates. You set the system locale using the Control Panel utilities provided by the operating system.

To correct this error

  • Check which locale settings the object supports.

See Also

Reference

CDate Function


'loop' without 'do'

Visual Basic Scripting Edition
'loop' without 'do'
See Also

You created a Do loop, but did not properly establish the loop. Do loops begin with an associated Do statement. The following demonstrates the correct structure of a Do loop.

CopyCode image Copy Code
      Do [{While | Until} condition]
   [statements]
   [Exit Do]
   [statements]
Loop

Or, you can use this syntax:

CopyCode image Copy Code
      Do
   [statements]
   [Exit Do]
   [statements]
Loop [{While | Until} condition]

To correct this error

  • You may have attempted to delete a Do control structure without removing the Loop statement.

  • Make sure that the Do loop includes all the necessary parts.

See Also

Reference

Do...Loop Statement
Exit Statement
For...Next Statement
While...Wend Statement


Empty Keyword

Visual Basic Scripting Edition
Empty Keyword
See Also
DropDown image

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

See Also

Concepts

Null Keyword


Regular expression object expected

JScript
Regular expression object expected
See Also

You attempted to invoke the RegExp.prototype.toString or RegExp.prototype.valueOf method on an object of a type other than RegExp. The object of this type of invocation must be of type RegExp.

To correct this error

  • Only invoke the RegExp.prototype.toString or RegExp.prototype.valueOf methods on objects of type RegExp.

See Also

Reference

Regular Expression Object (JScript 5.6)
Regular Expression Syntax (Scripting)


Expected 'Loop'

Visual Basic Scripting Edition
Expected 'Loop'
See Also

You created a Do loop construct, but did not properly terminate the loop. Do loop constructs are terminated with an associated Loop statement. The following demonstrates the correct structure of a Do loop construct.

CopyCode image Copy Code
      Do [{While | Until} condition]
   [statements]
   [Exit Do]
   [statements]
Loop

Or, you can use this syntax:

CopyCode image Copy Code
      Do
   [statements]
   [Exit Do]
   [statements]
Loop [{While | Until} condition]

To correct this error

  • Make sure that the Do loop construct includes all the necessary parts.

See Also

Reference

Do...Loop Statement
Exit Statement
For...Next Statement
While...Wend Statement


Cannot assign to a function result

JScript
Cannot assign to a function result
See Also

You attempted to assign a value to a function result. The result of a function can be assigned to a variable, but it cannot be used as a variable. If you want to assign a new value to the function itself, omit the parentheses (the function call operator). The following example demonstrates a situation in which this error is generated.

CopyCode image Copy Code
myFunction() = 42;  // Attempting to assign the value 42 to the result of the function call.

To correct this error

  • Do not use the value of a function call result as something you can assign to. You can assign the result of the function call to a variable though.

    CopyCode image Copy Code
    myVar = myFunction(42);

  • Alternatively, you can assign the function itself (and not its return value) to a variable.

    CopyCode image Copy Code
    myFunction = new Function("return 42;");

See Also

Reference

Function Object (JScript 5.6)

Concepts

Writing JScript Code
Functions (JScript 5.6)


Object not safe for initializing

Visual Basic Scripting Edition
Object not safe for initializing
See Also

You attempted to use an object that has not been marked safe for initialization. The set of objects that are safe to create is determined by the host. Generally, objects that allow untrusted scripts to do harmful actions (like access the hard disk) are considered unsafe.

For example, the FileSystemObject is not safe to run using Microsoft Internet Explorer as your client, but you can use this object on your local machine with Windows Script Host.

To correct this error

  • Make sure you are using a safe object.

  • Contact the developer of the object to see if there is a safe version.

  • You can find out if an object is safe by reading the object's documentation.

See Also

Reference

Initialize Event


Expected 'catch'

JScript
Expected 'catch'
See Also

You used the exception handling try block, but did not write the associated catch statement. The exception handling mechanism requires that the code that can fail, along with the code that should not execute if an exception occurs, be wrapped inside a try block. Exceptions are thrown from within the try block using the throw statement, and caught outside the try block with one or more catch statements.

To correct this error

  • Add the associated catch block.

  • Try using a finally block instead of a catch block.

See Also

Reference

try...catch...finally Statement (JScript 5.6)
Error Object (JScript 5.6)


Expected identifier, string or number

JScript
Expected identifier, string or number
See Also

You used incorrect literal syntax to declare an object literal. The properties of an object literal must be an identifier, a string, or a number. An object literal (also called an "object initializer") consists of a comma-separated list of property:value pairs, all enclosed within brackets. For example:

CopyCode image Copy Code
var point = {x:1.2, y:-3.4};

To correct this error

  • Ensure you use the proper literal syntax.

See Also

Reference

Comma Operator (,) (JScript 5.6)


Function expected

JScript
Function expected
See Also

Either you attempted to invoke one of the Function prototype methods on an object that was not a Function object, or you used an object in a function call context. For example, the following code produces this error because example is not a function.

CopyCode image Copy Code
var example = new Object();  // Create a new object called "example".
var x = example();           // Try and call example as if it were a function.

To correct this error

  • Only call Function prototype methods on Function objects.

  • Ensure that you use the function call operator () to call functions only.

See Also

Reference

Function Object (JScript 5.6)
prototype Property (JScript 5.6)


VBArray expected

JScript
VBArray expected
See Also

You supplied an object that was not a Visual Basic safeArray, when one was expected.

CopyCode image Copy Code
new VBArray(safeArray);

VBArrays are read-only, and cannot be created directly. The safeArray argument is a VBArray value, and must have obtained a VBArray value before being passed to the VBArray constructor. This can only be done by retrieving the value from an existing ActiveX or other object.

To correct this error

  • Ensure you pass only VBArray objects to the VBArray constructor.

See Also

Reference

VBArray Object (JScript 5.6)

Concepts

Using Arrays (JScript 5.6)


Unexpected quantifier (VBScript)

Visual Basic Scripting Edition
Unexpected quantifier (VBScript)
See Also

When composing your regular expression search pattern, you did not properly specify the match string.

To correct this error

  • Ensure your search pattern is properly constructed.

See Also

Concepts

Regular Expression (RegExp) Object


Overflow

Visual Basic Scripting Edition
Overflow
See Also

The value you attempted to assign to a variable is too large. This error occurs when one of the following is true:

  • The result of an assignment, calculation, or data type conversion is too large to be represented within the range of values allowed for that type of variable.

  • An assignment to a property exceeds the maximum value the property can accept.

  • You attempt to use a number in a calculation, and that number is coerced into an integer, but the result is larger than an integer.

To correct this error

  • Assign the value to a variable of a type that can hold a larger range of values.

  • Make sure your assignment fits the range for the property to which it is made.

See Also

Concepts

VBScript Variables
Err Object (VBScript)


Out of string space

Visual Basic Scripting Edition
Out of string space
See Also

You attempted to create a string object, but could not because you have used up all your system memory. This could be a result of a dynamically allocated array growing too large, or the instantiation of a large number of objects.

To correct this error

  • Use the Erase statement to reallocate dynamic-array storage space.

  • Use the ReDim statement to reallocate storage space.

  • Close any unnecessary applications, documents, or source files that are open.

See Also

Reference

Erase Statement
Dim Statement
ReDim Statement
CreateObject Function

Concepts

Nothing Keyword


Expected '{'

JScript
Expected '{'
See Also

You did not include the left brace that marks the beginning of the function body. Code that makes up the body of a function, even if it is a single line, must be contained within left and right braces. Notice that the use of braces in function bodies is stricter than in loops.

To correct this error

  • Add the left brace that marks the beginning of the function body.

See Also

Reference

Function Object (JScript 5.6)