JScript

JScript

JScript User's Guide

Using JScript in Internet Explorer

JScript Language Reference

© 2001 Microsoft Corporation. All rights reserved.

Build: Topic Version 5.6.9309.1546


JScript User's Guide

JScript Fundamentals

Advanced JScript


JScript Fundamentals

What Is JScript?

Writing JScript Code

JScript Variables

JScript Data Types

JScript Operators

Operator Precedence

Controlling Program Flow

Conditional Compilation

Conditional Compilation Variables

JScript Functions

JScript Objects

Intrinsic Objects

Creating Your Own Objects

JScript Reserved Words


What Is JScript?

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

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.

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.

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.

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 (*/).

/*
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 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.

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

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 sings (==). 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.

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:

+  // additon
-  // subtraction
*  // multiplication
/  // division

Here are some examples of JScript complex expressions.

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


JScript Variables

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

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:

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.

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:

_pagecount
Part9
Number_Items

Here are some examples of invalid variable names:

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.

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.

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.

noStringAtAll = ""; // The variable noStringAtAll is declared implicitly.

You cannot use a variable that has never been declared.

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.

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


JScript Data Types

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

The primary (primitive) data types are:

  • String
  • Number
  • Boolean

The composite (reference) data types are:

  • Object
  • Array

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:

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

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.

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:

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.

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:

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

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:

if ("prop" in someObject)
    // someObject has the property 'prop'


JScript Operators

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

// 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

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.

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:

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

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.

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

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 andAnd' 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.

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.

/*
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.

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

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

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.

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!");


JScript Functions

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.

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.

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);


JScript Objects

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:

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.

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:

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

// 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


Creating Your Own Objects

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.

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

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

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

// 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);


Intrinsic Objects

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.

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.

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.

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.

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.

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

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

/*
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.


JScript Reserved Words

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

Advanced Object Creation

Recursion

Variable Scope

Copying, Passing, and Comparing Data

Using Arrays

Special Characters

Troubleshooting Your Scripts


Advanced Object Creation

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.

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

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.

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

Circle.prototype.pi = Math.PI;
function ACirclesArea () {
    return this.pi * this.r * this.r; // The formula for the area of a circle is Ïr2.
}
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.

// 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

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.

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.

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

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.

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.

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,

var someVariable;

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

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

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

// 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

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.

theListing = addressBook[entryNum];
theFirstLine = theListing[1];

Objects as Associative Arrays

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

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,

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

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

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

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

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

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

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

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.

/*@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

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.

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

The information contained in these pages is intended to provide a introduction to regular expressions in general.

While an attempt has been made to make each topic stand on it's own, much of the information contained in these topics relies upon the understanding of a previously introduced feature or concept. Therefore, it's recommended that you peruse these topics sequentially for the best overall understanding of the material.

The Introduction to Regular Expressions consists of the following individuals topics:

Regular Expressions

Early Beginnings

Uses for Regular Expressions

Regular Expression Syntax

Build a Regular Expression

Order of Precedence

Ordinary Characters

Special Characters

Non-Printable Characters

Character Matching

Quantifiers

Anchors

Alternation and Grouping

Backreferences


Regular Expressions

Unless you have worked with regular expressions before, the term and the concept may be unfamiliar to you. However, they may not be as unfamiliar as you think.

Think about how you search for files on your hard disk. You most likely use the ? and * characters to help find the files you're looking for. The ? character matches a single character in a file name, while the * matches zero or more characters. A pattern such as 'data?.dat' would find the following files:

data1.dat
data2.dat
datax.dat
dataN.dat

Using the * character instead of the ? character expands the number of files found. 'data*.dat' matches all of the following:

data.dat
data1.dat
data2.dat
data12.dat
datax.dat
dataXYZ.dat

While this method of searching for files can certainly be useful, it is also very limited. The limited ability of the ? and * wildcard characters give you an idea of what regular expressions can do, but regular expressions are much more powerful and flexible.


Early Beginnings

Regular expressions trace their ancestry back to early research on how the human nervous system works. Warren McCulloch and Walter Pitts, a pair of neuro-physiologists, developed a mathematical way of describing these neural networks.

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

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

With regular expressions, you can:

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

For example, if you need to search an entire web site to remove some outdated material and replace some HTML formatting tags, you can use a regular expression to test each file to see if the material or the HTML formatting tags you are looking for exists in that file. That way, you can narrow down the affected files to only those that contain the material that has to be removed or changed. You can then use a regular expression to remove the outdated material, and finally, you can use regular expressions to search for and replace the tags that need replacing.

Another example of where a regular expression is useful occurs in a language that isn't known for its string-handling ability. VBScript, a subset of Visual Basic, has a rich set of string-handling functions. JScript, like C, does not. Regular expressions provide a significant improvement in string-handling for JScript. However, regular expressions may also be more efficient to use in VBScript as well, allowing you do perform multiple string manipulations in a single expression.


Regular Expression Syntax

A regular expression is a pattern of text that consists of ordinary characters (for example, letters a through z) and special characters, known as metacharacters. The pattern describes one or more strings to match when searching a body of text. The regular expression serves as a template for matching a character pattern to the string being searched.

Here are some examples of regular expression you might encounter:

JScript | VBScript | Matches
/^\[ \t]*$/ | "^\[ \t]*$" | 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.
/<(.*)>.*<\/\1>/ | "<(.*)>.*<\/\1>" | Match an HTML tag.

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 either a special character, a literal, a backreference, or an octal escape. For example, 'n' matches the character "n". '\n' matches a newline character. The sequence '\\' matches "\" and "\(" matches "(".
^ | Matches the position at the beginning of the input string. If the RegExp object's Multiline property is set, ^ also matches the position following '\n' or '\r'.
$ | Matches the position at the end of the input string. If the RegExp object's Multiline property is set, $ also matches the position preceding '\n' or '\r'.
* | Matches the preceding subexpression zero or more times. For example, zo* matches "z" and "zoo". * is equivalent to {0,}.
+ | Matches the preceding subexpression one or more times. For example, 'zo+' matches "zo" and "zoo", but not "z". + is equivalent to {1,}.
? | Matches the preceding subexpression zero or one time. For example, "do(es)?" matches the "do" in "do" or "does". ? is equivalent to {0,1}
{n} | 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 '[.\n]'.
(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 whitespace character including space, tab, form-feed, etc. Equivalent to [ \f\n\r\t\v].
\S | Matches any non-whitespace 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

Regular expressions are constructed in the same way that arithmetic expressions are created. That is, small expressions are combined using a variety of metacharacters and operators to create larger expressions.

You construct a regular expression by putting the various components of the expression pattern between a pair of delimiters. For JScript, the delimiters are a pair of forward slash (/) characters. For example:

/expression/

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

"expression"

In both of the examples shown above, the regular expression pattern (expression) is stored in the Pattern property of the RegExp object.

The components of a regular expression can be individual characters, sets of characters, ranges of characters, choices between characters, or any combination of all of these components.


Order of Precedence

Once you have constructed a regular expression, it is evaluated much like an arithmetic expression, that is, it is evaluated from left to right and follows an order of precedence.

The following table illustrates, from highest to lowest, the order of precedence of the various regular expression operators:

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


Ordinary Characters

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

The simplest form of a regular expression is a single, ordinary character that matches itself in a searched string. For example, the single-character pattern 'A' matches the letter 'A' wherever it appears in the searched string. Here are some examples of single-character regular expression patterns:

/a/
/7/
/M/

The equivalent VBScript single-character regular expressions are:

"a"
"7"
"M"

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

/a7M/

The equivalent VBScript expression is:

"a7M"

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


Special Characters

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

Special Character | Comment
$ | Matches the position at the end of an input string. If the RegExp object's Multiline property is set, $ also matches the position preceding '\n' or '\r'. To match the $ character itself, use \$.
( ) | Marks the beginning and end of a subexpression. Subexpressions can be captured for later use. To match these characters, use \( and \).
* | Matches the preceding subexpression zero or more times. To match the * character, use \*.
+ | Matches the preceding subexpression one or more times. To match the + character, use \+.
. | Matches any single character except the newline character \n. To match ., use \.
[ | Marks the beginning of a bracket expression. To match [, use \[.
? | Matches the preceding subexpression zero or one time, or indicates a non-greedy quantifier. To match the ? character, use \?.
\ | Marks the next character as either a special character, a literal, a backreference, or an octal escape. For example, 'n' matches the character 'n'. '\n' matches a newline character. The sequence '\\' matches "\" and '\(' matches "(".
^ | Matches the position at the beginning of an input string except when used in a bracket expression where it negates the character set. To match the ^ character itself, use \^.
{ | Marks the beginning of a quantifier expression. To match {, use \{.
| | Indicates a choice between two items. To match |, use \|.


Non-Printable Characters

There are a number of useful non-printing characters that must be used occasionally. The following table shows the escape sequences used to represent those non-printing characters:

Character | 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 whitespace character including space, tab, form-feed, etc. Equivalent to [\f\n\r\t\v].
\S | Matches any non-whitespace 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

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

/a.c/

The equivalent VBScript regular expression is:

"a.c"

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

/filename\.ext/

For VBScript, the equivalent expression appears as follows:

"filename\.ext"

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

Bracket Expressions

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

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

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

/Chapter [12345]/

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

"Chapter [12345]"

Notice that the word 'Chapter' and the space that follows are fixed in position relative to the characters within brackets. The bracket expression then, is used to specify only the set of characters that matches the single character position immediately following the word 'Chapter' and a space. That is the ninth character position.

If you want to express the matching characters using a range instead of the characters themselves, you can separate the beginning and ending characters in the range using the hyphen (-) character. The character value of the individual characters determines their relative order within a range. The following JScript regular expression contains a range expression that is equivalent to the bracketed list shown above.

/Chapter [1-5]/

The same expression for VBScript appears as follows:

"Chapter [1-5]"

When a range is specified in this manner, both the starting and ending values are included in the range. It is important to note that the starting value must precede the ending value in Unicode sort order.

If you want to include the hyphen character in your bracket expression, you must do one of the following:

  • Escape it with a backslash:
    [\-]
  • Put the hyphen character at the beginning or the end of the bracketed list. The following expressions matches all lowercase letters and the hyphen:
    [-a-z]
[a-z-]
  • Create a range where the beginning character value is lower than the hyphen character and the ending character value is equal to or greater than the hyphen. Both of the following regular expressions satisfy this requirement:
    [!--]
[!-~]

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

/Chapter [^12345]/

For VBScript use:

"Chapter [^12345]"

In the examples shown above, the expression matches any digit character in the ninth position except 1, 2, 3, 4, or 5. So, for example, 'Chapter 7' is a match and so is 'Chapter 9'.

The same expressions above can be represented using the hyphen character (-). For JScript:

/Chapter [^1-5]/

or for VBScript:

"Chapter [^1-5]"

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

/[A-Za-z0-9]/

The equivalent expression for VBScript is:

"[A-Za-z0-9]"


Quantifiers

Sometimes, you don't know how many characters there are to match. In order to accommodate that kind of uncertainty, regular expressions support the concept of quantifiers. These quantifiers let you specify how many times a given component of your regular expression must occur for your match to be true.

The following table illustrates the various quantifiers and their meanings:

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

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

The following VBScript regular expression performs the identical match:

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

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

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

For VBScript, use the following regular expression:

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

The disadvantage to the expression shown above is that if there is a chapter number greater than 99, it will still only match the first two digits. Another disadvantage is that somebody could create a Chapter 0 and it would match. A better JScript expression for matching only two digits are the following:

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

-or-

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

For VBScript, the following expressions are equivalent:

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

-or-

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

The '*', '+', and '?' quantifiers are all what are referred to as greedy, that is, they match as much text as possible. Sometimes that's not at all what you want to happen. Sometimes, you just want a minimal match.

Say, for example, you are searching an HTML document for an occurrence of a chapter title enclosed in an H1 tag. That text appears in your document as:

<H1>Chapter 1 – Introduction to Regular Expressions</H1>

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

/<.*>/

The VBScript regular expression is:

"<.*>"

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

/<.*?>/

-or-

"<.*?>"

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


Anchors

So far, the examples you've seen have been concerned only with finding chapter headings wherever they occur. Any occurrence of the string 'Chapter' followed by a space, followed by a number, could be an actual chapter heading, or it could also be a cross-reference to another chapter. Since true chapter headings always appear at the beginning of a line, you'll need to devise a way to find only the headings and not find the cross-references.

Anchors provide that capability. Anchors allow you to fix a regular expression to either the beginning or end of a line. They also allow you to create regular expressions that occur either within a word or at the beginning or end of a word. The following table contains the list of regular expression anchors and their meanings:

Character | 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. Don't confuse this use of the '^' with the use within a bracket expression. They're definitely not the same.

To match text at the end of a line of text, use the '$' character at the end of the regular expression.

To use anchors when searching for chapter headings, the following JScript regular expression matches a chapter heading with up to two following digits that occurs at the beginning of a line:

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

For VBScript the same regular expressions appears as:

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

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

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

For VBScript use:

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

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

/\bCha/

or for VBScript:

"\bCha"

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

/ter\b/

and

"ter\b"

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

/\Bapt/

and

"\Bapt"

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


Alternation and Grouping

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

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

Unfortunately, what happens is that the regular expressions shown above match either the word 'Chapter' at the beginning of a line, or 'Section' and whatever numbers follow that, at the end of the line. If the input string is 'Chapter 22', the expression shown above only matches the word 'Chapter'. If the input string is 'Section 22', the expression matches 'Section 22'. But that's not the intent here so there must be a way to make that regular expression more responsive to what you're trying to do and there is.

You can use parentheses to limit the scope of the alternation, that is, make sure that it applies only to the two words, 'Chapter' and 'Section'. However, parentheses are tricky as well, because they are also used to create subexpressions, something that's covered later in the section on subexpressions. By taking the regular expressions shown above and adding parentheses in the appropriate places, you can make the regular expression match either 'Chapter 1' or 'Section 3'.

The following regular expressions uses parentheses to group 'Chapter' and 'Section' so the expression works properly. For JScript:

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

For VBScript:

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

These expressions work properly except that an interesting by-product occurs. Placing parentheses around 'Chapter|Section' establishes the proper grouping, but it also causes either of the two matching words to be captured for future use. Since there's only one set of parentheses in the expression shown above, there is only one captured submatch. This submatch can be referred to using the Submatches collection in VBScript or the $1-$9 properties of the RegExp object in JScript.

Sometimes capturing a submatch is desirable, sometimes it's not. In the examples shown above, all you really want to do is use the parentheses for grouping a choice between the words 'Chapter' or 'Section'. You don't necessarily want to refer to that match later. In fact, unless you really need to capture submatches, don't use them. Your regular expressions will be more efficient since they won't have to take the time and memory to store those submatches.

You can use '?:' before the regular expression pattern inside the parentheses to prevent the match from being saved for possible later use. The following modification of the regular expressions shown above provides the same capability without saving the submatch. For JScript:

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

For VBScript:

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

In addition to the '?:' metacharacters, there are two other non-capturing metacharacters used for something called lookahead matches. A positive lookahead, specified using ?=, matches the search string at any point where a matching regular expression pattern in parentheses begins. A negative lookahead, specified using '?!', matches the search string at any point where a string not matching the regular expression pattern begins.

For example, suppose you have a document containing references to Windows 3.1, Windows 95, Windows 98, and Windows NT. Suppose further that you need to update the document by finding all the references to Windows 95, Windows 98, and Windows NT and changing those reference to Windows 2000. You can use the following JScript regular expression, which is an example of a positive lookahead, to match Windows 95, Windows 98, and Windows NT:

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

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

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

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


Backreferences

One of the most important features of regular expressions is the ability to store a part of a matched pattern for later reuse. As you'll recall, placing parentheses around a regular expression pattern or part of a pattern causes that part of the expression to be stored into a temporary buffer. You can override the saving of that part of the regular expression using the non-capturing metacharacters '?:', '?=', or '?!'.

Each captured submatch is stored as it is encountered from left to right in a regular expressions pattern. The buffer numbers where the submatches are stored begin at 1 and continue up to a maximum of 99 subexpressions. Each different buffer can be accessed using '\n' where n is one or two decimal digits identifying a specific buffer.

One of the simplest, most useful applications of back references provides the ability to locate the occurrence of two identical words together in a text. Take the following sentence:

Is is the cost of of gasoline going up up?

As written, the sentence shown above clearly has a problem with several duplicated words. It would be nice to devise a way to fix that sentence without having to look for duplicates of every single word. The following JScript regular expression uses a single subexpression to do that.

/\b([a-z]+) \1\b/gi

The equivalent VBScript expression is:

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

The subexpression, in this case, is everything between parentheses. That captured expression includes one or more alphabetic characters, as specified by '[a-z]+'. The second part of the regular expression is the reference to the previously captured submatch, that is, the second occurrence of the word just matched by the parenthetical expression. '\1' is used to specified the first submatch. The word boundary meta characters ensure that only separate words are detected. If they weren't, a phrase such as "is issued" or "this is" would be incorrectly identified by this expression.

In the JScript expression the global flag ('g') following the regular expression indicates that the expression is applied to as many matches as it can find in the input string. The case insensitivity 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:

var ss = "Is is the cost of of gasoline going up up?.\n";
var re = /\b([a-z]+) \1\b/gim;       //Create regular expression pattern.
var rv = ss.replace(re,"$1");   //Replace two occurrences with one.

The closest equivalent VBScript code appears as follows:

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

In the VBScript code, notice that the global, case-insensitivity, and multiline flags are set using the appropriately named properties of the RegExp object.

The use of the $1 within the replace method refers to the first saved submatch. If you had more than one submatch, you'd refer to them consecutively by $2, $3, and so on.

Another way that backreferences can be used is to break down a Universal Resource Indicator (URI) into its component parts. Assume that you want to break down the following URI down to the protocol (ftp, http, etc), the domain address, and the page/path:

http://msdn.microsoft.com:80/scripting/default.htm

The following regular expressions provides that functionality. For JScript:

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

For VBScript:

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

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

Applying the regular expression to the URI shown above, the submatches contain the following:

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


JScript Language Reference

Feature Information

Errors

Functions

Methods

Objects

Operators

Properties

Statements


Feature Information

The following table lists JScript 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)


Microsoft JScript Features - ECMA

The following table lists JScript features compliant with ECMA standards.

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

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

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

The following table lists the types of JScript errors.

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

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

See Also

JScript Syntax Errors


JScript Syntax Errors

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.

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

See Also

JScript Run-time Errors


JScript Functions

The following table lists JScript 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

Returns a reference to an Automation object from a file.

GetObject([pathname] [, class])

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.

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:

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:

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

If you don 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:

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:

MyObject.Line(9, 90);
MyObject.InsertText(9, 100, "Hello, world.");
MyObject.SaveAs("C:\\DRAWINGS\\SAMPLE.DRW");
Note Use the GetObject function when there is a current instance of the object, or if you want to create the object with a file already loaded. If there is no current instance, and you don't want the object started with a file loaded, use the 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.

Requirements

Version 5

See Also

ActiveXObject Object


ScriptEngine Function

Returns a string representing the scripting language in use.

ScriptEngine( )

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.

Example

The following example illustrates the use of the ScriptEngine function:

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

Requirements

Version 5

See Also

ScriptEngineBuildVersion Function | ScriptEngineMajorVersion Function | ScriptEngineMinorVersion Function


ScriptEngineBuildVersion Function

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

ScriptEngineBuildVersion( )

Remarks

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

Example

The following example illustrates the use of the ScriptEngineBuildVersion function:

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

Requirements

Version 5

See Also

ScriptEngine Function | ScriptEngineMajorVersion Function | ScriptEngineMinorVersion Function


ScriptEngineMajorVersion Function

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

ScriptEngineMajorVersion( )

Remarks

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

Example

The following example illustrates the use of the ScriptEngineMajorVersion function:

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

Requirements

Version 5

See Also

ScriptEngine Function | ScriptEngineBuildVersion Function | ScriptEngineMinorVersion Function


ScriptEngineMinorVersion Function

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

ScriptEngineMinorVersion( )

Remarks

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

Example

The following example illustrates the use of the ScriptEngineMinorVersion function.

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

Requirements

Version 5

See Also

ScriptEngine Function | ScriptEngineBuildVersion Function | ScriptEngineMajorVersion Function


JScript Methods

The following table list JScript 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
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
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 number of dimensions in a VBArray. | dimensions 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 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
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 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
Returns the value of a base expression raised to a specified power. | pow 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
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
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 converted to a string using Greenwich Mean Time (GMT). | toGMTString Method
Returns a date converted to a string using the current locale. | toLocaleString Method
Returns a string where all alphabetic characters have been converted to lowercase. | toLowerCase Method
Returns a string representation of an object. | toString 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 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


abs Method

Returns the absolute value of a number.

Math.abs(number)

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

Remarks

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

Example

The following example illustrates the use of the abs method.

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);
}

Requirements

Version 1

See Also

Math Object Methods

Applies To: Math Object


acos Method

Returns the arccosine of a number.

Math.acos(number)

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

Remarks

The return value is the arccosine of the number argument.

Requirements

Version 1

See Also

asin Method | atan Method | cos Method | sin Method | tan Method

Applies To: Math Object


anchor Method

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

strVariable.anchor(anchorString)

Arguments

strVariable
Required. Any String object or literal.
anchorString
Required. Text you want to place in the NAME attribute of an HTML anchor.

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:

var strVariable = "This is an anchor";
strVariable = strVariable.anchor("Anchor1");

The value of strVariable after the last statement is:

<A NAME="Anchor1">This is an anchor</A>

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

Requirements

Version 1

See Also

link Method | String Object Methods | String Object Properties

Applies To: String Object


apply Method

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

apply([thisObj[,argArray]])

Arguments

thisObj
Optional. The object to be used as the current object.
argArray
Optional. Array of arguments to be passed to the function.

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.

Requirements

Version 5.5

See Also

Applies To: Function Object


asin Method

Returns the arcsine of a number.

Math.asin(number)

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

Remarks

The return value is the arcsine of its numeric argument.

Requirements

Version 1

See Also

acos Method | atan Method | cos Method | Math Object Methods | sin Method | tan Method

Applies To: Math Object


atan Method

Returns the arctangent of a number.

Math.atan(number)

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

Remarks

The return value is the arctangent of its numeric argument.

Requirements

Version 1

See Also

acos Method | asin Method | atan2 Method | cos Method | Math Object Methods | sin Method | tan Method

Applies To: Math Object


atan2 Method

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

Math.atan2(y, x)

Arguments

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

Remarks

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

Requirements

Version 1

See Also

atan Method | tan Method

Applies To: Math Object


atEnd Method

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

myEnum.atEnd()

The required myEnum reference is any Enumerator object.

Remarks

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.

Example

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

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);
}

Requirements

Version 2

See Also

item Method | moveFirst Method | moveNext Method

Applies To: Enumerator Object


big Method

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

strVariable.big( )

The required strVariable reference is any String object or literal.

Remarks

The example that follows shows how the big method works:

var strVariable = "This is a string object";
strVariable = strVariable.big( );

The value of strVariable after the last statement is:

<BIG>This is a string object</BIG>

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

Requirements

Version 1

See Also

small Method | String Object Methods | String Object Properties

Applies To: String Object


blink Method

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

strVariable.blink( )

The required strVariable reference is any String object or literal.

Remarks

The following example demonstrates how the blink method works:

var strVariable = "This is a string object";
strVariable = strVariable.blink( );

The value of strVariable after the last statement is:

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

Requirements

Version 1

See Also

String Object Methods | String Object Properties

Applies To: String Object


bold Method

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

strVariable.bold()

The required strVariable reference is any String object or literal.

Remarks

The following example demonstrates how the bold method works:

var strVariable = "This is a string object";
strVariable = strVariable.bold( );

The value of strVariable after the last statement is:

<B>This is a string object</B>

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

Requirements

Version 1

See Also

italics Method | String Object Methods | String Object Properties

Applies To: String Object


call Method

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

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

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.

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.

Requirements

Version 5.5

See Also

Applies To: Function Object


ceil Method

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

Math.ceil(number)

The required number argument is a numeric expression.

Remarks

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

Requirements

Version 1

See Also

floor Method | Math Object Methods

Applies To: Math Object


charAt Method

Returns the character at the specified index.

strObj.charAt(index)

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.

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.

Example

The following example illustrates the use of the charAt method:

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

Requirements

Version 1

See Also

String Object Methods | String Object Properties

Applies To: String Object


charCodeAt Method

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

strObj.charCodeAt(index)

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.

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.

Example

The following example illustrates the use of the charCodeAt method.

function charCodeAtTest(n){
  var str = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"; //Initialize variable.
  var n;                                  //Declare variable.
  n = str.charCodeAt(n - 1);              //Get the Unicode value of the
                                          // character at position n.
  return(n);                              //Return the value.
}

Requirements

Version 5.5

See Also

fromCharCode Methods | String Object methods

Applies To: String Object


compile Method

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

rgExp.compile(pattern, [flags])

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)

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.

Example

The following example illustrates the use of the compile method:

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;
}

Requirements

Version 3

See Also

Regular Expression Object Methods | Regular Expression Object Properties | Regular Expression Syntax

Applies To: Regular Expression Object


concat Method (Array)

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

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

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.

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.

Example

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

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);
}

Requirements

Version 3

See Also

concat Method (String) | join Method | String Object

Applies To: Array Object


concat Method (String)

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

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

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.

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.

Example

The following example illustrates the use of the concat method when used with a string:

function concatDemo(){
   var str1 = "ABCDEFGHIJKLM"
   var str2 = "NOPQRSTUVWXYZ";
   var s = str1.concat(str2);
   // Return concatenated string.
   return(s);
}

Requirements

Version 3

See Also

Addition Operator (+) | Array Object | concat Method (Array) | String Object Methods

Applies To: String Object


cos Method

Returns the cosine of a number.

Math.cos(number)

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

Remarks

The return value is the cosine of its numeric argument.

Requirements

Version 1

See Also

acos Method | asin Method | atan Method | Math Object Methods | sin Method | tan Method

Applies To: Math Object


decodeURI Method

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

decodeURI(URIstring)

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

Remarks

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.

Requirements

Version 5.5

See Also

decodeURIComponent Method | encodeURI Method

Applies To: Global Object


decodeURIComponent Method

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

decodeURIComponent(encodedURIString)

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

Remarks

A URIComponent is part of a complete URI.

If the encodedURIString is not valid, a URIError occurs.

Requirements

Version 5.5

See Also

decodeURI Method | encodeURI Method

Applies To: Global Object


dimensions Method

Returns the number of dimensions in a VBArray.

array.dimensions( )

The required array is a VBArray object.

Remarks

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.

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

Requirements

Version 3

See Also

getItem Method | lbound Method | toArray Method | ubound Method

Applies To: VBArray Object


encodeURI Method

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

encodeURI(URIString)

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

Remarks

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.

Requirements

Version 5.5

See Also

decodeURI Method | decodeURIComponent Method

Applies To: Global Object


encodeURIComponent Method

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

encodeURIComponent(encodedURIString)

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

Remarks

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.

Requirements

Version 5.5

See Also

decodeURI Method | decodeURIComponent Method

Applies To: Global Object


escape Method

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

escape(charString)

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

Remarks

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 The escape method should not be used to encode Uniform Resource Identifiers (URI). Use encodeURI and encodeURIComponent methods instead.

Requirements

Version 1

See Also

encodeURI Method | encodeURIComponent Method | String Object | unescape Method

Applies To: Global Object


eval Method

Evaluates JScript code and executes it.

eval(codeString)

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

Remarks

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:

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.

Requirements

Version 1

See Also

String Object

Applies To: Global Object


exec Method

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

rgExp.exec(str)

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.

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.

Example

The following example illustrates the use of the exec method:

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");
  }
}

Requirements

Version 3

See Also

match Method | RegExp Object | Regular Expression Object Methods | Regular Expression Object Properties | Regular Expression Syntax | search method | test Method

Applies To: Regular Expression Object


exp Method

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

Math.exp(number)

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

Remarks

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

Requirements

Version 1

See Also

E Property | Math Object Methods

Applies To: Math Object


fixed Method

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

strVariable.fixed( )

The required strVariable reference is any String object or literal.

Remarks

The following example demonstrates how the fixed method works:

var strVariable = "This is a string object";
strVariable = strVariable.fixed();

The value of strVariable after the last statement is:

<TT>This is a string object</TT>

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

Requirements

Version 1

See Also

String Object Methods | String Object Properties

Applies To: String Object


floor Method

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

Math.floor(number)

The required number argument is a numeric expression.

Remarks

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

Requirements

Version 1

See Also

ceil Method | Math Object Methods

Applies To: Math Object


fontcolor Method

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

strVariable.fontcolor(colorVal)

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.

Remarks

The following example demonstrates the fontcolor method:

var strVariable = "This is a string";
strVariable = strVariable.fontcolor("red");

The value of strVariable after the last statement is:

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

Requirements

Version 1

See Also

fontsize Method | String Object Methods | String Object Properties

Applies To: String Object


fontsize Method

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

strVariable.fontsize(intSize)

Arguments

strVariable
Required. Any String object or literal.
intSize
Required. Integer value that specifies the size of the text.

Remarks

The following example demonstrates the fontsize method:

var strVariable = "This is a string";
strVariable = strVariable.fontsize(-1);

The value of strVariable after the last statement is:

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

Requirements

Version 1

See Also

fontcolor Method | String Object Methods | String Object Properties

Applies To: String Object


fromCharCode Method

Returns a string from a number of Unicode character values.

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

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.

Remarks

A String object need not be created before calling fromCharCode.

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

var test = String.fromCharCode(112, 108, 97, 105, 110);

Requirements

Version 3

See Also

charCodeAt Method | String Object Methods

Applies To: String Object


getDate Method

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

dateObj.getDate()

The required dateObj reference is a Date object.

Remarks

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.

Example

The following example illustrates the use of the getDate method.

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

Requirements

Version 1

See Also

Date Object Methods | getUTCDate Method | setDate Method | setUTCDate Method

Applies To: Date Object


getDay Method

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

dateObj.getDay()

The required dateObj reference is a Date object.

Remarks

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.

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]);
}

Requirements

Version 1

See Also

Date Object Methods | getUTCDay Method

Applies To: Date Object


getFullYear Method

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

dateObj.getFullYear()

The required dateObj reference is a Date object.

Remarks

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.

The following example illustrates the use of the GetFullYear method.

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);
}

Requirements

Version 3

See Also

Date Object Methods | getUTCFullYear Method | setFullYear Method | setUTCFullYear Method

Applies To: Date Object


getHours Method

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

dateObj.getHours()

The required dateObj reference is a Date object.

Remarks

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.

The following example illustrates the use of the getHours method.

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);
}

Requirements

Version 1

See Also

Date Object Methods | getUTCHours Method | setHours Method | setUTCHours Method

Applies To: Date Object


getItem Method

Returns the item at the specified location.

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

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.

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

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

Requirements

Version 1

See Also

dimensions Method | lbound Method | toArray Method | ubound Method

Applies To: VBArray Object


getMilliseconds Method

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

dateObj.getMilliseconds()

The required dateObj reference is a Date object.

Remarks

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

The millisecond value returned can range from 0-999.

Example

The following example illustrates the use of the getMilliseconds method.

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);
}

Requirements

Version 3

See Also

Date Object Methods | getUTCMilliseconds Method | setMilliseconds Method | setUTCMilliseconds Method

Applies To: Date Object


getMinutes Method

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

dateObj.getMinutes()

The required dateObj reference is a Date object.

Remarks

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.

Example

The following example illustrates the use of the getMinutes method.

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);
}

Requirements

Version 3

See Also

Date Object Methods | getUTCMinutes Method | setMinutes Method | setUTCMinutes Method

Applies To: Date Object


getMonth Method

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

dateObj.getMonth()

The required dateObj reference is a Date object.

Remarks

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.

Example

The following example illustrates the use of the getMonth method.

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

Requirements

Version 1

See Also

Date Object Methods | getUTCMonth Method | setMonth Method | setUTCMonth Method

Applies To: Date Object


getSeconds Method

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

dateObj.getSeconds()

The required dateObj reference is a Date object.

Remarks

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.

Example

The following example illustrates the use of the getSeconds method.

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);
}

Requirements

Version 1

See Also

Date Object Methods | getUTCSeconds Method | setSeconds Method | setUTCSeconds Method

Applies To: Date Object


getTime Method

Returns the time value in a Date object.

dateObj.getTime()

The required dateObj reference is a Date object.

Remarks

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:

var MinMilli = 1000 * 60
var HrMilli = MinMilli * 60
var DyMilli = HrMilli * 24

Example

The following example illustrates the use of the getTime method.

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);
}

Requirements

Version 1

See Also

Date Object Methods | setTime Method

Applies To: Date Object


getTimezoneOffset Method

Returns the difference in minutes between the time on the host computer and Universal Coordinated Time (UTC).

dateObj.getTimezoneOffset()

The required dateObj reference is a Date object.

Remarks

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.

Example

The following example illustrates the use of the getTimezoneOffset method.

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);
}

Requirements

Version 1

See Also

Date Object Methods

Applies To: Date Object


getUTCDate Method

Returns the date in a Date object using Universal Coordinated Time (UTC).

dateObj.getUTCDate()

The required dateObj reference is a Date object.

Remarks

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.

Example

The following example illustrates the use of the getUTCDate method.

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);
}

Requirements

Version 3

See Also

Date Object Methods | getDate Method | setDate Method | setUTCDate Method

Applies To: Date Object


getUTCDay Method

Returns the day of the week value in a Date object using Universal Coordinated Time (UTC).

dateObj.getUTCDay()

The required dateObj reference is a Date object.

Remarks

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

Example

The following example illustrates the use of the getUTCDay method.

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]);
}

Requirements

Version 3

See Also

Date Object Methods | getDay Method

Applies To: Date Object


getUTCFullYear Method

Returns the year value in a Date object using Universal Coordinated Time (UTC).

dateObj.getUTCFullYear()

The required dateObj reference is a Date object.

Remarks

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.

Example

The following example illustrates the use of the getUTCFullYear method.

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);
}

Requirements

Version 3

See Also

Date Object Methods | getFullYear Method | setFullYear Method | setUTCFullYear Method

Applies To: Date Object


getUTCHours Method

Returns the hours value in a Date object using Universal Coordinated Time (UTC).

dateObj.getUTCHours()

The required dateObj reference is a Date object.

Remarks

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.

Example

The following example illustrates the use of the getUTCHours method.

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);
}

Requirements

Version 3

See Also

Date Object Methods | getHours Method | setHours Method | setUTCHours Method

Applies To: Date Object


getUTCMilliseconds Method

Returns the milliseconds value in a Date object using Universal Coordinated Time (UTC).

dateObj.getUTCMilliseconds()

The required dateObj reference is a Date object.

Remarks

To get the number of milliseconds in local time, use the getMilliseconds method.

The millisecond value returned can range from 0-999.

Example

The following example illustrates the use of the getUTCMilliseconds method.

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);
}

Requirements

Version 3

See Also

Date Object Methods | getMilliseconds Method | setMilliseconds Method | setUTCMilliseconds Method

Applies To: Date Object


getUTCMinutes Method

Returns the minutes value in a Date object using Universal Coordinated Time (UTC).

dateObj.getUTCMinutes()

The required dateObj reference is a Date object.

Remarks

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.

Example

The following example illustrates the use of the getUTCMinutes method.

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);
}

Requirements

Version 3

See Also

Date Object Methods | getMinutes Method | setMinutes Method | setUTCMinutes Method

Applies To: Date Object


getUTCMonth Method

Returns the month value in a Date object using Universal Coordinated Time (UTC).

dateObj.getUTCMonth()

The required dateObj reference is a Date object.

Remarks

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.

Example

The following example illustrates the use of the getUTCMonth method.

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);
}

Requirements

Version 3

See Also

Date Object Methods | getMonth Method | setMonth Method | setUTCMonth Method

Applies To: Date Object


getUTCSeconds Method

Returns the seconds value in a Date object using Universal Coordinated Time (UTC).

dateObj.getUTCSeconds()

The required dateObj reference is a Date object.

Remarks

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.

Example

The following example illustrates the use of the getUTCSeconds method.

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);
}

Requirements

Version 3

See Also

Date Object Methods | getSeconds Method | setSeconds Method | setUTCSeconds Method

Applies To: Date Object


getVarDate Method

Returns the VT_DATE value in a Date object.

dateObj.getVarDate()

The required dateObj reference is a Date object.

Remarks

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.

Requirements

Version 3

See Also

getDate Method | parse Method

Applies To: Date Object


getYear Method

Returns the year value in a Date object.

dateObj.getYear()

The required dateObj reference is a Date object.

Remarks

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

Example

The following example illustrates the use of the getYear method:

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

Requirements

Version 1

See Also

Date Object Methods | getFullYear Method | getUTCFullYear Method | setFullYear Method | setUTCFullYear Method | setYear Method

Applies To: Date Object


indexOf Method

Returns the character position where the first occurrence of a substring occurs within a String object.

strObj.indexOf(subString[, startIndex])

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.

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.

Example

The following example illustrates the use of the indexOf method.

function IndexDemo(str2){
   var str1 = "BABEBIBOBUBABEBIBOBU"
   var s = str1.indexOf(str2);
   return(s);
}

Requirements

Version 1

See Also

lastIndexOf Method | String Object Methods | String Object Properties

Applies To: String Object


isFinite Method

Returns a Boolean value that indicates if a supplied number is finite.

isFinite(number)

The required number argument is any numeric value.

Remarks

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.

Requirements

Version 3

See Also

isNaN Method

Applies To: Global Object


isNaN Method

Returns a Boolean value that indicates whether a value is the reserved value NaN (not a number).

isNaN(numValue)

The required numValue is the value to be tested against NAN.

Remarks

The isNaN function returns true if the value is NaN, and false otherwise. You typically use this function 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.

Requirements

Version 1

See Also

isFinite Method | NaN Property (Global) | parseFloat Method | parseInt Method

Applies To: Global Object


italics Method

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

strVariable.italics( )
"String Literal".italics( )

Remarks

The following example demonstrates how the italics method works:

var strVariable = "This is a string";
strVariable = strVariable.italics( );

The value of strVariable after the last statement is:

<I>This is a string</I>

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

Requirements

Version 1

See Also

bold Method | String Object Methods | String Object Properties

Applies To: String Object


item Method

Returns the current item in the collection.

enumObj.item()

The required enumObj reference is any Enumerator object.

Remarks

The item method returns the current item. If the collection is empty or the current item is undefined, it returns undefined.

Example

In following code, the item method is used to return a member of the Drives collection.

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);
}

Requirements

Version 3

See Also

atEnd Method | moveFirst Method | moveNext Method

Applies To: Enumerator Object


join Method

Returns a string value consisting of all the elements of an array concatenated together and separated by the specified separator character.

arrayObj.join(separator)

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.

Remarks

If any element of the array is undefined or null, it is treated as an empty string.

Example

The following example illustrates the use of the join method.

function JoinDemo(){
   var a, b;
   a = new Array(0,1,2,3,4);
   b = a.join("-");
   return(b);
}

Requirements

Version 2

See Also

Array Object Methods | String Object

Applies To: Array Object


lastIndexOf Method

Returns the last occurrence of a substring within a String object.

strObj.lastIndexOf(substring[, startindex])

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.

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.

function lastIndexDemo(str2)
{
   var str1 = "BABEBIBOBUBABEBIBOBU"
   var s = str1.lastIndexOf(str2);
   return(s);
}

Requirements

Version 1

See Also

indexOf Method | String Object Methods | String Object Properties

Applies To: String Object


lbound Method

Returns the lowest index value used in the specified dimension of a VBArray.

safeArray.lbound(dimension)

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.

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.

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.

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

Requirements

Version 3

See Also

dimensions Method | getItem Method | toArray Method | ubound Method

Applies To: VBArray Object


link Method

Places an HTML anchor with an HREF attribute around the text in a String object.

strVariable.link(linkstring)
"String Literal".link(linkstring)

The linkstring argument is the text that you want to place in the HREF attribute of the HTML anchor.

Remarks

Call the link method to create a hyperlink out of a String object. The following is an example of how the method accomplishes this:

var strVariable = "This is a hyperlink";
strVariable = strVariable.link("http://www.microsoft.com");

The value of strVariable after the last statement is:

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

Requirements

Version 1

See Also

anchor Method | String Object Methods | String Object Properties

Applies To: String Object


localeCompare Method

Returns a value indicating whether two strings are equivalent in the current locale.

stringVar.localeCompare(stringExp)

Arguments

stringVar
Required. A String object or literal.
stringExp
Required. String to compare to stringVar.

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.

Requirements

Version 5.5

See Also

toLocalString

Applies To: String Object


log Method

Returns the natural logarithm of a number.

Math.log(number)

The required number argument is a numeric expression for which the natural logarithm is sought.

Return Value

The return value is the natural logarithm of number. The base is e.

Requirements

Version 1

See Also

Math Object Methods

Applies To: Math Object


match Method

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

stringObj.match(rgExp)

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.

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.

Example

The following example illustrates the use of the match method.

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.

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.

var r, re = "Spain";
r = "The rain in Spain".replace(re, "Canada");

Requirements

Version 3

See Also

exec Method | RegExp Object | replace Method | search Method | String Object Methods | test Method

Applies To: String Object


max Method

Returns the greater of zero or more supplied numeric expressions.

Math.max([number1[, number2[. . . [, numberN]]]])

The optional number1, number2, . . ., numberN arguments are numeric expressions to be evaluated.

Remarks

If no arguments are provided, the return value is equal to NEGATIVE_INFINITY. If any argument is NaN, the return value is also NaN.

Requirements

Version 1

See Also

Math Object Methods | min Method| NEGATIVE_INFINITY Property

Applies To: Math Object


min Method

Returns the lesser of zero or more supplied numeric expressions.

Math.min([number1[, number2[. . . [,numberN]]]])

The optional number1, number2, . . ., numberN arguments are numeric expressions to be evaluated.

Remarks

If no arguments are provided, the return value is equal to POSITIVE_INFINITY. If any argument is NaN, the return value is also NaN.

Requirements

Version 1

See Also

Math Object Methods | max Method | POSITIVE_INFINITY Property

Applies To: Math Object


moveFirst Method

Resets the current item in the collection to the first item.

enumObj.moveFirst( )

The required enumObj reference is any Enumerator object.

Remarks

If there are no items in the collection, the current item is set to undefined.

Example

In following example, the moveFirst method is used to evaluate members of the Drives collection from the beginning of the list:

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 1st 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.
}

Requirements

Version 3

See Also

atEnd Method | item Method | moveNext Method

Applies To: Enumerator Object


moveNext Method

Moves the current item to the next item in the collection.

enumObj.moveNext( )

The required enumObj reference is any Enumerator object.

Remarks

If the enumerator is at the end of the collection or the collection is empty, the current item is set to undefined.

In following example, the moveNext method is used to move to the next drive in the Drives collection:

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

Requirements

Version 3

See Also

atEnd Method | item Method | moveFirst Method

Applies To: Enumerator Object


parse Method

Parses a string containing a date, and returns the number of milliseconds between that date and midnight, January 1, 1970.

Date.parse(dateVal)

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.

Remarks

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.

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.

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:

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

Requirements

Version 1

See Also

Date Object Methods

Applies To: Date Object


parseFloat Method

Returns a floating-point number converted from a string.

parseFloat(numString)

The required numString argument is a string that contains a floating-point number.

Remarks

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.

parseFloat("abc")      // Returns NaN.
parseFloat("1.2abc")   // Returns 1.2.

You can test for NaN using the isNaN method.

Requirements

Version 1

See Also

isNaN Method | parseInt Method | String Object

Applies To: Global Object


parseInt Method

Returns an integer converted from a string.

parseInt(numString, [radix])

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.

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.

parseInt("abc")     // Returns NaN.
parseInt("12abc")   // Returns 12.

You can test for NaN using the isNaN method.

Requirements

Version 1

See Also

isNaN Method | parseFloat Method | String Object | valueOf Method

Applies To: Global Object


pop Method

Removes the last element from an array and returns it.

arrayObj.pop( )

The required arrayObj reference is an Array object.

Remarks

If the array is empty, undefined is returned.

Requirements

Version 5.5

See Also

push Method

Applies To: Array Object


pow Method

Returns the value of a base expression taken to a specified power.

Math.pow(base, exponent)

Arguments

base
Required. The base value of the expression.
exponent
Required. The exponent value of the expression.

Example

In the following example, a numeric expression equal to baseexponent returns 1000.

Math.pow(10,3);

Requirements

Version 1

See Also

Math Object Methods

Applies To: Math Object


push Method

Appends new elements to an array, and returns the new length of the array.

arrayObj.push([item1 [item2 [. . . [itemN ]]]])

Arguments

arrayObj
Required. An Array object.
item, item2,. . ., itemN
Optional. New elements of the Array.

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.

Requirements

Version 5.5

See Also

concat Method | pop Method

Applies To: Array Object


random Method

Returns a pseudorandom number between 0 and 1.

Math.random( )

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.

Requirements

Version 1

See Also

Math Object Methods

Applies To: Math Object


replace Method

Returns a copy of a string with text replaced using a regular expression or search string.

stringObj.replace(rgExp, replaceText)

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.

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.

Example

The following example illustrates the use of the replace method to replace the first instance of the word "The" with the word "A."

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 "A" with "The".
   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.

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").

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."));

Requirements

Version 1

See Also

exec Method | match Method | RegExp Object | search Method | String Object Methods | test Method

Applies To: String Object


reverse Method

Returns an Array object with the elements reversed.

arrayObj.reverse( )

The required arrayObj reference is an Array object.

Remarks

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.

Example

The following example illustrates the use of the reverse method.

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

Requirements

Version 2

See Also

Array Object Methods

Applies To: Array Object


round Method

Returns a supplied numeric expression rounded to the nearest integer.

Math.round(number)

The required number argument is the value to be rounded to the nearest integer.

Remarks

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.

Requirements

Version 1

See Also

Math Object Methods

Applies To: Math Object


search Method

Returns the position of the first substring match in a regular expression search.

stringObj.search(rgExp)

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.

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.

Example

The following example illustrates the use of the search method.

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

Requirements

Version 3

See Also

exec Method | match Method | Regular Expression Object | Regular Expression Syntax | replace Method | String Object Methods | test Method

Applies To: String Object


setDate Method

Sets the numeric date of the Date object using local time.

dateObj.setDate(numDate)

Arguments

dateObj
Required. Any Date object.
numDate
Required. A numeric value equal to the numeric date.

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.

Example

The following example illustrates the use of the setDate method.

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

Requirements

Version 3

See Also

Date Object Methods | getDate Method | getUTCDate Method | setUTCDate Method

Applies To: Date Object


setFullYear Method

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

dateObj.setFullYear(numYear[, numMonth[, numDate]])

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.

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.

Example

The following example illustrates the use of the setFullYear method:

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

Requirements

Version 3

See Also

Date Object Methods | getFullYear Method | getUTCFullYear Method | setUTCFullYear Method

Applies To: Date Object


setHours Method

Sets the hour value in the Date object using local time.

dateObj.setHours(numHours[, numMin[, numSec[, numMilli]]])

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.

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.

Example

The following example illustrates the use of the setHours method.

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

Requirements

Version 3

See Also

Date Object Methods | getHours Method | getUTCHours Method | setUTCHours Method

Applies To: Date Object


setMilliseconds Method

Sets the milliseconds value in the Date object using local time.

dateObj.setMilliseconds(numMilli)

Arguments

dateObj
Required. Any Date object.
numMilli
Required. A numeric value equal to the millisecond value.

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.

Example

The following example illustrates the use of the setMilliseconds method.

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

Requirements

Version 3

See Also

Date Object Methods | getMilliseconds Method | getUTCMilliseconds Method | setUTCMilliseconds Method

Applies To: Date Object


setMinutes Method

Sets the minutes value in the Date object using local time.

dateObj.setMinutes(numMinutes[, numSeconds[, numMilli]])

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.

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.

Example

The following example illustrates the use of the setMinutes method.

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

Requirements

Version 1

See Also

Date Object Methods | getMinutes Method | getUTCMinutes Method | setUTCMinutes Method

Applies To: Date Object


setMonth Method

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

dateObj.setMonth(numMonth[, dateVal])

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.

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

Example

The following example illustrates the use of the setMonth method.

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

Requirements

Version 1

See Also

Date Object Methods | getMonth Method | getUTCMonth Method | setUTCMonth Method

Applies To: Date Object


setSeconds Method

Sets the seconds value in the Date object using local time.

dateObj.setSeconds(numSeconds[, numMilli])

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.

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

Example

The following example illustrates the use of the setSeconds method.

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

Requirements

Version 1

See Also

Date Object Methods | getSeconds Method | getUTCSeconds Method | setUTCSeconds Method

Applies To: Date Object


setTime Method

Sets the date and time value in the Date object.

dateObj.setTime(milliseconds)

Arguments

dateObj
Required. Any Date object.
milliseconds
Required. An integer value representing the number of elapsed seconds since midnight, January 1, 1970 GMT.

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.

Example

The following example illustrates the use of the setTime method.

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

Requirements

Version 1

See Also

Date Object Methods | getTime Method

Applies To: Date Object


setUTCDate Method

Sets the numeric date in the Date object using Universal Coordinated Time (UTC).

dateObj.setUTCDate(numDate)

Arguments

dateObj
Required. Any Date object.
numDate
Required. A numeric value equal to the numeric date.

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.

Example

The following example illustrates the use of the setUTCDate method.

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

Requirements

Version 3

See Also

Date Object Methods | getDate Method | getUTCDate Method | setDate Method

Applies To: Date Object


setUTCFullYear Method

Sets the year value in the Date object using Universal Coordinated Time (UTC).

dateObj.setUTCFullYear(numYear[, numMonth[, numDate]])

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.

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.

Example

The following example illustrates the use of the setUTCFullYear method.

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

Requirements

Version 3

See Also

Date Object Methods | getFullYear Method | getUTCFullYear Method | setFullYear Method

Applies To: Date Object


setUTCHours Method

Sets the hours value in the Date object using Universal Coordinated Time (UTC).

dateObj.setUTCHours(numHours[, numMin[, numSec[, numMilli]]])

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.

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

Example

The following example illustrates the use of the setUTCHours method.

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

Requirements

Version 3

See Also

Date Object Methods | getHours Method | getUTCHours Method | setHours Method

Applies To: Date Object


setUTCMilliseconds Method

Sets the milliseconds value in the Date object using Universal Coordinated Time (UTC).

dateObj.setUTCMilliseconds(numMilli)

Arguments

dateObj
Required. Any Date object.
numMilli
Required. A numeric value equal to the millisecond value.

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.

Example

The following example illustrates the use of the setUTCMilliseconds method.

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

Requirements

Version 3

See Also

Date Object Methods | getMilliseconds Method | getUTCMilliseconds Method | setMilliseconds Method

Applies To: Date Object


setUTCMinutes Method

Sets the minutes value in the Date object using Universal Coordinated Time (UTC).

dateObj.setUTCMinutes(numMinutes[, numSeconds[, numMilli]])

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.

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

Example

The following example illustrates the use of the setUTCMinutes method:

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

Requirements

Version 3

See Also

Date Object Methods | getMinutes Method | getUTCMinutes Method | setMinutes Method

Applies To: Date Object


setUTCMonth Method

Sets the month value in the Date object using Universal Coordinated Time (UTC).

dateObj.setUTCMonth(numMonth[, dateVal])

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.

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

Example

The following example illustrates the use of the setUTCMonth method.

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

Requirements

Version 3

See Also

Date Object Methods | getMonth Method | getUTCMonth Method | setMonth Method

Applies To: Date Object


setUTCSeconds Method

Sets the seconds value in the Date object using Universal Coordinated Time (UTC).

dateObj.setUTCSeconds(numSeconds[, numMilli])

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.

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

Example

The following example illustrates the use of the setSeconds method.

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

Requirements

Version 3

See Also

Date Object Methods | getSeconds Method | getUTCSeconds Method | setSeconds Method

Applies To: Date Object


setYear Method

Sets the year value in the Date object.

dateObj.setYear(numYear)

Arguments

dateObj
Required. Any Date object.
numYear
Required. A numeric value equal to the year minus 1900.

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

Requirements

Version 1

See Also

Date Object Methods | getFullYear Method | getUTCFullYear Method | getYear Method | setFullYear Method | setUTCFullYear Method

Applies To: Date Object


shift Method

Removes the first element from an array and returns it.

arrayObj.shift( )

The required arrayObj reference is an Array object.

Remarks

The shift method removes the first element from an array and returns it.

Requirements

Version 5.5

See Also

unshift Method

Applies To: Array Object


sin Method

Returns the sine of a number.

Math.sin(number)

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

Remarks

The return value is the sine of the numeric argument.

Requirements

Version 1

See Also

acos Method | asin Method | atan Method | cos Method | Math Object Methods | tan Method

Applies To: Math Object


slice Method (Array)

Returns a section of an array.

arrayObj.slice(start, [end])

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.

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.

Example

In the following example, all but the last element of myArray is copied into newArray:

newArray = myArray.slice(0, -1)

Requirements

Version 3

See Also

slice Method (String) | String Object

Applies To: Array Object


slice Method (String)

Returns a section of a string.

stringObj.slice(start, [end])

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.

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.

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.

str1.slice(0)
str2.slice(0,-1)

Requirements

Version 3

See Also

Array Object | slice Method (Array) | String Object Methods

Applies To: String Object


small Method

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

strVariable.small( )
"String Literal".small( )

Remarks

The following example illustrates the use of the small method:

var strVariable = "This is a string";
strVariable = strVariable.small( );

The value of strVariable after the last statement is:

<SMALL>This is a string</SMALL>

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

Requirements

Version 1

See Also

big Method | String Object Methods | String Object Properties

Applies To: String Object


sort Method

Returns an Array object with the elements sorted.

arrayobj.sort(sortFunction)

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.

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.

Example

The following example illustrates the use of the sort method.

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

Requirements

Version 2

See Also

Array Object Methods

Applies To: Array Object


splice Method

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]]]])

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.

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.

Requirements

Version 5.5

See Also

slice Method (Array)

Applies To: Array Object


split Method

Returns the array of strings that results when a string is separated into substrings.

stringObj.split([separator[, limit]])

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.

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.

Example

The following example illustrates the use of the split method.

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);
}

Requirements

Version 3

See Also

concat Method | RegExp Object | Regular Expression Object | Regular Expression Syntax | String Object Methods

Applies To: String Object


sqrt Method

Returns the square root of a number.

Math.sqrt(number)

The required number argument is a numeric expression.

Remarks

If number is negative, the return value is NaN.

Requirements

Version 1

See Also

Math Object Methods | SQRT1_2 Property | SQRT2 Property

Applies To: Math Object


strike Method

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

strVariable.strike( )
"String Literal".strike( )

Remarks

The following example demonstrates how the strike method works:

var strVariable = "This is a string object";
strVariable = strVariable.strike( );

The value of strVariable after the last statement is:

<STRIKE>This is a string object</STRIKE>

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

Requirements

Version 1

See Also

String Object Methods | String Object Properties

Applies To: String Object


sub Method

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

strVariable.sub( )
"String Literal".sub( )

Remarks

The following example demonstrates how the sub method works:

var strVariable = "This is a string object";
strVariable = strVariable.sub( );

The value of strVariable after the last statement is:

<SUB>This is a string object</SUB>

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

Requirements

Version 1

See Also

String Object Methods | String Object Properties | sup Method

Applies To: String Object


substr Method

Returns a substring beginning at a specified location and having a specified length.

stringvar.substr(start [, length ])

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.

Remarks

If length is zero or negative, an empty string is returned. If not specified, the substring continues to the end of stringvar.

Example

The following example illustrates the use of the substr method.

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".
}

Requirements

Version 3

See Also

String Object Methods | String Object Properties | substring Method

Applies To: String Object


substring Method

Returns the substring at the specified location within a String object.

strVariable.substring(start, end)
"String Literal".substring(start, end)

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.

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.

Example

The following example illustrates the use of the substring method.

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

Requirements

Version 1

See Also

String Object Methods | String Object Properties | substr Method

Applies To: String Object


sup Method

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

strVariable.sup( )
"String Literal".sup( )

Remarks

The following example demonstrates how the sup method works.

var strVariable = "This is a string object";
strVariable = strVariable.sup( );

The value of strVariable after the last statement is:

<SUP>This is a string object</SUP>

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

Requirements

Version 1

See Also

String Object Methods | String Object Properties | sub Method

Applies To: String Object


tan Method

Returns the tangent of a number.

Math.tan(number)

The required number argument is a numeric expression for which the tangent is sought.

Remarks

The return value is the tangent of number.

Requirements

Version 1

See Also

acos Method | asin Method | atan Method | atan2 Method | cos Method | Math Object Methods | sin Method

Applies To: Math Object


test Method

Returns a Boolean value that indicates whether or not a pattern exists in a searched string.

rgExp.test(str)

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.

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.

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:

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

Requirements

Version 3

See Also

RegExp Object | Regular Expression Object | Regular Expression Object Methods | Regular Expression Object Properties | Regular Expression Syntax

Applies To: Regular Expression Object


toArray Method

Returns a standard JScript array converted from a VBArray.

safeArray.toArray( )

The required safeArray reference is a VBArray object.

Remarks

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.

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

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

Requirements

Version 3

See Also

dimensions Method | getItem Method | lbound Method | ubound Method

Applies To: VBArray Object


toDateString Method

Returns a date as a string value.

objDate.toDateString( )

The required objDate reference is a Date object.

Remarks

The toDateString method returns a string value containing the date, in the current time zone, in a convenient, easily read format.

Requirements

Version 5.5

See Also

toTimeString Method | toLocaleDateString Method

Applies To: Date Object


toExponential Method

Returns a string containing a number represented in exponential notation.

numObj.toExponential([fractionDigits])

Arguments

numObj
Required. A Number object.
fractionDigits
Optional. Number of digits after the decimal point. Must be in the range 0 – 20, inclusive.

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.

Requirements

Version 5.5

See Also

toFixed Method | toPrecision Method

Applies To: Number Object


toFixed Method

Returns a string representing a number in fixed-point notation.

numObj.toFixed([fractionDigits])

Arguments

numObj
Required A Number object.
fractionDigits
Optional. Number of digits after the decimal point. Must be in the range 0 – 20, inclusive.

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.

Requirements

Version 5.5

See Also

toExponential Method | toPrecision Method

Applies To: Number Object


toGMTString Method

Returns a date converted to a string using Greenwich Mean Time(GMT).

dateObj.toGMTString()

The required dateObj reference is any Date object.

Remarks

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

Requirements

Version 1

See Also

Date Object Methods | toUTCString Method

Applies To: Date Object


toLocaleDateString Method

Returns a date as a string value appropriate to the host environment's current locale.

objDate.toLocaleDateString( )

The required objDate reference is a Date object.

Remarks

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.

Requirements

Version 5.5

See Also

toDateString Method | toLocaleTimeString Method

Applies To: Date Object


toLocaleLowerCase Method

Returns a string where all alphabetic characters have been converted to lowercase, taking into account the host environment's current locale.

stringVar.tolocaleLowerCase( )

The required stringVar reference is a String object, value, or literal.

Remarks

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.

Requirements

Version 5.5

See Also

toLocaleUpperCase Method | toLowerCase Method

Applies To: String Object


toLocaleString Method

Returns a date converted to a string using the current locale.

dateObj.toLocaleString()

The required dateObj is any Date object.

Remarks

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

Example

The following example illustrates the use of the toLocaleString method.

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
}

Requirements

Version 1

See Also

Date Object Methods

Applies To: Array Object | Date Object | Number Object | Object Object


toLocaleTimeString Method

Returns a time as a string value appropriate to the host environment's current locale.

objDate.toLocaleTimeString( )

The required objDate reference is a Date object.

Remarks

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.

Requirements

Version 5.5

See Also

ToTimeString Method | toLocaleDateString Method

Applies To: Date Object


toLocaleUpperCase Method

Returns a string where all alphabetic characters have been converted to uppercase, taking into account the host environment's current locale.

stringVar.tolocaleUpperCase( )

The required stringVar reference is a String object, value, or literal.

Remarks

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.

Requirements

Version 5.5

See Also

toLocaleLowerCase Method | toUpperCase Method

Applies To: String Object


toLowerCase Method

Returns a string where all alphabetic characters have been converted to lowercase.

strVariable.toLowerCase( )
"String Literal".toLowerCase( )

Remarks

The toLowerCase method has no effect on nonalphabetic characters.

The following example demonstrates the effects of the toLowerCase method:

var strVariable = "This is a STRING object";
strVariable = strVariable.toLowerCase( );

The value of strVariable after the last statement is:

this is a string object

Requirements

Version 1

See Also

String Object Methods | String Object Properties | toUpperCase Method

Applies To: String Object


toPrecision Method

Returns a string containing a number represented either in exponential or fixed-point notation with a specified number of digits.

numObj.toPrecision ([precision])

Arguments

numObj
Required. A Number object.
precision
Optional. Number of significant digits. Must be in the range 1 – 21, inclusive.

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.

Requirements

Version 5.5

See Also

toFixed Method | toExponential Method

Applies To: Number Object


toString Method

Returns a string representation of an object.

objectname.toString([radix])

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.

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

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.

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

Requirements

Version 2

See Also

function Statement

Applies To: Array Object | Boolean Object | Date Object | Error Object | Function Object | Number Object | Object Object | String Object


toTimeString Method

Returns a time as a string value.

objDate.toTimeString( )

The required objDate reference is a Date object.

Remarks

The toTimeString method returns a string value containing the time, in the current time zone, in a convenient, easily read format.

Requirements

Version 5.5

See Also

toDateString Method | toLocaleTimeString Method

Applies To: Date Object


toUpperCase Method

Returns a string where all alphabetic characters have been converted to uppercase.

strVariable.toUpperCase( )
"String Literal".toUpperCase( )

Remarks

The toUpperCase method has no effect on non-alphabetic characters.

Example

The following example demonstrates the effects of the toUpperCase method:

var strVariable = "This is a STRING object";
strVariable = strVariable.toUpperCase( );

The value of strVariable after the last statement is:

THIS IS A STRING OBJECT

Requirements

Version 1

See Also

String Object Methods | String Object Properties | toLowerCase Method

Applies To: String Object


toUTCString Method

Returns a date converted to a string using Universal Coordinated Time (UTC).

dateObj.toUTCString()

The required dateObj reference is any Date object.

Remarks

The toUTCString method returns a String object that contains the date formatted using UTC convention in a convenient, easily read form.

Example

The following example illustrates the use of the toUTCString method.

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

Requirements

Version 3

See Also

Date Object Methods | toGMTString Method

Applies To: Date Object


ubound Method

Returns the highest index value used in the specified dimension of the VBArray.

safeArray.ubound(dimension)

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.

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.

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.

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

Requirements

Version 3

See Also

dimensions Method | getItem Method | lbound Method | toArray Method

Applies To: VBArray Object


unescape Method

Decodes String objects encoded with the escape method.

unescape(charString)

The required charString argument is a String object or literal to be decoded.

Remarks

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 The unescape method should not be used to decode Uniform Resource Identifiers (URI). Use decodeURI and decodeURIComponent methods instead.

Requirements

Version 1

See Also

DecodeURI Method | decodeURIComponent Method | escape Method | String Object

Applies To: Global Object


unshift Method

Returns an array with specified elements inserted at the beginning.

arrayObj.unshift([item1[, item2 [, . . . [, itemN]]]])

Arguments

arrayObj
Required. An Array object.
item1, item2,. . ., itemN
Optional. Elements to insert at the start of the Array.

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.

Requirements

Version 5.5

See Also

shift Method

Applies To: Array Object


UTC Method

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]]]])

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.

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 If year is between 0 and 99, use 1900 + year for the year.

Example

The following example illustrates the use of the UTC method.

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

Requirements

Version 1

See Also

Date Object Methods | setTime Method

Applies To: Date Object


valueOf Method

Returns the primitive value of the specified object.

object.valueOf( )

The required object reference is any intrinsic JScript object.

Remarks

The valueOf method is defined differently for each intrinsic JScript object.

Object | Return Value
Array | The elements of the array are converted into strings, and the strings are concatenated together, separated by commas. This behaves the same as the Array.toString and Array.join methods.
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.

Requirements

Version 2

See Also

toString Method

Applies To: Array Object | Boolean Object | Date Object | Function Object | Number Object | Object Object | String Object


JScript Objects

The following table lists JScript 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
Creates a new Boolean value. | Boolean Object
Enables basic storage and retrieval of dates and times. | Date Object
Object that stores data key, item pairs. | Dictionary 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
Provides access to a computer's file system. | FileSystemObject Object
Creates a new function. | Function Object
An intrinsic object whose purpose is to collect global methods into one object. | Global Object
A 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


ActiveXObject Object

Enables and returns a reference to an Automation object.

newObj = new ActiveXObject(servername.typename[, location])

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.

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:

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.

// 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":

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.

Requirements

Version 1

See Also

GetObject Function


Array Object

Provides support for creation of arrays of any data type.

arrayObj = new Array()
arrayObj = new Array([size])
arrayObj = new Array([element0[, element1[, ...[, elementN]]]])

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.

Remarks

After an array is created, the individual elements of the array can be accessed using [ ] notation, for example:

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.

Properties

constructor Property | length Property | prototype Property

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

Requirements

Version 2

See Also

new Operator


arguments Object

An object representing the arguments to the currently executing function, and the functions that called it.

[function.]arguments[n]

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.

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 0…n properties of the arguments object.

Example

The following example illustrates the use of the arguments object.

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

Requirements

Version 1

See Also

0…n Properties | callee Property | length Property


Boolean Object

Creates a new Boolean value.

Syntax

boolObj = new Boolean([boolValue])

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.

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.

Properties

constructor Property | prototype Property

Methods

toString Method | valueOf Method

Requirements

Version 2

See Also

new Operator | var Statement


Date Object

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]]]])

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.

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.

Error

The following example illustrates the use of the Date object.

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

Properties

constructor Property | prototype Property

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 | 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 | toGMTString Method | toLocaleString Method | toUTCString Method | toString Method | valueOf Method | parse Method | UTC Method

Requirements

Version 1

See Also

new Operator | var Statement


Enumerator Object

Enables enumeration of items in a collection.

enumObj = new Enumerator([collection])

Arguments

enumObj
Required. The variable name to which the Enumerator object is assigned.
collection
Optional. Any Collection object.

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.

Example

The following code shows the usage of the Enumerator object:

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

Properties

The Enumerator object has no properties.

Methods

atEnd Method | item Method | moveFirst Method | moveNext Method

Requirements

Version 3


Error Object

Contains information about errors.

errorObj = new Error()
errorObj = new Error([number])
errorObj = new Error([number[, description]])

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.

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.

Example

The following example illustrates the use of the implicitly created Error object.

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".
}

Methods

The Error object has no methods.

Properties

description Property | number Property

Requirements

Version 5

See Also

new Operator | throw Statement | try...catch Statement | var Statement


Function Object

Creates a new function.

Syntax 1

function functionName([argname1 [, ...[, argnameN]]])
{
   body
}

Syntax 2

functionName = new Function( [argname1, [... argnameN,]] body );

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.

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:

Example 1

function add(x, y)
{
   return(x + y);            //Perform addition and return results.
}

Example 2

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:

add(2, 3);
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.

Properties

arguments Property | caller Property | constructor Property | prototype Property

Methods

toString Method | valueOf Method

Requirements

Version 2

See Also

function Statement | new Operator | var Statement


Global Object

An intrinsic object whose purpose is to collect global methods into one object.

The Global object has no syntax. You call its methods directly.

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.

Properties

Infinity Property | NaN Property

Methods

escape Method | eval Method | isFinite Method | isNaN Method | parseFloat Method | parseInt Method | unescape Method

Requirements

Version 5

See Also

Object Object


Math Object

An intrinsic object that provides basic mathematics functionality and constants.

Math.[{property | method}]

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.

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.

Properties

E Property | LN2 Property | LN10 Property | LOG2E Property | LOG10E Property | PI Property | SQRT1_2 Property | SQRT2 Property

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

Requirements

Version 1

See Also

Number Object


Number Object

An object representation of the number data type and placeholder for numeric constants.

numObj = new Number(value)

Arguments

numobj
Required. The variable name to which the Number object is assigned.
value
Required. The numeric value of the Number object being created.

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.

Properties

MAX_VALUE Property | MIN_VALUE Property | NaN Property | NEGATIVE_INFINITY Property | POSITIVE_INFINITY Property | constructor Property | prototype Property

Methods

toLocaleString Method | toString Method | valueOf Method

Requirements

Version 1

See Also

Math Object | new Operator


Object Object

Provides functionality common to all JScript objects.

obj = new Object([value])

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.

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.

Properties

prototype Property | constructor Property

Methods

toLocaleString Method | toString Method | valueOf Method

Requirements

Version 3

See Also

Function Object | Global Object


RegExp Object

An intrinsic global object that stores information about the results of regular expression pattern matches.

RegExp.property

The required property argument can be any one of the RegExp object properties.

Remarks

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

Example

The following example illustrates the use of the global RegExp object.

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);
}

Properties

$1...$9 Properties | index Property | input Property | lastIndex Property | lastMatch Property | lastParen Property | leftContext Property | rightContext Property

Methods

The RegExp object has no methods.

Requirements

Version 3

See Also

Regular Expression Object | Regular Expression Syntax | String Object


Regular Expression Object

An object that contains a regular expression pattern along with flags that identify how to apply the pattern.

Syntax 1

re = /pattern/[flags]

Syntax 2

re = new RegExp("pattern",["flags"])

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)

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.

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:

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

Properties

lastIndex Property | source Property

Methods

compile Method | exec Method | test Method

Requirements

Version 3

See Also

RegExp Object | Regular Expression Syntax | String Object


String Object

Allows manipulation and formatting of text strings and determination and location of substrings within strings.

Syntax

newString = new String(["stringLiteral"])

Arguments

newString
Required. The variable name to which the String object is assigned.
stringLiteral
Optional. Any group of Unicode characters.

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:

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:

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.

Properties

constructor Property | length Property | prototype Property

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 | match Method | replace Method | search Method | slice Method | small Method | split Method | strike Method | sub Method | substr Method | substring Method | sup Method | toLowerCase Method | toUpperCase Method | toString Method | valueOf Method

Requirements

Version 1

See Also

new Operator


VBArray Object

Provides access to Visual Basic safe arrays.

varName = new VBArray(safeArray)

Arguments

varName
Required. The variable name to which the VBArray is assigned.
safeArray
Required. A VBArray value.

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.

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

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

Properties

The VBArray object has no properties.

Methods

dimensions Method | getItem Method | lbound Method | toArray Method | ubound Method

Requirements

Version 3

See Also

Array Object


JScript Operators

The following table lists JScript operators

Description | Language Element
Sums two numbers or concatenates two strings. | Addition Operator (+)
Assigns a value to a variable. | 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 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 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 two numbers and returns a numeric result. | Division 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
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 two numbers and returns the remainder. | Modulus 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 (!==)
List containing information about the execution precedence of JScript operators. | Operator Precedence
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 (-)
Performs an unsigned right shift of the bits in an expression. | Unsigned Right Shift Operator (>>>)
Prevents an expression from returning a value. | void Operator


Addition Assignment Operator (+=)

Adds the value of an expression to the value of a variable and assigns the result to the variable.

result += expression

Arguments

result
Any variable.
expression
Any expression.

Remarks

Using this operator is exactly the same as specifying:

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

Requirements

Version 1

See Also

+ Operator | Operator Precedence | Operator Summary


Addition Operator (+)

Adds the value of one numeric expression to another or concatenates two strings.

result = expression1 + expression2

Arguments

result
Any variable.
expression1
Any expression.
expression2
Any expression.

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

Requirements

Version 1

See Also

+= Operator | Operator Precedence | Operator Summary


Assignment Operator (=)

Assigns a value to a variable.

result = expression

Arguments

result
Any variable.
expression
Any numeric expression.

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:

j = k = l = 0;

j, k, and l equal zero after the example statement is executed.

Requirements

Version 1

See Also

Operator Precedence | Operator Summary


Bitwise AND 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.

result &= expression

Arguments

result
Any variable.
expression
Any expression.

Remarks

Using this operator is exactly the same as specifying:

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:

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.

Requirements

Version 1

See Also

& Operator | Operator Precedence | Operator Summary


Bitwise AND Operator (&)

Performs a bitwise AND on two expressions.

result = expression1 & expression2

Arguments

result
Any variable.
expression1
Any expression.
expression2
Any expression.

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:

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.

Requirements

Version 1

See Also

&= Operator | Operator Precedence | Operator Summary


Bitwise Left Shift Operator (<<)

Left shifts the bits of an expression.

result = expression1 << expression2

Arguments

result
Any variable.
expression1
Any expression.
expression2
Any expression.

Remarks

The << operator shifts the bits of expression1 left by the number of bits specified in expression2. For example:

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

Requirements

Version 1

See Also

<<= Operator | >> Operator | >>> Operator | Operator Precedence | Operator Summary


Bitwise NOT Operator (~)

Performs a bitwise NOT (negation) on an expression.

result = ~ expression

Arguments

result
Any variable.
expression
Any expression.

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:

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.

Requirements

Version 1

See Also

! Operator | Operator Precedence | Operator Summary


Bitwise OR Assignment Operator (|=)

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

Arguments

result
Any variable.
expression
Any expression.

Remarks

Using this operator is exactly the same as specifying:

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:

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.

Requirements

Version 1

See Also

| Operator | Operator Precedence | Operator Summary


Bitwise OR Operator (|)

Performs a bitwise OR on two expressions.

result = expression1 | expression2

Arguments

result
Any variable.
expression1
Any expression.
expression2
Any expression.

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:

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.

Requirements

Version 1

See Also

|= Operator | Operator Precedence | Operator Summary


Bitwise Right Shift Operator (>>)

Right shifts the bits of an expression, maintaining sign.

result = expression1 >> expression2

Arguments

result
Any variable.
expression1
Any expression.
expression2
Any expression.

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

var temp
temp = -14 >> 2

Requirements

Version 1

See Also

<< Operator | >>= Operator | >>> Operator | Operator Precedence | Operator Summary


Bitwise XOR Assignment Operator (^=)

Performs a bitwise exclusive OR on a variable and an expression and assigns the result to the variable.

result ^= expression

Arguments

result
Any variable.
expression
Any expression.

Remarks

Using the ^= operator is exactly the same as specifying:

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:

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.

Requirements

Version 1

See Also

^ Operator | Operator Precedence | Operator Summary


Bitwise XOR Operator (^)

Performs a bitwise exclusive OR on two expressions.

result = expression1 ^ expression2

Arguments

result
Any variable.
expression1
Any expression.
expression2
Any expression.

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:

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.

Requirements

Version 1

See Also

^= Operator | Operator Precedence | Operator Summary


Comma Operator (,)

Causes two expressions to be executed sequentially.

expression1, expression2

Arguments

expression1
Any expression.
expression2
Any expression.

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:

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.

Requirements

Version 1

See Also

for Statement | Operator Precedence | Operator Summary


Comparison Operators

Returns a Boolean value indicating the result of the comparison.

expression1 comparisonoperator expression2

Arguments

expression1
Any expression.
comparisonoperator
Any comparison operator.
expression2
Any expression.

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.

Requirements

Version 1

See Also

Operator Precedence | Operator Summary


Compound Assignment Operators

The following table lists JScript assignment operators.

Operator | Symbol
Addition | +=
Bitwise AND | &=
Bitwise Or | |=
Bitwise XOR | ^=
Division | /=
Left Shift | <<=
Modulus | %=
Multiplication | *=
Right Shift | >>=
Subtraction | -=
Unsigned Right Shift | >>>=

Requirements

Version Information


Conditional (Ternary) Operator (?:)

Executes one of two statements depending on a condition.

test ? statement1 : statement2

Arguments

test
Any Boolean expression.
statement1
A statement executed if test is true. May be a compound statement.
statement2
A statement executed if test is false. May be a compound statement.

Remarks

The ?: operator is 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:

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:

var now = new Date();
var greeting = "Good";
if (now.getHours() > 17)
   greeting += " evening.";
else
   greeting += " day.";

Requirements

Version 1

See Also

if...else Statement | Operator Precedence | Operator Summary


delete Operator

Deletes a property from an object, or removes an element from an array.

delete expression

The expression argument is a valid JScript expression that usually results in a property name or array element.

Remarks

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.

Requirements

Version 3

See Also

Operator Precedence | Operator Summary


Division Assignment Operator (/=)

Divides the value of a variable by the value of an expression and assigns the result to the variable.

result /= expression

Arguments

result
Any numeric variable.
expression
Any numeric expression.

Remarks

Using the /= operator is exactly the same as specifying:

result = result / expression

Requirements

Version 1

See Also

/ Operator | Operator Precedence | Operator Summary


Division Operator (/)

Divides the value of two expressions.

result = number1 / number2

Arguments

result
Any numeric variable.
number1
Any numeric expression.
number2
Any numeric expression.

Requirements

Version 1

See Also

/= Operator | Operator Precedence | Operator Summary


in Operator

Tests for the existence of a property in an object.

result = property in object

Arguments

result
Required. Any variable.
property
Required. An expression that evaluates to a string expression.
object
Required. Any object.

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.

Requirements

Version 1

See Also

Operator Precedence | Operator Summary


Increment (++) and Decrement (--) Operators

JScript

Increment (++) and Decrement ( — ) Operators

Increments or decrements the value of a variable by one.

Syntax 1

result = ++variable
result = --variable
result = variable++
result = variable--

Syntax 2

++variable
--variable
variable++
variable--

Arguments

result
Any variable.
variable
Any variable.

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:

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:

var j, k;
k = 2;
j = k++;

Here, j is assigned the value 2, as the increment occurs after the expression is evaluated.

Requirements

Version 1

See Also

Operator Precedence | Operator Summary


instanceof Operator

Returns a Boolean value that indicates whether or not an object is an instance of a particular class.

result = object instanceof class

Arguments

result
Required. Any variable.
object
Required. Any object expression.
class
Required. Any defined object class.

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.

Example

The following example illustrates the use of the instanceof operator.

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));

Requirements

Version 5

See Also

Operator Precedence | Operator Summary


Left Shift Assignment 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.

result <<= expression

Arguments

result
Any variable.
expression
Any expression.

Remarks

Using the <<= operator is exactly the same as specifying:

result = result << expression

The <<= operator shifts the bits of result left by the number of bits specified in expression. For example:

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.

Requirements

Version 1

See Also

<< Operator | >> Operator | >>> Operator | Operator Precedence | Operator Summary


Logical AND Operator (&&)

Performs a logical conjunction on two expressions.

result = expression1 && expression2

Arguments

result
Any variable.
expression1
Any expression.
expression2
Any expression.

Remarks

If, and only if, both expressions evaluate to True, result is True. If either expression evaluates to False, result is False.

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.

Requirements

Version 1

See Also

Operator Precedence | Operator Summary


Logical NOT Operator (!)

Performs logical negation on an expression.

result = !expression

Arguments

result
Any variable.
expression
Any expression.

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.

Requirements

Version 1

See Also

~ Operator | Operator Precedence | Operator Summary


Logical OR Operator (||)

Performs a logical disjunction on two expressions.

result = expression1 || expression2

Arguments

result
Any variable.
expression1
Any expression.
expression2
Any expression.

Remarks

If either or both expressions evaluate to True, result is True. The following table illustrates how result is determined:

If expression1 is | 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.

Requirements

Version 1

See Also

Operator Precedence | Operator Summary


Modulus Assignment Operator (%=)

Divides the value of a variable by the value of an expression, and assigns the remainder to the variable.

result %= expression

Arguments

result
Any variable.
expression
Any numeric expression.

Remarks

Using the %= operator is exactly the same as specifying:

result = result % expression

Requirements

Version 1

See Also

% Operator | Operator Precedence | Operator Summary


Modulus Operator (%)

Divides the value of one expression by the value of another, and returns the remainder.

result = number1 % number2

Arguments

result
Any variable.
number1
Any numeric expression.
number2
Any numeric expression.

Remarks

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

A = 19 % 6.7

Requirements

Version 1

See Also

%= Operator | Operator Precedence | Operator Summary


Multiplication Assignment Operator (*=)

Multiplies the value of a variable by the value of an expression and assigns the result to the variable.

result *= expression

Arguments

result
Any variable.
expression
Any expression.

Remarks

Using the *= operator is exactly the same as specifying:

result = result * expression

Requirements

Version 1

See Also

* Operator | Operator Precedence | Operator Summary


Multiplication Operator (*)

Multiplies the value of two expressions.

result = number1*number2

Arguments

result
Any variable.
number1
Any expression.
number2
Any expression.

Requirements

Version 1

See Also

*= Operator | Operator Precedence | Operator Summary


new Operator

Creates a new object.

new constructor[(arguments)]

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.

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.

my_object = new Object;
my_array = new Array();
my_date = new Date("Jan 5 1996");

Requirements

Version 1

See Also

function Statement


Right Shift Assignment 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.

result >>= expression

Arguments

result
Any variable.
expression
Any expression.

Remarks

Using the >>= operator is exactly the same as specifying:

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

var temp
temp = -14
temp >>= 2

Requirements

Version 1

See Also

<< Operator | >> Operator | >>> Operator | Operator Precedence | Operator Summary


Subtraction Assignment Operator (-=)

Subtracts the value of an expression from the value of a variable and assigns the result to the variable.

result -= expression

Arguments

result
Any numeric variable.
expression
Any numeric expression.

Remarks

Using the -= operator is exactly the same as doing the following:

result = result – expression

Requirements

Version 1

See Also

- Operator | Operator Precedence | Operator Summary


Subtraction Operator (-)

Subtracts the value of one expression from another or provides unary negation of a single expression.

Syntax 1

result = number1 - number2

Syntax 2

-number

Arguments

result
Any numeric variable.
number
Any numeric expression.
number1
Any numeric expression.
number2
Any numeric expression.

Remarks

In Syntax 1, the - operator is the arithmetic subtraction operator used to find the difference between two numbers. In Syntax 2, the - operator is used as the unary negation operator to indicate the negative value of an expression.

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.

Requirements

Version 1

See Also

-= Operator | Operator Precedence | Operator Summary


typeof Operator

Returns a string that identifies the data type of an expression.

typeof[(]expression[)] ;

The expression argument is any expression for which type information is sought.

Remarks

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.

Requirements

Version 1

See Also

Operator Precedence | Operator Summary


Unsigned Right Shift Operator (>>>)

Right shifts the bits of an expression, without maintaining sign.

result = expression1 >>> expression2

Arguments

result
Any variable.
expression1
Any expression.
expression2
Any expression.

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:

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

Requirements

Version 1

See Also

>>>= Operator | << Operator | >> Operator | Operator Precedence | Operator Summary


Unsigned Right Shift Assignment 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.

result >>>= expression

Arguments

result
Any variable.
expression
Any expression.

Remarks

Using the >>>= operator is exactly the same as doing the following:

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:

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

Requirements

Version 1

See Also

>>> Operator | << Operator | >> Operator | Operator Precedence | Operator Summary


void Operator

Prevents an expression from returning a value.

void expression

The expression argument is any valid JScript expression.

Remarks

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.

Requirements

Version 2

See Also

Operator Precedence | Operator Summary


JScript Properties

The following table lists JScript properties.

Description | Language Element
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 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 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 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 the number closest to zero that can be represented in JScript. | MIN_VALUE 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 reference to the prototype for a class of objects. | prototype 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


0...n Properties

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]]

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.

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.

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:

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()));

Requirements

Version 5.5

See Also

Applies To: arguments Object | Function object


$1...$9 Properties

Returns the nine most-recently memorized portions found during pattern matching. Read-only.

RegExp.$n

Arguments

RegExp
Always the global RegExp object.

n

Any integer from 1 through 9.

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:

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);
}

Requirements

Version 1

See Also

RegExp Object Properties | Regular Expression Syntax

Applies To: RegExp Object


arguments Property

Returns the arguments object for the currently executing Function object.

function.arguments

The function argument is the name of the currently executing function, and can be omitted.

Remarks

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.

Example

The following example illustrates the use of the arguments property:

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);
}

Requirements

Version 2

See Also

Arguments Object | function Statement

Applies To: Function Object


callee Property

Returns the Function object being executed, that is, the body text of the specified Function object.

[function.]arguments.callee

The optional function argument is the name of the currently executing Function object.

Remarks

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.

Example

function factorial(n){
  if (n <= 0)
  return 1;
  else
    return n * arguments.callee(n - 1)
}
print(factorial(3));

Requirements

Version 5.5

See Also

Applies To: arguments Object | Function object


caller Property

Returns a reference to the function that invoked the current function.

functionName.caller

The functionName object is the name of any executing function.

Remarks

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:

function CallLevel(){
   if (CallLevel.caller == null)
      return("CallLevel was called from the top level.");
   else
      return("CallLevel was called by another function.");
}

Requirements

Version 2

See Also

function Statement

Applies To: Function Object


constructor Property

Specifies the function that creates an object.

object.constructor

The required object is the name of an object or function.

Remarks

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:

x = new String("Hi");
if (x.constructor == String)
   // Do something (the condition will be true).

or

function MyFunc {
   // Body of function.
}

y = new MyFunc;
if (y.constructor == MyFunc)
   // Do something (the condition will be true).

Requirements

Version 2

See Also

prototype Property

Applies To: Array Object | Boolean Object | Date Object | Function Object | Math Object | Number Object | Object Object | String Object


description Property

Returns or sets the descriptive string associated with a specific error.

object.description [= stringExpression]

Arguments

object
Required. Any instance of an Error object.
stringExpression
Optional. A string expression containing a description of the error.

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:

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".
}

Requirements

Version 5

See Also

number Property | message Property | name Property

Applies To: Error Object


E Property

Returns Euler's constant, the base of natural logarithms. The E property is approximately equal to 2.718.

numVar = Math.E

Requirements

Version 1

See Also

exp Method | Math Object Properties

Applies To: Math Object


global Property

Returns a Boolean value indicating the state of the global flag (g) used with a regular expression. Default is false. Read-only.

rgExp.global

The required rgExp reference is an instance of a Regular Expression object.

Remarks

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.

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.

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
}

Requirements

Version 5.5

See Also

ignoreCase Property | multiline Property | Regular Expression Syntax

Applies To: RegExp Object


hasOwnProperty Method

Returns a Boolean value indicating whether an object has a property with the specified name.

object.hasOwnProperty(proName)

Arguments

object
Required. Instance of an object.
proName
Required. String value of a property name.

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.

Example

In the following example, all String objects share a common split method. The following code will print false and true.

var s = new String("JScript");
print(s.hasOwnProperty("split"));
print(String.prototype.hasOwnProperty("split"));

Requirements

Version 5.5

See Also

in Operator

Applies To: Object Object


ignoreCase Property

Returns a Boolean value indicating the state of the ignoreCase flag (i) used with a regular expression. Default is false. Read-only.

rgExp.ignoreCase

The required rgExp reference is an instance of the RegExp object.

Remarks

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.

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.

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
}

Requirements

Version 5.5

See Also

global property | multiline Property | Regular Expression Syntax

Applies To: RegExp Object


index Property

Returns the character position where the first successful match begins in a searched string. Read-only.

RegExp.index

The object associated with this property is always the global RegExp object.

Remarks

The index property is zero-based. The initial value of the index property is –1. Its value changes whenever a successful match is made.

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.

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");
  }
}

Requirements

Version 3

See Also

RegExp Object Properties | Regular Expression Syntax

Applies To: RegExp Object


Infinity Property

Returns an initial value of Number.POSITIVE_INFINITY.

Infinity

Remarks

The Infinity property is a member of the Global object, and is made available when the scripting engine is initialized.

Requirements

Version 3

See Also

POSITIVE_INFINITY Property | NEGATIVE_INFINITY Property

Applies To: Global Object


input Property ($_)

Returns the string against which a regular expression search was performed. Read-only.

RegExp.input

The object associated with this property is always the global RegExp object.

Remarks

The value of input property is modified any time the searched string is changed.

The following example illustrates the use of the input property:

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);
}

Requirements

Version 3

See Also

RegExp Object Properties | Regular Expression Syntax

Applies To: RegExp Object


isPrototypeOf Method

Returns a Boolean value indicating whether an object exists in another object's prototype chain.

object1.isPrototypeOf(object2)

Arguments

object1
Required. Instance of an object.
object2
Required. Another object whose protoype chain is to be checked.

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.

Example

The following example illustrates the use of the isPrototypeof method.

function test(){
  var re = new RegExp();                        //Initialize variable.
  return (RegExp.prototype.isPrototypeOf(re));  //Return true.
}

Requirements

Version 5.5

See Also

Applies To: Object Object


lastIndex Property

Returns the character position where the next match begins in a searched string.

RegExp.lastIndex

The object associated with this property is always the global RegExp object.

Remarks

The lastIndex property is zero-based, that is, the index of the first character is zero. It's 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.

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.

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");
  }
}

Requirements

Version 3

See Also

RegExp Object Properties | Regular Expression Syntax

Applies To: RegExp Object


leftContext Property ($`)

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

The object associated with this property is always the global RegExp object.

Remarks

The initial value of the leftContext property is an empty string. The value of the leftContext property changes whenever a successful match is made.

Example

The following example illustrates the use of the leftContext property:

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());

Requirements

Version 5.5

See Also

$1...$9 Properties | index Property | input Property | lastIndex Property | lastMatch Property | lastParen Property | rightContext Property

Applies To: RegExp Object


length Property (arguments)

Returns the actual number of arguments passed to a function by the caller.

[function.]arguments.length

The optional function argument is the name of the currently executing Function object.

Remarks

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.

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:

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);
}

Requirements

Version 5.5

See Also

arguments Property | length Property (Array) | length Property (String)

Applies To: arguments Object | Function object


length Property (Array)

Returns an integer value one higher than the highest element defined in an array.

numVar = arrayObj.length

Arguments

numVar
Required. Any numeric variable.
arrayObj
Required. Any Array object.

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:

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:

function LengthDemo(){
   var a;
   a = new Array(0,1,2,3,4);
   return(a.length);
}

Requirements

Version 2

See Also

length Property (Function) | length Property (String)

Applies To: Array Object


lastMatch Property ($&)

Returns the last matched characters from any regular expression search. Read-only.

RegExp.lastMatch

The object associated with this property is always the global RegExp object.

Remarks

The initial value of the lastMatch property is an empty string. The value of the lastMatch property changes whenever a successful match is made.

Example

The following example illustrates the use of the lastMatch property:

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());

Requirements

Version 5.5

See Also

$1...$9 Properties | index Property | input Property | lastIndex Property | lastParen Property | leftContext Property | rightContext Property

Applies To: RegExp Object


lastParen Property ($+)

Returns the last parenthesized submatch from any regular expression search, if any. Read-only.

RegExp.lastParen

The object associated with this property is always the global RegExp object.

Remarks

The initial value of the lastParen property is an empty string. The value of the lastParen property changes whenever a successful match is made.

Example

The following example illustrates the use of the lastParen property:

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());

Requirements

Version 5.5

See Also

$1...$9 Properties | index Property | input Property | lastIndex Property | lastMatch Property | leftContext Property | rightContext Property

Applies To: RegExp Object


length Property (Function)

Returns the number of arguments defined for a function.

functionName.length

The required functionName is the name of the function.

Remarks

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.

The following example illustrates the use of the length property:

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);
}

Requirements

Version 2

See Also

arguments Property | length Property (Array) | length Property (String)

Applies To: Function Object


length Property (String)

Returns the length of a String object.

strVariable.length
"String Literal".length

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.

Requirements

Version 1

See Also

length Property (Array) | length Property (Function) | String Object Methods | String Object Properties

Applies To: String Object


LN10 Property

Returns the natural logarithm of 10.

numVar = Math.LN10

Remarks

The LN10 property is approximately equal to 2.302.

Requirements

Version 1

See Also

Math Object Properties

Applies To: Math Object


LN2 Property

Returns the natural logarithm of 2.

numVar = Math.LN2

Syntax

The LN2 property is approximately equal to 0.693.

Requirements

Version 1

See Also

Math Object Properties

Applies To: Math Object


LOG10E Property

Returns the base-10 logarithm of e, Euler's constant.

varName = Math.LOG10E

Remarks

The LOG10E property, a constant, is approximately equal to 0.434.

Requirements

Version 1

See Also

Math Object Properties

Applies To: Math Object


LOG2E Property

Returns the base-2 logarithm of e, Euler's constant.

varName = Math.LOG2E

Remarks

The LOG2E property, a constant, is approximately equal to 1.442.

Requirements

Version 1

See Also

Math Object Properties

Applies To: Math Object


MAX_VALUE Property

Returns the largest number representable in JScript. Equal to approximately 1.79E+308.

Number.MAX_VALUE

The number argument is the Number object.

Remarks

The Number object does not have to be created before the MAX_VALUE property can be accessed.

Requirements

Version 2

See Also

MIN_VALUE Property | NaN Property | NEGATIVE_INFINITY Property | POSITIVE_INFINITY Property | toString Method

Applies To: Number Object


message Property

Returns an error message string.

errorObj.message

Arguments

errorObj
Required. Instance of Error object.

Remarks

The message property is a string containing an error message displayed to users. It contains the same information as the description property.

Example

The following example causes a TypeError exception to be thrown, and displays the name of the error and its message.

try {
  // 'null' is not a valid object
  null.doSomething();
}
catch(e){
  print(e.name + ": " + e.message);
  print(e.number + ": " + e.description);
}

Requirements

Version 5

See Also

description Property | name Property

Applies To: Error Object


MIN_VALUE Property

Returns the number closest to zero representable in JScript. Equal to approximately 5.00E-324.

Number.MIN_VALUE

The number argument is the Number object.

Remarks

The Number object does not have to be created before the MIN_VALUE property can be accessed.

Requirements

Version 2

See Also

MAX_VALUE Property | NaN Property | NEGATIVE_INFINITY Property | POSITIVE_INFINITY Property | toString Method

Applies To: Number Object


multiline Property

Returns a Boolean value indicating the state of the multiline flag (m) used with a regular expression. Default is false. Read-only.

rgExp.multiline

The required rgExp argument is an instance of the RegExp object

Remarks

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 multline 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".

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.

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
}

Requirements

Version 5.5

See Also

global property | ignoreCase Property | Regular Expression Syntax

Applies To: RegExp Object


name Property

Returns the name of an error.

errorObj.name

Arguments

errorObj
Required. Instance of Error object.

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.

Example

The following example causes a TypeError exception to be thrown, and displays the name of the error and its message.

try {
  // 'null' is not a valid object
  null.doSomething();
}
catch(e){
  print(e.name + ": " + e.message);
  print(e.number + ": " + e.description);
}

Requirements

Version 5.5

See Also

description Property | message Property | number Property

Applies To: Error Object


NaN Property

A special value that indicates an arithmetic expression returned a value that was not a number.

Number.NaN

The number argument is the Number object.

Remarks

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.

Requirements

Version 2

See Also

isNaN Method | MAX_VALUE Property | MIN_VALUE Property | NEGATIVE_INFINITY Property | POSITIVE_INFINITY Property | toString Method

Applies To: Number Object


NaN Property (Global)

Returns the special value NaN indicating that an expression is not a number.

NaN

Remarks

The NaN property (not a number) is a member of the Global object, and is made available when the scripting engine is initialized.

Requirements

Version 3

See Also

isNaN Method

Applies To: Global Object


NEGATIVE_INFINITY Property

Returns a value more negative than the largest negative number (-Number.MAX_VALUE) representable in JScript.

Number.NEGATIVE_INFINITY

The number argument is the Number object.

Remarks

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.

Requirements

Version 2

See Also

MAX_VALUE Property | MIN_VALUE Property | NaN Property | POSITIVE_INFINITY Property | toString Method

Applies To: Number Object


number Property

Returns or sets the numeric value associated with a specific error. The Error object's default property is number.

object.number [= errorNumber]

Arguments

object
Any instance of the Error object.
errorNumber
An integer representing an error.

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:

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".
}

Requirements

Version 5

See Also

description Property | message Property | name Property

Applies To: Error Object


PI Property

Returns the ratio of the circumference of a circle to its diameter, approximately 3.141592653589793.

numVar = Math.PI

Syntax

The PI property, a constant, is approximately equal to 3.14159.

Requirements

Version 1

See Also

Math Object Properties

Applies To: Math Object


POSITIVE_INFINITY Property

Returns a value larger than the largest number (Number.MAX_VALUE) that can be represented in JScript.

Number.POSITIVE_INFINITY

The number argument is the Number object.

Remarks

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.

Requirements

Version 2

See Also

MAX_VALUE Property | MIN_VALUE Property | NaN Property | NEGATIVE_INFINITY Property | toString Method

Applies To: Number Object


propertyIsEnumerable Property

Returns a Boolean value indicating whether a specified property is part of an object and if it is enumerable.

object.propertyIsEnumerable(proName)

Arguments

object
Required. Instance of an object.
proName
Required. String value of a property name.

Remarks

The propertyIsEnumerable property returns true if proName exists in object and can be enumerated using a For…In 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.

Example

function testIsEnumerable(){
  var a = new Array("apple", "banana", "cactus");
  return(a.propertyIsEnumerable(1));
}

Requirements

Version 5.5

See Also

Applies To: Object Object


prototype Property

Returns a reference to the prototype for a class of objects.

objectName.prototype

The objectName argument is the name of an object.

Remarks

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.

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.

Requirements

Version 2

See Also

constructor Property

Applies To: Array Object | Boolean Object | Date Object | Function Object | Number Object | Object Object | String Object


rightContext Property ($')

Returns the characters from the position following the last match to the end of the searched string. Read-only.

RegExp.rightContext

The object associated with this property is always the global RegExp object.

Remarks

The initial value of the rightContext property is an empty string. The value of the rightContext property changes whenever a successful match is made.

Example

The following example illustrates the use of the rightContext property:

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());

Requirements

Version 5.5

See Also

$1...$9 Properties | index Property | input Property | lastIndex Property | lastMatch Property | lastParen Property | leftContext Property

Applies To: RegExp Object


source Property

Returns a copy of the text of the regular expression pattern. Read-only.

rgExp.source

The rgExp argument is a Regular expression object. It can be a variable name or a literal.

The following example illustrates the use of the source property:

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);
}

Requirements

Version 3

See Also

Regular Expression Object Methods | Regular Expression Object Properties | Regular Expression Syntax

Applies To: Regular Expression Object


SQRT1_2 Property

Returns he square root of 0.5, or one divided by the square root of 2.

numVar = Math.SQRT1_2

Remarks

The SQRT1_2 property, a constant, is approximately equal to 0.707.

Requirements

Version 1

See Also

Math Object Properties | sqrt Method | SQRT2 Property

Applies To: Math Object


SQRT2 Property

Returns the square root of 2.

numVar = Math.SQRT2

Syntax

The SQRT2 property, a constant, is approximately equal to 1.414.

Requirements

Version 1

See Also

Math Object Properties | sqrt Method | SQRT1_2 Property

Applies To: Math Object


undefined Property

Returns an initial value of undefined.

undefined

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.

Example

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.");

Requirements

Version 5.5

See Also

Applies To: Global Object


JScript Statements

The following table lists JScript 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
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


@cc_on Statement

Activates conditional compilation support.

@cc_on

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:

/*@cc_on*/
...
(remainder of script)

Alternatively, an @if or @set statement outside of a comment also activates conditional compilation.

Requirements

Version 3

See Also

Conditional Compilation | Conditional Compilation Variables | @if Statement | @set Statement


@if Statement

Conditionally executes a group of statements, depending on the value of an expression.

@if (
   condition1
)
   text1
[@elif (
   condition2
)
   text2]
[@else
   text3]
@end

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.

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:

alert(@if (@_win32) "using Windows NT or Windows 95" @else "using Windows 3.1" @end)

Requirements

Version 3

See Also

Conditional Compilation | Conditional Compilation Variables | @cc_on Statement | @set Statement


@set Statement

Creates variables used with conditional compilation statements.

@set @varname = term

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.

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:

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

@if (@newVar != @newVar)
   ...

This works because NaN is the only value not equal to itself.

Requirements

Version 3

See Also

Conditional Compilation | Conditional Compilation Variables | @cc_on Statement | @if Statement


break Statement

Terminates the current loop, or if in conjunction with a label, terminates the associated statement.

break [label];

The optional label argument specifies the label of the statement you are breaking from.

Remarks

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.

Example

The following example illustrates the use of the break statement.

function BreakTest(breakpoint){
   var i = 0;
   while (i < 100)
   {
   if (i == breakpoint)
      break;
      i++;
   }
   return(i);
}

Requirements

Version 1

See Also

continue Statement | do...while Statement | for Statement | for...in Statement | Labeled Statement | while Statement


Comment Statements

Causes comments to be ignored by the JScript parser.

Syntax 1

Single-line Comment:
// comment

Syntax 2

Multiline Comment:
/*
comment
*/

The comment argument is the text of any comment you want to include in your script.

Syntax 3

//@CondStatement

Syntax 4

/*@
condStatement
@*/

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.

Remarks

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.

Example

The following example illustrates the most common uses of the comment statement.

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);
}

Requirements

Version 1


continue Statement

Stops the current iteration of a loop, and starts a new iteration.

continue [label];

The optional label argument specifies the statement to which continue applies.

Remarks

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.

Example

The following example illustrates the use of the continue statement.

function skip5(){
   var s = "", i=0;
   while (i < 10)
   {
      i++;
      // Skip 5
      if (i==5)
      {
       continue;
      }
   s += i;
   }
   return(s);
}

Requirements

Version 1

See Also

break Statement | do...while Statement | for Statement | for...in Statement | Labeled Statement | while Statement


do...while Statement

Executes a statement block once, and then repeats execution of the loop until a condition expression evaluates to false.

do
   statement
while (expression) ;

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.

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.

Example

The following example illustrates the use of the do...while statement to iterate the Drives collection.

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);
}

Requirements

Version 3

See Also

break Statement | continue Statement | for Statement | for...in Statement | while Statement | Labeled Statement


for Statement

Executes a block of statements for as long as a specified condition is true.

for (initialization; test; increment)
   statements

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.

Remarks

You usually use a for loop when the loop is to be executed a specific number of times.

Example

The following example demonstrates a for loop.

/* 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;
}

Requirements

Version 1

See Also

for...in Statement | while Statement


for...in Statement

Executes one or more statements for each property of an object, or each element of an array.

for (variable in [object | array])
   statements

Arguments

variable
Required. A variable that can be any property of object or any element 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.

Remarks

Before each iteration of a loop, variable is assigned the next property of object or the next element of array. You can then use it in any of the statements inside the loop, exactly as if you were using 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, ...

Example

The following example illustrates the use of the for ... in statement with an object used as an associative array.

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 Use the enumerator object to iterate members of a collection.

Requirements

Version 5

See Also

for Statement | while Statement


function Statement

Declares a new function.

function functionname([arg1 [, arg2 [,...[, argN]]]])
{
   statements
}

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.

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.

Example

The following example illustrates the use of the function statement.

function myfunction(arg1, arg2){
   var r;
   r = arg1 * arg2;
   return(r);
}
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.

Requirements

Version 1

See Also

new Operator


if...else Statement

Conditionally executes a group of statements, depending on the value of an expression.

if (condition)
   statement1
[else
   statement2]

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.

Remarks

It is generally good practice to enclose statement1 and statement2 in braces ({}) for clarity and to avoid inadvertent errors.

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.

if (x == 5)
   if (y == 6)
      z = 17;
else
   z = 20;

Changing the code in the following manner eliminates any ambiguities:

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:

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.

Requirements

Version 1

See Also

Conditional Operator (?:)


Labeled Statement

Provides an identifier for a statement.

label :
   statements

Arguments

label
Required. A unique identifier used when referring to the labeled statement.
statements
Optional. One or more statements associated with label.

Remarks

Labels are used by the break and continue statements to specify the statement to which the break and continue apply.

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:

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)
}

Requirements

Version 3

See Also

break Statement | continue Statement


return Statement

Exits from the current function and returns a value from that function.

return[(][expression][)];

The optional expression argument is the value to be returned from the function. If omitted, the function does not return a value.

Remarks

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.

Example

The following example illustrates the use of the return statement.

function myfunction(arg1, arg2){
   var r;
   r = arg1 * arg2;
   return(r);
}

Requirements

Version 1

See Also

function Statement


switch Statement

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
}

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.

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.

Example

The following example tests an object for its type.

function MyObject() {
...}

switch (object.constructor){
   case Date:
   ...
   case Number:
   ...
   case String:
   ...
   case MyObject:
   ...
   default:
   ...
}

Requirements

Version 3

See Also

break Statement | if...else Statement


this Statement

Refers to the current object.

this.property

The required property argument is one of the current object's properties

Remarks

The this keyword is typically used in object constructors to refer to the current object.

Example

In the following example, this refers to the newly created Car object, and assigns values to three properties:

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.

Requirements

Version 1

See Also

new Operator


throw Statement

Generates an error condition that can be handled by a try...catch…finally statement.

throw exception

The required exception argument can be any expression.

Remarks

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:

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));

Requirements

Version 5

See Also

try...catch Statement


try...catch...finally Statement

JScript

try...catch…finally Statement

Implements error handling for JScript.

try {
   tryStatements}
catch(exception){
   catchStatements}
finally {
   finallyStatements}

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.

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

Example

The following example shows how JScript exception handling works.

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:

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

Requirements

Version 5

See Also

throw Statement


var Statement

Declares a variable.

var variable1 [ = value1 ] [, variable2 [ = value2], ...]

Arguments

variable1, variable2
The names of the variables being declared.
value1, value2
The initial value assigned to the variable.

Remarks

Use the var statement to declare variables. These variables can be assigned values at declaration or later in your script.

Example

The following example illustrates the use of the var statement.

var index;
var name = "Thomas Jefferson";
var answer = 42, counter, numpages = 10;

Requirements

Version 1

See Also

function Statement | new Operator


while Statement

Executes a statement until a specified condition is false.

while (expression)
   statements

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.

Remarks

The while statement checks expression before a loop is first executed. If expression is false at this time, the loop is never executed.

Example

The following example illustrates the use of the while statement.

function BreakTest(breakpoint){
   var i = 0;
   while (i < 100)
   {
   if (i == breakpoint)
      break;
      i++;
   }
   return(i);
}

Requirements

Version 1

See Also

break Statement | continue Statement | do...while Statement | for Statement | for...in Statement


with Statement

Establishes the default object for a statement.

with (object)
   statements

Arguments

object
The new default object.
statements
One or more statements for which object is the default object.

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.

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:

with (Math){
   x = cos(3 * PI) + sin (LN10)
   y = tan(14 * E)
}

Requirements

Version 1

See Also

this Statement


VBScript

VBScipt User's Guide

VBScript Langauge Reference


VBScript User's Guide

What Is VBScript?

Adding VBScript Code to an HTML Page

VBScript Fundamentals

VBScript Data Types

VBScript Variables

VBScript Constants

VBScript Operators

Using Conditional Statements

Looping Through Code

VBScript Procedures

VBScript Coding Conventions


What Is VBScript?

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

Easy to Use and Learn

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

Windows Script

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

VBScript in Other Applications and Browsers

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


Adding VBScript Code to an HTML Page

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

The <SCRIPT> Tag

VBScript code is written within paired <SCRIPT> tags. For example, a procedure to test a delivery date might appear as follows:

<SCRIPT LANGUAGE="VBScript">
<!--
   Function CanDeliver(Dt)
      CanDeliver = (CDate(Dt) - Now()) > 2
   End Function
-->
</SCRIPT>

Beginning and ending <SCRIPT> tags surround the code. The LANGUAGE attribute indicates the scripting language. You must specify the language because browsers can use other scripting languages. Notice that the CanDeliver function is embedded in comment tags (<!— and —>). This prevents browsers that don't understand the <SCRIPT> tag from displaying the code.

Since the example is a general function — it is not tied to any particular form control — you can include it in the HEAD section of the page:

<HTML>
<HEAD>
<TITLE>Place Your Order</TITLE>
<SCRIPT LANGUAGE="VBScript">
<!--
   Function CanDeliver(Dt)
      CanDeliver = (CDate(Dt) - Now()) > 2
   End Function
-->
</SCRIPT>
</HEAD>
<BODY>
...

You can use SCRIPT blocks anywhere in an HTML page. You can put them in both the BODY and HEAD sections. However, you will probably want to put all general-purpose scripting code in the HEAD section in order to keep all the code together. Keeping your code in the HEAD section ensures that all code is read and decoded before it is called from within the BODY section.

One notable exception to this rule is that you may want to provide inline scripting code within forms to respond to the events of objects in your form. For example, you can embed scripting code to respond to a button click in a form:

<HTML>
<HEAD>
<TITLE>Test Button Events</TITLE>
</HEAD>
<BODY>
<FORM NAME="Form1">
   <INPUT TYPE="Button" NAME="Button1" VALUE="Click">
   <SCRIPT FOR="Button1" EVENT="onClick" LANGUAGE="VBScript">
      MsgBox "Button Pressed!"
   </SCRIPT>
</FORM>
</BODY>
</HTML>

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


VBScript Features not in Visual Basic for Applications

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

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

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

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 !


VBScript Fundamentals

VBScript Data Types

VBScript Variables

VBScript Constants

VBScript Operators

Using Conditional Statements

Looping Through Code

VBScript Procedures

VBScript Coding Conventions


A Simple VBScript Page

A Simple Page

With Microsoft® Internet Explorer, you can view the page produced by the following HTML code. If you click the button on the page, you see VBScript in action.

<HTML>
<HEAD><TITLE>A Simple First Page</TITLE>
<SCRIPT LANGUAGE="VBScript">
<!--
Sub Button1_OnClick
   MsgBox "Mirabile visu."
End Sub
-->
</SCRIPT>
</HEAD>
<BODY>
<H3>A Simple First Page</H3><HR>
<FORM><INPUT NAME="Button1" TYPE="BUTTON" VALUE="Click Here"></FORM>
</BODY>
</HTML>

The result is a little underwhelming: a dialog box displays a Latin phrase ("Wonderful to behold"). However, there's quite a bit going on.

When Internet Explorer reads the page, it finds the <SCRIPT> tags, recognizes there is a piece of VBScript code, and saves the code. When you click the button, Internet Explorer makes the connection between the button and the code, and runs the procedure.

The Sub procedure in the <SCRIPT> tags is an event procedure. There are two parts to the procedure name: the name of the button, Button1 (from the NAME attribute in the <INPUT> tag), and an event name, OnClick. The two names are joined by an underscore(_). Any time the button is clicked, Internet Explorer looks for and runs the corresponding event procedure, Button1_OnClick.

Internet Explorer defines the events available for form controls in the Internet Explorer Scripting Object Model documentation, which can be found on the Microsoft® Web site (http://www.microsoft.com).

Pages can use combinations of controls and procedures, too. VBScript and Forms shows some simple interactions between controls.

Other Ways to Attach Code to Events

Although the preceding way is probably the simplest and most general, you can attach VBScript code to events in two other ways. Internet Explorer allows you to add short sections of inline code in the tag defining the control. For example, the following <INPUT> tag performs the same action as the previous code example when you click the button:

<INPUT NAME="Button1" TYPE="BUTTON"
   VALUE="Click Here" OnClick='MsgBox "Mirabile visu."'>

Notice that the function call itself is enclosed in single quotation marks, and the string for the MsgBox function is enclosed in double quotation marks. You can use multiple statements as long as you separate the statements with colons (:).

You can also write a <SCRIPT> tag so that it applies only to a particular event for a specific control:

<SCRIPT LANGUAGE="VBScript" EVENT="OnClick" FOR="Button1">
<!--
   MsgBox "Mirabile visu."
-->
</SCRIPT>

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


VBScript Features

The following table is a list of VBScript features.

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 | IsArray IsDate IsEmpty IsNull IsNumeric IsObject TypeName VarType


VBScript Data Types

VBScript has only one data type called a Variant. A Variant is a special kind of data type that can contain different kinds of information, depending on how it is used. Because Variant is the only data type in VBScript, it is also the data type returned by all functions in VBScript.

At its simplest, a Variant can contain either numeric or string information. A Variant behaves as a number when you use it in a numeric context and as a string when you use it in a string context. That is, if you are working with data that looks like numbers, VBScript assumes that it is numbers and does what is most appropriate for numbers. Similarly, if you're working with data that can only be string data, VBScript treats it as string data. You can always make numbers behave as strings by enclosing them in quotation marks (" ").

Variant Subtypes

Beyond the simple numeric or string classifications, a Variant can make further distinctions about the specific nature of numeric information. For example, you can have numeric information that represents a date or a time. When used with other date or time data, the result is always expressed as a date or a time. You can also have a rich variety of numeric information ranging in size from Boolean values to huge floating-point numbers. These different categories of information that can be contained in a Variant are called subtypes. Most of the time, you can just put the kind of data you want in a Variant, and the Variant behaves in a way that is most appropriate for the data it contains.

The following table shows subtypes of data that a Variant can contain.

Subtype | 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

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

Declaring Variables

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

Dim DegreesFahrenheit

You declare multiple variables by separating each variable name with a comma. For example:

Dim Top, Bottom, Left, Right

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

Naming Restrictions

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

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

Scope and Lifetime of Variables

A variable's scope is determined by where you declare it. When you declare a variable within a procedure, only code within that procedure can access or change the value of that variable. It has local scope and is a 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:

B = 200

Scalar Variables and Array Variables

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

Dim A(10)

Although the number shown in the parentheses is 10, all arrays in VBScript are zero-based, so this array actually contains 11 elements. In a zero-based array, the number of array elements is always the number shown in parentheses plus one. This kind of array is called a fixed-size array.

You assign data to each of the elements of the array using an index into the array. Beginning at zero and ending at 10, data can be assigned to the elements of an array as follows:

A(0) = 256
A(1) = 324
A(2) = 100
 . . .
A(10) = 55

Similarly, the data can be retrieved from any element using an index into the particular array element you want. For example:

 . . .
SomeVariable = A(8)
 . . .

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

Dim MyTable(5, 10)

In a two-dimensional array, the first number is always the number of rows; the second number is the number of columns.

You can also declare an array whose size changes during the time your script is running. This is called a dynamic array. The array is initially declared within a procedure using either the Dim statement or using the ReDim statement. However, for a dynamic array, no size or number of dimensions is placed inside the parentheses. For example:

Dim MyArray()
ReDim AnotherArray()

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

ReDim MyArray(25)
 . . .
ReDim Preserve MyArray(30)

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


VBScript Constants

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

Creating Constants

You create user-defined constants in VBScript using the Const statement. Using the Const statement, you can create string or numeric constants with meaningful names and assign them literal values. For example:

Const MyString = "This is my string."
Const MyAge = 49

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

Const CutoffDate = #6-1-97#

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


VBScript Operators

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

Operator Precedence

When several operations occur in an expression, each part is evaluated and resolved in a predetermined order called operator precedence. You can use parentheses to override the order of precedence and force some parts of an expression to be evaluated before others. Operations within parentheses are always performed before those outside. Within parentheses, however, standard operator precedence is maintained.

When expressions contain operators from more than one category, arithmetic operators are evaluated first, comparison operators are evaluated next, and logical operators are evaluated last. Comparison operators all have equal precedence; that is, they are evaluated in the left-to-right order in which they appear. Arithmetic and logical operators are evaluated in the following order of precedence.

Arithmetic

Description | Symbol
Exponentiation | ^
Unary negation | -
Multiplication | *
Division | /
Integer division | \
Modulus arithmetic | Mod
Addition | +
Subtraction | -
String concatenation | &

Comparison

Description | 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

Controlling Program Execution

You can control the flow of your script with conditional statements and looping statements. Using conditional statements, you can write VBScript code that makes decisions and repeats actions. The following conditional statements are available in VBScript:

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

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

The If...Then...Else statement is used to evaluate whether a condition is True or False and, depending on the result, to specify one or more statements to run. Usually the condition is an expression that uses a comparison operator to compare one value or variable with another. For information about comparison operators, see Comparison Operators. If...Then...Else statements can be nested to as many levels as you need.

Running Statements if a Condition is True

To run only one statement when a condition is True, use the single-line syntax for the If...Then...Else statement. The following example shows the single-line syntax. Notice that this example omits the Else keyword.

Sub FixDate()
    Dim myDate
    myDate = #2/13/95#
    If myDate < Now Then myDate = Now
End Sub

To run more than one line of code, you must use the multiple-line (or block) syntax. This syntax includes the End If statement, as shown in the following example:

Sub AlertUser(value)
   If value = 0 Then
      AlertLabel.ForeColor = vbRed
      AlertLabel.Font.Bold = True
      AlertLabel.Font.Italic = True
   End If
End Sub

Running Certain Statements if a Condition is True and Running Others if a Condition is False

You can use an If...Then...Else statement to define two blocks of executable statements: one block to run if the condition is True, the other block to run if the condition is False.

Sub AlertUser(value)
   If value = 0 Then
      AlertLabel.ForeColor = 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:

Sub ReportValue(value)
   If value = 0 Then
      MsgBox value
   ElseIf value = 1 Then
      MsgBox value
   ElseIf value = 2 then
      Msgbox value
   Else
      Msgbox "Value out of range!"
   End If

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

Making Decisions with Select Case

The Select Case structure provides an alternative to If...Then...ElseIf for selectively executing one block of statements from among multiple blocks of statements. A Select Case statement provides capability similar to the If...Then...Else statement, but it makes code more efficient and readable.

A Select Case structure works with a single test expression that is evaluated once, at the top of the structure. The result of the expression is then compared with the values for each Case in the structure. If there is a match, the block of statements associated with that Case is executed, as in the following example.

Select Case Document.Form1.CardType.Options(SelectedIndex).Text
   Case "MasterCard"
      DisplayMCLogo
      ValidateMCAccount
   Case "Visa"
      DisplayVisaLogo
      ValidateVisaAccount
   Case "American Express"
      DisplayAMEXCOLogo
      ValidateAMEXCOAccount
   Case Else
      DisplayUnknownImage
      PromptAgain
End Select

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


Looping Through Code

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

The following looping statements are available in VBScript:

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

Using Do Loops

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

Repeating Statements While a Condition is True

Use the While keyword to check a condition in a Do...Loop statement. You can check the condition before you enter the loop (as shown in the following ChkFirstWhile example), or you can check it after the loop has run at least once (as shown in the ChkLastWhile example). In the ChkFirstWhile procedure, if myNum is set to 9 instead of 20, the statements inside the loop will never run. In the ChkLastWhile procedure, the statements inside the loop run only once because the condition is already False.

Sub ChkFirstWhile()
   Dim counter, myNum
   counter = 0
   myNum = 20
   Do While myNum > 10
      myNum = myNum - 1
      counter = counter + 1
   Loop
   MsgBox "The loop made " & counter & " repetitions."
End Sub

Sub ChkLastWhile()
   Dim counter, myNum
   counter = 0
   myNum = 9
   Do
      myNum = myNum - 1
      counter = counter + 1
   Loop While myNum > 10
   MsgBox "The loop made " & counter & " repetitions."
End Sub

Repeating a Statement Until a Condition Becomes True

There are two ways to use the Until keyword to check a condition in a Do...Loop statement. You can check the condition before you enter the loop (as shown in the following ChkFirstUntil example), or you can check it after the loop has run at least once (as shown in the ChkLastUntil example). As long as the condition is False, the looping occurs.

Sub ChkFirstUntil()
   Dim counter, myNum
   counter = 0
   myNum = 20
   Do Until myNum = 10
      myNum = myNum - 1
      counter = counter + 1
   Loop
   MsgBox "The loop made " & counter & " repetitions."
End Sub

Sub ChkLastUntil()
   Dim counter, myNum
   counter = 0
   myNum = 1
   Do
      myNum = myNum + 1
      counter = counter + 1
   Loop Until myNum = 10
   MsgBox "The loop made " & counter & " repetitions."
End Sub

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

You can exit a Do...Loop by using the Exit Do statement. Because you usually want to exit only in certain situations, such as to avoid an endless loop, you should use the Exit Do statement in the True statement block of an If...Then...Else statement. If the condition is False, the loop runs as usual.

In the following example, myNum is assigned a value that creates an endless loop. The If...Then...Else statement checks for this condition, preventing the endless repetition.

Sub ExitExample()
   Dim counter, myNum
      counter = 0
      myNum = 9
      Do Until myNum = 10
         myNum = myNum - 1
         counter = counter + 1
         If myNum < 10 Then Exit Do
      Loop
      MsgBox "The loop made " & counter & " repetitions."
End Sub

Using While...Wend

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

Using For...Next

You can use For...Next statements to run a block of statements a specific number of times. For loops, use a counter variable whose value increases or decreases with each repetition of the loop.

The following example causes a procedure called MyProc to execute 50 times. The For statement specifies the counter variable x and its start and end values. The Next statement increments the counter variable by 1.

Sub DoMyProc50Times()
   Dim x
   For x = 1 To 50
      MyProc
   Next
End Sub

Using the Step keyword, you can increase or decrease the counter variable by the value you specify. In the following example, the counter variable j is incremented by 2 each time the loop repeats. When the loop is finished, the total is the sum of 2, 4, 6, 8, and 10.

Sub TwosTotal()
   Dim j, total
   For j = 2 To 10 Step 2
      total = total + j
   Next
   MsgBox "The total is " & total
End Sub

To decrease the counter variable, use a negative Step value. You must specify an end value that is less than the start value. In the following example, the counter variable myNum is decreased by 2 each time the loop repeats. When the loop is finished, total is the sum of 16, 14, 12, 10, 8, 6, 4, and 2.

Sub NewTotal()
   Dim myNum, total
   For myNum = 16 To 2 Step -2
      total = total + myNum
   Next
   MsgBox "The total is " & total
End Sub

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

Using For Each...Next

A For Each...Next loop is similar to a For...Next loop. Instead of repeating the statements a specified number of times, a For Each...Next loop repeats a group of statements for each item in a collection of objects or for each element of an array. This is especially helpful if you don't know how many elements are in a collection.

In the following HTML code example, the contents of a Dictionary object is used to place text in several text boxes.

<HTML>
<HEAD><TITLE>Forms and Elements</TITLE></HEAD>
<SCRIPT LANGUAGE="VBScript">
<!--
Sub cmdChange_OnClick
   Dim d   'Create a variable
   Set d = CreateObject("Scripting.Dictionary")
   d.Add "0", "Athens"   'Add some keys and items
   d.Add "1", "Belgrade"
   d.Add "2", "Cairo"

   For Each I in d
      Document.frmForm.Elements(I).Value = D.Item(I)
   Next
End Sub
-->
</SCRIPT>
<BODY>
<CENTER>
<FORM NAME="frmForm"

<Input Type = "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

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

Sub Procedures

A Sub procedure is a series of VBScript statements (enclosed by Sub and End Sub statements) that perform actions but don't return a value. A Sub procedure can take arguments (constants, variables, or expressions that are passed by a calling procedure). If a Sub procedure has no arguments, its Sub statement must include an empty set of parentheses ().

The following Sub procedure uses two intrinsic, or built-in, VBScript functions, MsgBox and InputBox, to prompt a user for information. It then displays the results of a calculation based on that information. The calculation is performed in a Function procedure created using VBScript. The Function procedure is shown after the following discussion.

Sub ConvertTemp()
   temp = InputBox("Please enter the temperature in degrees F.", 1)
   MsgBox "The temperature is " & Celsius(temp) & " degrees C."
End Sub

Function Procedures

A Function procedure is a series of VBScript statements enclosed by the Function and End Function statements. A Function procedure is similar to a Sub procedure, but can also return a value. A Function procedure can take arguments (constants, variables, or expressions that are passed to it by a calling procedure). If a Function procedure has no arguments, its Function statement must include an empty set of parentheses. A Function returns a value by assigning a value to its name in one or more statements of the procedure. The return type of a Function is always a Variant.

In the following example, the Celsius function calculates degrees Celsius from degrees Fahrenheit. When the function is called from the ConvertTemp Sub procedure, a variable containing the argument value is passed to the function. The result of the calculation is returned to the calling procedure and displayed in a message box.

Sub ConvertTemp()
   temp = InputBox("Please enter the temperature in degrees F.", 1)
   MsgBox "The temperature is " & Celsius(temp) & " degrees C."
End Sub

Function Celsius(fDegrees)
   Celsius = (fDegrees - 32) * 5 / 9
End Function

Getting Data into and out of Procedures

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

Function Celsius(fDegrees)
   Celsius = (fDegrees - 32) * 5 / 9
End Function

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

Using Sub and Function Procedures in Code

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

Temp = Celsius(fDegrees)

-or-

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.

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

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

  • Naming conventions for objects, variables, and procedures
  • Commenting conventions
  • Text formatting and indenting guidelines

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

Constant Naming Conventions

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

USER_LIST_MAX
NEW_LINE

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

conYourOwnConstant

Variable Naming Conventions

To enhance readability and consistency, use the following prefixes with descriptive names for variables in your VBScript code.

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

'*********************************************************
' 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 and Forms

Simple Validation

You can use Visual Basic Scripting Edition to do much of the form processing that you'd usually have to do on a server. You can also do things that just can't be done on the server.

Here's an example of simple client-side validation. The HTML code is for a text box and a button. If you use Microsoft® Internet Explorer to view the page produced by the following code, you'll see a small text box with a button next to it.

<HTML>
<HEAD><TITLE>Simple Validation</TITLE>
<SCRIPT LANGUAGE="VBScript">
<!--
Sub Validate
  Dim TheForm
  Set TheForm = Document.forms("ValidForm")
  If IsNumeric(TheForm.Text1.Value) Then
    If TheForm.Text1.Value < 1 Or TheForm.Text1.Value > 10 Then
      MsgBox "Please enter a number between 1 and 10."
    Else
      MsgBox "Thank you."
    End If
  Else
    MsgBox "Please enter a numeric value."
  End If
End Sub-->
</SCRIPT>
</HEAD>
<BODY>
<H3>Simple Validation</H3><HR>
<form id="ValidForm" action="nothing.asp" onsubmit="Validate(); return false;" language="jscript">
Enter a value between 1 and 10:
<input name="Text1" TYPE="TEXT" SIZE="2">
<input name="Submit" TYPE="Submit" VALUE="Submit">
</form>
</BODY>
</HTML>

The difference between this text box and the examples on A Simple VBScript Page is that the Value property of the text box is used to check the entered value. To get the Value property, the code has to qualify the reference to the name of the text box.

You can always write out the full reference Document.ValidForm.Text1. However, where you have multiple references to form controls, you'll want to do what was done here. First declare a variable. Then use the Set statement to assign the form to the variable TheForm. A regular assignment statement, such as Dim, doesn't work here; you must use Set to preserve the reference to an object.

Using Numeric Values

Notice that the example directly tests the value against a number: it uses the IsNumeric function to make sure the string in the text box is a number. Although VBScript automatically converts strings and numbers, it's always a good practice to test a user-entered value for its data subtype and to use conversion functions as necessary. When doing addition with text box values, convert the values explicitly to numbers because the plus sign (+) operator represents both addition and string concatenation. For example, if Text1 contains "1" and Text2 contains "2", you see the following results:

A = Text1.Value + Text2.Value   ' A is "12"
A = CDbl(Text1.Value) + Text2.Value   ' A is 3

Validating and Passing Data Back to the Server

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

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

To send the data to the server, the code invokes the Submit method on the form object when the data is correct. From there, the server handles the data just as it otherwise would — except that the data is correct before it gets there. Find complete information about the Submit method and other methods in the Internet Explorer Scripting Object Model documentation, which can be found on the Microsoft® Web site (http://www.microsoft.com).

So far, you've seen only the standard HTML <FORM> objects. Internet Explorer also lets you exploit the full power of ActiveX® controls (formerly called OLE controls) and Java objects.


VBScript in Internet Explorer

A Simple VBScript Page

VBScript and Forms

Using VBScript with Objects


Using VBScript with Objects

Using Objects

Whether you use an ActiveX® control (formerly called an OLE control) or a Java object, Microsoft Visual Basic Scripting Edition and Microsoft® Internet Explorer handle it the same way. If you're using Internet Explorer and have installed the Label control, you can see the page produced by the following code.

You include an object using the <OBJECT> tags and set its initial property values using <PARAM> tags. If you're a Visual Basic programmer, you'll recognize that using the <PARAM> tags is just like setting initial properties for a control on a form. For example, the following set of <OBJECT> and <PARAM> tags adds the ActiveX Label control to a page:

<OBJECT
   classid="clsid:99B42120-6EC7-11CF-A6C7-00AA00A47DD2"
   id=lblActiveLbl
   width=250
   height=250
   align=left
   hspace=20
   vspace=0
>
<PARAM NAME="Angle" VALUE="90">
<PARAM NAME="Alignment" VALUE="4">
<PARAM NAME="BackStyle" VALUE="0">
<PARAM NAME="Caption" VALUE="A Simple Desultory Label">
<PARAM NAME="FontName" VALUE="Verdana, Arial, Helvetica">
<PARAM NAME="FontSize" VALUE="20">
<PARAM NAME="FontBold" VALUE="1">
<PARAM NAME="FrColor" VALUE="0">
</OBJECT>

You can get properties, set properties, and invoke methods just as with any of the form controls. The following code, for example, includes <FORM> controls you can use to manipulate two properties of the Label control:

<FORM NAME="LabelControls">
<INPUT TYPE="TEXT" NAME="txtNewText" SIZE=25>
<INPUT TYPE="BUTTON" NAME="cmdChangeIt" VALUE="Change Text">
<INPUT TYPE="BUTTON" NAME="cmdRotate" VALUE="Rotate Label">
</FORM>

With the form defined, an event procedure for the cmdChangeIt button changes the label text:

<SCRIPT LANGUAGE="VBScript">
<!--
Sub cmdChangeIt_onClick
   Dim TheForm
   Set TheForm = Document.LabelControls
   lblActiveLbl.Caption = TheForm.txtNewText.Value
End Sub
-->
</SCRIPT>

The code qualifies references to controls and values inside the forms just as in the Simple Validation example.

Several ActiveX controls are available for use with Internet Explorer. You can find complete information about the properties, methods, and events there, as well as the class identifiers (CLSID) for the controls on the Microsoft® Web site (http://www.microsoft.com). You can find more information about the <OBJECT> tag on the Internet Explorer 4.0 Author's Guide and HTML Reference page.

Note Earlier releases of Internet Explorer required braces ({}) around the classid attribute and did not conform to the W3C specification. Using braces with the current release generates a "This page uses an outdated version of the <OBJECT> tag" message.


Introduction to Regular Expressions

The information contained in these pages is intended to provide an introduction to regular expressions in general.

While an attempt has been made to make each topic stand on it's own, much of the information contained in these topics relies upon the understanding of a previously introduced feature or concept. Therefore, it's recommended that you peruse these topics sequentially for the best overall understanding of the material.

The Introduction to Regular Expressions consists of the following individuals topics:

Regular Expressions

Early Beginnings

Uses for Regular Expressions

Regular Expression Syntax

Build a Regular Expression

Order of Precedence

Ordinary Characters

Special Characters

Non-Printable Characters

Character Matching

Quantifiers

Anchors

Alternation and Grouping

Backreferences


Early Beginnings

Regular expressions trace their ancestry back to early research on how the human nervous system works. Warren McCulloch and Walter Pitts, a pair of neuro-physiologists, developed a mathematical way of describing these neural networks.

In 1956, an mathematician named Stephen Kleene, building on the earlier work of McCulloch and Pitts, published a paper entitled, Representation of Events in Nerve Nets that introduced the concept of regular expressions. Regular expressions were expressions used to describe what he called "the algebra of regular sets". hence the term "regular expression."

Subsequently, his work found its way into some early efforts with computational search algorithms done by Ken Thompson, the principal inventor of Unix. The first practical application of regular expressions was in the Unix editor called qed.

And the rest, as they say, is history. Regular expressions have been an important part of text-based editors and search tools ever since.


Regular Expression Syntax

A regular expression is a pattern of text that consists of ordinary characters (for example, letters a through z) and special characters, known as metacharacters. The pattern describes one or more strings to match when searching a body of text. The regular expression serves as a template for matching a character pattern to the string being searched.

Here are some examples of regular expression you might encounter:

JScript | VBScript | Matches
/^\[ \t]*$/ | "^\[ \t]*$" | 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.
/<(.*)>.*<\/\1>/ | "<(.*)>.*<\/\1>" | Match an HTML tag.

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 either a special character, a literal, a backreference, or an octal escape. For example, 'n' matches the character "n". '\n' matches a newline character. The sequence '\\' matches "\" and "\(" matches "(".
^ | Matches the position at the beginning of the input string. If the RegExp object's Multiline property is set, ^ also matches the position following '\n' or '\r'.
$ | Matches the position at the end of the input string. If the RegExp object's Multiline property is set, $ also matches the position preceding '\n' or '\r'.
* | Matches the preceding subexpression zero or more times. For example, zo* matches "z" and "zoo". * is equivalent to {0,}.
+ | Matches the preceding subexpression one or more times. For example, 'zo+' matches "zo" and "zoo", but not "z". + is equivalent to {1,}.
? | Matches the preceding subexpression zero or one time. For example, "do(es)?" matches the "do" in "do" or "does". ? is equivalent to {0,1}
{n} | 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 '[.\n]'.
(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 whitespace character including space, tab, form-feed, etc. 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 exists, \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 (©).


Quantifiers

Sometimes, you don't know how many characters there are to match. In order to accommodate that kind of uncertainty, regular expressions support the concept of quantifiers. These quantifiers let you specify how many times a given component of your regular expression must occur for your match to be true.

The following table illustrates the various quantifiers and their meanings:

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

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

The following VBScript regular expression performs the identical match:

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

Notice that the quantifier appears after the range expression. Therefore, it applies to the entire range expression that, in this case, specifies only digits from 0 through 9, inclusive.

The '+' quantifier is not used here because there does not necessarily need to be a digit in the second or subsequent position. The '?' character also is not used because it limits the chapter numbers to only two digits. You want to match at least one digit following 'Chapter' and a space character.

If you know that your chapter numbers are limited to only 99 chapters, you can use the following JScript expression to specify at least one, but not more than 2 digits.

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

For VBScript, use the following regular expression:

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

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

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

or

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

For VBScript, the following expressions are equivalent:

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

or

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

The '*', '+', and '?' quantifiers are all what are referred to as greedy, that is, they match as much text as possible. Sometimes that's not at all what you want to happen. Sometimes, you just want a minimal match.

Say, for example, you are searching an HTML document for an occurrence of a chapter title enclosed in an H1 tag. That text appears in your document as:

<H1>Chapter 1 – Introduction to Regular Expressions</H1>

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

/<.*>/

The VBScript regular expression is:

"<.*>"

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

/<.*?>/

or

"<.*?>"

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


Alternation and Grouping

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

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

Unfortunately, what happens is that the regular expressions shown above match either the word 'Chapter' at the beginning of a line, or 'Section' and whatever numbers follow that, at the end of the line. If the input string is 'Chapter 22', the expression shown above only matches the word 'Chapter'. If the input string is 'Section 22', the expression matches 'Section 22'. But that's not the intent here so there must be a way to make that regular expression more responsive to what you're trying to do and there is.

You can use parentheses to limit the scope of the alternation, that is, make sure that it applies only to the two words, 'Chapter' and 'Section'. However, parentheses are tricky as well, because they are also used to create subexpressions, something that's covered later in the section on subexpressions. By taking the regular expressions shown above and adding parentheses in the appropriate places, you can make the regular expression match either 'Chapter 1' or 'Section 3'.

The following regular expressions use parentheses to group 'Chapter' and 'Section' so the expression works properly. For JScript:

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

For VBScript:

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

These expressions work properly except that an interesting by-product occurs. Placing parentheses around 'Chapter|Section' establishes the proper grouping, but it also causes either of the two matching words to be captured for future use. Since there's only one set of parentheses in the expression shown above, there is only one captured submatch. This submatch can be referred to using the Submatches collection in VBScript or the $1-$9 properties of the RegExp object in JScript.

Sometimes capturing a submatch is desirable, sometimes it's not. In the examples shown above, all you really want to do is use the parentheses for grouping a choice between the words 'Chapter' or 'Section'. You don't necessarily want to refer to that match later. In fact, unless you really need to capture submatches, don't use them. Your regular expressions will be more efficient since they won't have to take the time and memory to store those submatches.

You can use '?:' before the regular expression pattern inside the parentheses to prevent the match from being saved for possible later use. The following modification of the regular expressions shown above provides the same capability without saving the submatch. For JScript:

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

For VBScript:

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

In addition to the '?:' metacharacters, there are two other non-capturing metacharacters used for something called lookahead matches. A positive lookahead, specified using ?=, matches the search string at any point where a matching regular expression pattern in parentheses begins. A negative lookahead, specified using '?!', matches the search string at any point where a string not matching the regular expression pattern begins.

For example, suppose you have a document containing references to Windows 3.1, Windows 95, Windows 98, and Windows NT. Suppose further that you need to update the document by finding all the references to Windows 95, Windows 98, and Windows NT and changing those reference to Windows 2000. You can use the following JScript regular expression, which is an example of a positive lookahead, to match Windows 95, Windows 98, and Windows NT:

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

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

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

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


Backreferences

One of the most important features of regular expressions is the ability to store a part of a matched pattern for later reuse. As you'll recall, placing parentheses around a regular expression pattern or part of a pattern causes that part of the expression to be stored into a temporary buffer. You can override the saving of that part of the regular expression using the non-capturing metacharacters '?:', '?=', or '?!'.

Each captured submatch is stored as it is encountered from left to right in a regular expressions pattern. The buffer numbers where the submatches are stored begin at 1 and continue up to a maximum of 99 subexpressions. Each different buffer can be accessed using '\n' where n is one or two decimal digits identifying a specific buffer.

One of the simplest, most useful applications of back references provides the ability to locate the occurrence of two identical words together in a text. Take the following sentence:

Is is the cost of of gasoline going up up?

As written, the sentence shown above clearly has a problem with several duplicated words. It would be nice to devise a way to fix that sentence without having to look for duplicates of every single word. The following JScript regular expression uses a single subexpression to do that.

/\b([a-z]+) \1\b/gi

The equivalent VBScript expression is:

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

The subexpression, in this case, is everything between parentheses. That captured expression includes one or more alphabetic characters, as specified by '[a-z]+'. The second part of the regular expression is the reference to the previously captured submatch, that is, the second occurrence of the word just matched by the parenthetical expression. '\1' is used to specified the first submatch. The word boundary Meta characters ensure that only separate words are detected. If they weren't, a phrase such as "is issued" or "this is" would be incorrectly identified by this expression.

In the JScript expression the global flag ('g') following the regular expression indicates that the expression is applied to as many matches as it can find in the input string. The case insensitivity ('i') flag at the end of the expression specifies the case insensitivity. The multiline flag specifies that potential matches may occur on either side of a newline character. For VBScript, the various flags cannot be set in the expression but must be explicitly set using properties of the RegExp object.

Using the regular expression shown above, the following JScript code can use the submatch information to replace an occurrence of two consecutive identical words in a string of text with a single occurrence of the same word:

var ss = "Is is the cost of of gasoline going up up?.\n";
var re = /\b([a-z]+) \1\b/gim;       //Create regular expression pattern.
var rv = ss.replace(re,"$1");   //Replace two occurrences with one.

The closest equivalent VBScript code appears as follows:

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

In the VBScript code, notice that the global, case-insensitivity, and multiline flags are set using the appropriately named properties of the RegExp object.

The use of the $1 within the replace method refers to the first saved submatch. If you had more than one submatch, you'd refer to them consecutively by $2, $3, and so on.

Another way that backreferences can be used is to break down a Universal Resource Indicator (URI) into its component parts. Assume that you want to break down the following URI down to the protocol (ftp, http, etc), the domain address, and the page/path:

http://msdn.microsoft.com:80/scripting/default.htm

The following regular expressions provide that functionality. For JScript:

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

For VBScript:

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

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

Applying the regular expression to the URI shown above, the submatches contain the following:

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


VBScript Language Reference

Constants

Errors

Events

Functions

Methods

Miscellaneous

Objects and Collections

Operators

Properties

Statements


Version Information

The following table lists the version of Microsoft Visual Basic Scripting Edition implemented by host applications.

Host Application | 1.0 | 2.0 | 3.0 | 4.0 | 5.0 | 5.5 | 5.6
Microsoft Internet Explorer 3.0 | x |  |  |  |  |  |
Microsoft Internet Information Server 3.0 |  | x |  |  |  |  |
Microsoft Internet Explorer 4.0 |  |  | x |  |  |  |
Microsoft Internet Information Server 4.0 |  |  | x |  |  |  |
Microsoft Windows Scripting Host 1.0 |  |  | x |  |  |  |
Microsoft Outlook 98 |  |  | x |  |  |  |
Microsoft Visual Studio 6.0 |  |  |  | x |  |  |
Microsoft Internet Explorer 5.0 |  |  |  |  | x |  |
Microsoft Internet Information Services 5.0 |  |  |  |  | x |  |
Microsoft Internet Explorer 5.5 |  |  |  |  |  | x |
Microsoft Visual Studio .NET |  |  |  |  |  |  | x

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

Language Element | 1.0 | 2.0 | 3.0 | 4.0 | 5.0 | 5.5 | 5.6
Abs Function | x |  |  |  |  |  |
Addition Operator (+) | x |  |  |  |  |  |
And Operator | x |  |  |  |  |  |
Array Function |  | x |  |  |  |  |
Asc Function | x |  |  |  |  |  |
Assignment Operator (=) | 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 |  |  |  |  | x |  |
Clear Method | x |  |  |  |  |  |
CLng Function | x |  |  |  |  |  |
Color Constants |  | x |  |  |  |  |
Comparison Constants |  | x |  |  |  |  |
Concatenation Operator (&) | x |  |  |  |  |  |
Const Statement |  | 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 |  |  |  |  |  |
Description Property | x |  |  |  |  |  |
Dim Statement | x |  |  |  |  |  |
Division Operator (/) | x |  |  |  |  |  |
Do...Loop Statement | x |  |  |  |  |  |
Empty | x |  |  |  |  |  |
Eqv Operator | x |  |  |  |  |  |
Erase Statement | x |  |  |  |  |  |
Err Object | x |  |  |  |  |  |
Eval Function |  |  |  |  | x |  |
Execute Method |  |  |  |  | x |  |
Execute Statement |  |  |  |  | x |  |
ExecuteGlobal Statement |  |  |  |  | x |  |
Exit Statement | x |  |  |  |  |  |
Exp Function | x |  |  |  |  |  |
Exponentiation Operator (^) | x |  |  |  |  |  |
False | x |  |  |  |  |  |
Filter Function |  | x |  |  |  |  |
FirstIndex Property |  |  |  |  | x |  |
Fix Function | x |  |  |  |  |  |
For...Next Statement | x |  |  |  |  |  |
For Each...Next Statement |  | x |  |  |  |  |
FormatCurrency Function |  | x |  |  |  |  |
FormatDateTime Function |  | x |  |  |  |  |
FormatNumber Function |  | x |  |  |  |  |
FormatPercent Function |  | x |  |  |  |  |
Function Statement | x |  |  |  |  |  |
GetLocale Function |  |  |  |  | x |  |
GetObject Function |  | x |  |  |  |  |
GetRef Function |  |  |  |  | x |  |
Global Property |  |  |  |  | x |  |
Hex Function | x |  |  |  |  |  |
HelpContext Property |  | x |  |  |  |  |
HelpFile Property |  | x |  |  |  |  |
Hour Function | x |  |  |  |  |  |
If...Then...Else Statement | x |  |  |  |  |  |
IgnoreCase Property |  |  |  |  | x |  |
Imp Operator | x |  |  |  |  |  |
Initialize Event |  |  |  |  | x |  |
InputBox Function | x |  |  |  |  |  |
InStr Function | x |  |  |  |  |  |
InStrRev Function |  | x |  |  |  |  |
Int Function | 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 Function | x |  |  |  |  |  |
Match Object |  |  |  |  | x |  |
Matches Collection |  |  |  |  | x |  |
Mid Function | x |  |  |  |  |  |
Minute Function | x |  |  |  |  |  |
Miscellaneous Constants |  | x |  |  |  |  |
Mod Operator | x |  |  |  |  |  |
Month Function | x |  |  |  |  |  |
MonthName Function |  | x |  |  |  |  |
MsgBox Constants |  | x |  |  |  |  |
MsgBox Function | x |  |  |  |  |  |
Multiplication Operator (*) | x |  |  |  |  |  |
Negation Operator (-) | x |  |  |  |  |  |
Not Operator | x |  |  |  |  |  |
Now Function | x |  |  |  |  |  |
Nothing | x |  |  |  |  |  |
Null | x |  |  |  |  |  |
Number Property | x |  |  |  |  |  |
Oct Function | x |  |  |  |  |  |
On Error Statement | x |  |  |  |  |  |
Option Explicit Statement | x |  |  |  |  |  |
Or Operator | x |  |  |  |  |  |
Pattern Property |  |  |  |  | x |  |
Private Statement |  | x |  |  |  |  |
PropertyGet Statement |  |  |  |  | x |  |
PropertyLet Statement |  |  |  |  | x |  |
PropertySet Statement |  |  |  |  | x |  |
Public Statement |  | x |  |  |  |  |
Raise Method | x |  |  |  |  |  |
Randomize Statement | x |  |  |  |  |  |
ReDim Statement | x |  |  |  |  |  |
RegExp Object |  |  |  |  | x |  |
Rem Statement | x |  |  |  |  |  |
Replace Function |  | x |  |  |  |  |
Replace Method |  |  |  |  | x |  |
RGB Function |  | x |  |  |  |  |
Right Function | x |  |  |  |  |  |
Rnd Function | x |  |  |  |  |  |
Round Function |  | x |  |  |  |  |
RTrim Function | 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 | x |  |  |  |  |  |
Space Function | x |  |  |  |  |  |
Split Function |  | x |  |  |  |  |
Sqr Function | x |  |  |  |  |  |
StrComp Function | x |  |  |  |  |  |
String Constants |  | x |  |  |  |  |
String Function | x |  |  |  |  |  |
StrReverse Function |  | x |  |  |  |  |
Sub Statement | x |  |  |  |  |  |
Subtraction Operator (-) | x |  |  |  |  |  |
Tan Function | x |  |  |  |  |  |
Terminate Event |  |  |  |  | x |  |
Test Method |  |  |  |  | x |  |
Time Function | x |  |  |  |  |  |
Timer Function |  |  |  |  | x |  |
TimeSerial Function | x |  |  |  |  |  |
TimeValue Function | x |  |  |  |  |  |
Trim Function | x |  |  |  |  |  |
Tristate Constants |  | x |  |  |  |  |
True | x |  |  |  |  |  |
TypeName Function |  | x |  |  |  |  |
UBound Function | x |  |  |  |  |  |
UCase Function | x |  |  |  |  |  |
Value Property |  |  |  |  | x |  |
VarType Constants |  | x |  |  |  |  |
VarType Function | x |  |  |  |  |  |
VBScript Constants |  | x |  |  |  |  |
Weekday Function | x |  |  |  |  |  |
WeekdayName Function |  | x |  |  |  |  |
While...Wend Statement | x |  |  |  |  |  |
With Statement |  |  |  |  | x |  |
Xor Operator | x |  |  |  |  |  |
Year Function | x |  |  |  |  |  |


VBScript Constants

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

Here are the various categories of constants provided in VBScript and a brief description of each:

  • Color Constants Defines eight basic colors that can be used in scripting.
  • 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

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

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


Comparison Constants

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

Constant | Value | Description
vbBinaryCompare | 0 | Perform a binary comparison.
vbTextCompare | 1 | Perform a textual comparison.

Requirements

Version 2

See Also

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


Date and Time Constants

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

Constant | Value | 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

Color Constants | Comparison Constants | Date Format Constants | Miscellaneous Constants | MsgBox Constants | String Constants | Tristate Constants | VarType Constants


Date Format Constants

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

Constant | Value | 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

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


Miscellaneous Constants

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

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

Requirements

Version 2

See Also

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


MsgBox Constants

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

Constant | Value | 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

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


String Constants

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

Constant | 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

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


Tristate Constants

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

Constant | Value | Description
vbUseDefault | -2 | Use default from computer's regional settings.
vbTrue | -1 | True
vbFalse | 0 | False

Requirements

Version 2

See Also

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


VarType Constants

These constants are only available when your project has an explicit reference to the appropriate type library containing these constant definitions. For VBScript, you must explicitly declare these constants in your code.

Constant | Value | Description
vbEmpty | 0 | Uninitialized (default)
vbNull | 1 | Contains no valid data
vbInteger | 2 | Integer subtype
vbLong | 3 | Long subtype
vbSingle | 4 | Single subtype
vbSingle | 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

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


Errors

In This Section

VBScript Run-time Errors

VBScript Syntax Errors

Related Sections

© 2001 Microsoft Corporation. All rights reserved.

Build: Topic Version 5.6.9309.1546


VBScript Run-time Errors

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

Error Number | Description
429 | 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

VBScript Syntax Errors


VBScript Syntax Errors

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

Error Number | 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

VBScript Run-time Errors


Events

In This Section

Initialize Event

Terminate Event

Related Sections

VBScript Langauge Reference


Initialize Event

Occurs when an instance of the associated class is created.

Private Sub Class_Initialize()
   statements
End Sub

The statements part consists of zero or more code statements to be run when the class is initialized.

Remarks

The following example illustrates the use of the Initialize event.

Class TestClass
   Private Sub Class_Initialize   ' Setup Initialize event.
      MsgBox("TestClass started")
   End Sub
   Private Sub Class_Terminate   ' Setup Terminate event.
      MsgBox("TestClass terminated")
   End Sub
End Class

Set X = New TestClass   ' Create an instance of TestClass.
Set X = Nothing   ' Destroy the instance.

Requirements

Version 5

See Also

Class Object | Class Statement | Terminate Event

Applies To: Class Object


Terminate Event

Occurs when an instance of the associated class is terminated.

Private Sub Class_Terminate()
   statements
End Sub

The statements part consists of zero or more code statements to be run when the class is initialized.

Remarks

The following example illustrates the use of the Terminate event.

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

Requirements

Version 5

See Also

Class Object | Class Statement | Initialize Event

Applies To: Class Object


Functions

The following table contains the VBScript functions.

Abs | Array | Asc | Atn
CBool | CByte | CCur | CDate
CDbl | Chr | CInt | CLng
Conversions | Cos | CreateObject | CSng
Date | DateAdd | DateDiff | DatePart
DateSerial | DateValue | Day | Derived Maths
Eval | Exp | Filter | FormatCurrency
FormatDateTime | FormatNumber | FormatPercent | GetLocale
GetObject | GetRef | Hex | Hour
InputBox | InStr | InStrRev | Int, Fixs
IsArray | IsDate | IsEmpty | IsNull
IsNumeric | IsObject | Join | LBound
LCase | Left | Len | LoadPicture
Log | LTrim; RTrim; and Trims | 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
Tan | Time | Timer | TimeSerial
TimeValue | TypeName | UBound | UCase
VarType | Weekday | WeekdayName | Year

Related Sections

VBScript Langauge Reference


Abs Function

Returns the absolute value of a number.

Abs(number)

The number argument can be any valid numeric expression. If number contains Null, Null is returned; if it is an uninitialized variable, zero is returned.

Remarks

The absolute value of a number is its unsigned magnitude. For example, Abs(-1) and Abs(1) both return 1.

The following example uses the Abs function to compute the absolute value of a number:

Dim MyNumber
MyNumber = Abs(50.3)  ' Returns 50.3.
MyNumber = Abs(-50.3) ' Returns 50.3.

Requirements

Version 1

See Also

Sgn Function


Array Function

Returns a Variant containing an array.

Array(arglist)

The required arglist argument is a comma-delimited list of values that are assigned to the elements of an array contained with the Variant. If no arguments are specified, an array of zero length is created.

Remarks

The notation used to refer to an element of an array consists of the variable name followed by parentheses containing an index number indicating the desired element. In the following example, the first statement creates a variable named A. The second statement assigns an array to variable A. The last statement assigns the value contained in the second array element to another variable.

Dim A
A = Array(10,20,30)
B = A(2)   ' B is now 30.
Note A variable that is not declared as an array can still contain an array. Although a Variant variable containing an array is conceptually different from an array variable containing Variant elements, the array elements are accessed in the same way.

Requirements

Version 2

See Also

Dim Statement


Asc Function

Returns the ANSI character code corresponding to the first letter in a string.

Asc(string)

The string argument is any valid string expression. If the string contains no characters, a run-time error occurs.

Remarks

In the following example, Asc returns the ANSI character code of the first letter of each string:

Dim MyNumber
MyNumber = Asc("A")       ' Returns 65.
MyNumber = Asc("a")       ' Returns 97.
MyNumber = Asc("Apple")   ' Returns 65.
Note The AscB function is used with byte data contained in a string. Instead of returning the character code for the first character, AscB returns the first byte. AscW is provided for 32-bit platforms that use Unicode characters. It returns the Unicode (wide) character code, thereby avoiding the conversion from Unicode to ANSI.

Requirements

Version 1

See Also

Chr Function


Atn Function

Returns the arctangent of a number.

Atn(number)

The number argument can be any valid numeric expression.

Remarks

The Atn function takes the ratio of two sides of a right triangle (number) and returns the corresponding angle in radians. The ratio is the length of the side opposite the angle divided by the length of the side adjacent to the angle. The range of the result is -pi /2 to pi/2 radians.

To convert degrees to radians, multiply degrees by pi/180. To convert radians to degrees, multiply radians by 180/pi.

The following example uses Atn to calculate the value of pi:

Dim pi
pi = 4 * Atn(1)   ' Calculate the value of pi.
Note 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).

Requirements

Version 1

See Also

Cos Function | Derived Math Functions | Sin Function | Tan Function


CBool Function

Returns an expression that has been converted to a Variant of subtype Boolean.

CBool(expression)

The expression argument is any valid expression.

Remarks

If expression is zero, False is returned; otherwise, True is returned. If expression can't be interpreted as a numeric value, a run-time error occurs.

The following example uses the CBool function to convert an expression to a Boolean. If the expression evaluates to a nonzero value, CBool returns True; otherwise, it returns False.

Dim A, B, Check
A = 5: B = 5           ' Initialize variables.
Check = CBool(A = B)   ' Check contains True.
A = 0                  ' Define variable.
Check = CBool(A)       ' Check contains False.

Requirements

Version 1

See Also

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


CByte Function

Returns an expression that has been converted to a Variant of subtype Byte.

CByte(expression)

The expression argument is any valid expression.

Remarks

In general, you can document your code using the subtype conversion functions to show that the result of some operation should be expressed as a particular data type rather than the default data type. For example, use CByte to force byte arithmetic in cases where currency, single-precision, double-precision, or integer arithmetic normally would occur.

Use the CByte function to provide internationally aware conversions from any other data type to a Byte subtype. For example, different decimal separators are properly recognized depending on the locale setting of your system, as are different thousand separators.

If expression lies outside the acceptable range for the byte subtype, an error occurs. The following example uses the CByte function to convert an expression to a byte:

Dim MyDouble, MyByte
MyDouble = 125.5678        ' MyDouble is a Double.
MyByte = CByte(MyDouble)   ' MyByte contains 126.

Requirements

Version 1

See Also

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


CCur Function

Returns an expression that has been converted to a Variant of subtype Currency.

CCur(expression)

The expression argument is any valid expression.

Remarks

In general, you can document your code using the subtype conversion functions to show that the result of some operation should be expressed as a particular data type rather than the default data type. For example, use CCur to force currency arithmetic in cases where integer arithmetic normally would occur.

You should use the CCur function to provide internationally aware conversions from any other data type to a Currency subtype. For example, different decimal separators and thousands separators are properly recognized depending on the locale setting of your system.

The following example uses the CCur function to convert an expression to a Currency:

Dim MyDouble, MyCurr
MyDouble = 543.214588         ' MyDouble is a Double.
MyCurr = CCur(MyDouble * 2)   ' Convert result of MyDouble * 2 (1086.429176) to a Currency (1086.4292).

Requirements

Version 1

See Also

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


CDate Function

Returns an expression that has been converted to a Variant of subtype Date.

CDate(date)

The date argument is any valid date expression.

Remarks

Use the IsDate function to determine if date can be converted to a date or time. CDate recognizes date literals and time literals as well as some numbers that fall within the range of acceptable dates. When converting a number to a date, the whole number portion is converted to a date. Any fractional part of the number is converted to a time of day, starting at midnight.

CDate recognizes date formats according to the locale setting of your system. The correct order of day, month, and year may not be determined if it is provided in a format other than one of the recognized date settings. In addition, a long date format is not recognized if it also contains the day-of-the-week string.

The following example uses the CDate function to convert a string to a date. In general, hard coding dates and times as strings (as shown in this example) is not recommended. Use date and time literals (such as #10/19/1962#, #4:45:23 PM#) instead.

MyDate = "October 19, 1962"   ' 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.

Requirements

Version 1

See Also

IsDate Function


CDbl Function

Returns an expression that has been converted to a Variant of subtype Double.

CDbl(expression)

The expression argument is any valid expression.

Remarks

In general, you can document your code using the subtype conversion functions to show that the result of some operation should be expressed as a particular data type rather than the default data type. For example, use CDbl or CSng to force double-precision or single-precision arithmetic in cases where currency or integer arithmetic normally would occur.

Use the CDbl function to provide internationally aware conversions from any other data type to a Double subtype. For example, different decimal separators and thousands separators are properly recognized depending on the locale setting of your system.

This example uses the CDbl function to convert an expression to a Double.

Dim MyCurr, MyDouble
MyCurr = CCur(234.456784)              ' MyCurr is a Currency (234.4567).
MyDouble = CDbl(MyCurr * 8.2 * 0.01)   ' Convert result to a Double (19.2254576).

Requirements

Version 1

See Also

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


Chr Function

Returns the character associated with the specified ANSI character code.

Chr(charcode)

The charcode argument is a number that identifies a character.

Remarks

Numbers from 0 to 31 are the same as standard, nonprintable ASCII codes. For example, Chr(10) returns a linefeed character.

The following example uses the Chr function to return the character associated with the specified character code:

Dim MyChar
MyChar = Chr(65)   ' Returns A.
MyChar = Chr(97)   ' Returns a.
MyChar = Chr(62)   ' Returns >.
MyChar = Chr(37)   ' Returns %.
Note The ChrB function is used with byte data contained in a string. Instead of returning a character, which may be one or two bytes, ChrB always returns a single byte. ChrW is provided for 32-bit platforms that use Unicode characters. Its argument is a Unicode (wide) character code, thereby avoiding the conversion from ANSI to Unicode.

Requirements

Version 1

See Also

Asc Function


CInt Function

Returns an expression that has been converted to a Variant of subtype Integer.

CInt(expression)

The expression argument is any valid expression.

Remarks

In general, you can document your code using the subtype conversion functions to show that the result of some operation should be expressed as a particular data type rather than the default data type. For example, use CInt or CLng to force integer arithmetic in cases where currency, single-precision, or double-precision arithmetic normally would occur.

Use the CInt function to provide internationally aware conversions from any other data type to an Integer subtype. For example, different decimal separators are properly recognized depending on the locale setting of your system, as are different thousand separators.

If expression lies outside the acceptable range for the Integer subtype, an error occurs.

The following example uses the CInt function to convert a value to an Integer:

Dim MyDouble, MyInt
MyDouble = 2345.5678     ' MyDouble is a Double.
MyInt = CInt(MyDouble)   ' MyInt contains 2346.
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.

Requirements

Version 1

See Also

CBool Function | CByte Function | CCur Function | CDate Function | CDbl Function | CLng Function | CSng Function | CStr Function | Int, Fix Functions


CLng Function

Returns an expression that has been converted to a Variant of subtype Long.

CLng(expression)

The expression argument is any valid expression.

Remarks

In general, you can document your code using the subtype conversion functions to show that the result of some operation should be expressed as a particular data type rather than the default data type. For example, use CInt or CLng to force integer arithmetic in cases where currency, single-precision, or double-precision arithmetic normally would occur.

Use the CLng function to provide internationally aware conversions from any other data type to a Long subtype. For example, different decimal separators are properly recognized depending on the locale setting of your system, as are different thousand separators.

If expression lies outside the acceptable range for the Long subtype, an error occurs.

The following example uses the CLng function to convert a value to a Long:

Dim MyVal1, MyVal2, MyLong1, MyLong2
MyVal1 = 25427.45: MyVal2 = 25427.55   ' MyVal1, MyVal2 are Doubles.
MyLong1 = CLng(MyVal1)   ' MyLong1 contains 25427.
MyLong2 = CLng(MyVal2)   ' MyLong2 contains 25428.
Note CLng differs from the Fix and Int functions, which truncate, rather than round, the fractional part of a number. When the fractional part is exactly 0.5, the CLng function always rounds it to the nearest even number. For example, 0.5 rounds to 0, and 1.5 rounds to 2.

Requirements

Version 1

See Also

CBool Function | CByte Function | CCur Function | CDate Function | CDbl Function | CInt Function | CSng Function | CStr Function | Int, Fix Functions


Conversion Functions

Asc Function

CBool Function

CByte Function

CCur Function

CDate Function

CDbl Function

Chr Function

CInt Function

CLng Function

CSng Function

CStr Function

Hex Function

Oct Function


Cos Function

Returns the cosine of an angle.

Cos(number)

The number argument can be any valid numeric expression that expresses an angle in radians.

Remarks

The Cos function takes an angle and returns the ratio of two sides of a right triangle. The ratio is the length of the side adjacent to the angle divided by the length of the hypotenuse. The result lies in the range -1 to 1.

To convert degrees to radians, multiply degrees by pi /180. To convert radians to degrees, multiply radians by 180/pi.

The following example uses the Cos function to return the cosine of an angle:

Dim MyAngle, MySecant
MyAngle = 1.3                 ' Define angle in radians.
MySecant = 1 / Cos(MyAngle)   ' Calculate secant.

Requirements

Version 1

See Also

Atn Function | Derived Math Functions | Sin Function | Tan Function


CreateObject Function

Creates and returns a reference to an Automation object.

CreateObject(servername.typename [, location])

Arguments

servername
Required. The name of the application providing the object.
typename
Required. The type or class of the object to create.
location
Optional. The name of the network server where the object is to be created.

Remarks

Automation servers provide at least one type of object. For example, a word-processing application may provide an application object, a document object, and a toolbar object.

To create an Automation object, assign the object returned by CreateObject to an object variable:

Dim ExcelSheet
Set ExcelSheet = CreateObject("Excel.Sheet")

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

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

Creating an object on a remote server can only be accomplished when Internet security is turned off. You can create an object on a remote networked computer by passing the name of the computer to the servername argument of CreateObject. That name is the same as the machine name portion of a share name. For a network share named "\\myserver\public", the servername is "myserver". In addition, you can specify servername using DNS format or an IP address.

The following code returns the version number of an instance of Excel running on a remote network computer named "myserver":

Function GetVersion
   Dim XLApp
   Set XLApp = CreateObject("Excel.Application", "MyServer")
   GetVersion = XLApp.Version
End Function

An error occurs if the specified remote server does not exist or cannot be found.

Requirements

Version 2

See Also

GetObject Function


CSng Function

Returns an expression that has been converted to a Variant of subtype Single.

CSng(expression)

The expression argument is any valid expression.

Remarks

In general, you can document your code using the data type conversion functions to show that the result of some operation should be expressed as a particular data type rather than the default data type. For example, use CDbl or CSng to force double-precision or single-precision arithmetic in cases where currency or integer arithmetic normally would occur.

Use the CSng function to provide internationally aware conversions from any other data type to a Single subtype. For example, different decimal separators are properly recognized depending on the locale setting of your system, as are different thousand separators.

If expression lies outside the acceptable range for the Single subtype, an error occurs.

The following example uses the CSng function to convert a value to a Single:

Dim MyDouble1, MyDouble2, MySingle1, MySingle2   ' MyDouble1, MyDouble2 are Doubles.
MyDouble1 = 75.3421115: MyDouble2 = 75.3421555
MySingle1 = CSng(MyDouble1)   ' MySingle1 contains 75.34211.
MySingle2 = CSng(MyDouble2)   ' MySingle2 contains 75.34216.

Requirements

Version 1

See Also

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


CStr Function

Returns an expression that has been converted to a Variant of subtype String.

CStr(expression)

The expression argument is any valid expression.

Remarks

In general, you can document your code using the data type conversion functions to show that the result of some operation should be expressed as a particular data type rather than the default data type. For example, use CStr to force the result to be expressed as a String.

You should use the CStr function instead of Str to provide internationally aware conversions from any other data type to a String subtype. For example, different decimal separators are properly recognized depending on the locale setting of your system.

The data in expression determines what is returned according to the following table:

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

Dim MyDouble, MyString
MyDouble = 437.324         ' MyDouble is a Double.
MyString = CStr(MyDouble)   ' MyString contains "437.324".

Requirements

Version 1

See Also

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


Date Function

Returns the current system date.

Date

Remarks

The following example uses the Date function to return the current system date:

Dim MyDate
MyDate = Date   ' MyDate contains the current system date.

Requirements

Version 1

See Also

CDate Function | Now Function | Time Function


DateAdd Function

Returns a date to which a specified time interval has been added.

DateAdd(interval, number, date)

Arguments

interval
Required. String expression that is the interval you want to add. See Settings section for values.
number
Required. Numeric expression that is the number of interval you want to add. The numeric expression can either be positive, for dates in the future, or negative, for dates in the past.
date
Required. Variant or literal representing the date to which interval is added.

Settings

The interval argument can have the following values:

Setting | Description
yyyy | Year
q | Quarter
m | Month
y | Day of year
d | Day
w | Weekday
ww | Week of year
h | Hour
n | Minute
s | Second

Remarks

You can use the DateAdd function to add or subtract a specified time interval from a date. For example, you can use DateAdd to calculate a date 30 days from today or a time 45 minutes from now. To add days to date, you can use Day of Year ("y"), Day ("d"), or Weekday ("w").

The DateAdd function won't return an invalid date. The following example adds one month to January 31:

NewDate = DateAdd("m", 1, "31-Jan-95")

In this case, DateAdd returns 28-Feb-95, not 31-Feb-95. If date is 31-Jan-96, it returns 29-Feb-96 because 1996 is a leap year.

If the calculated date would precede the year 100, an error occurs.

If number isn't a Long value, it is rounded to the nearest whole number before being evaluated.

Requirements

Version 2

See Also

DateDiff Function | DatePart Function


DateDiff Function

Returns the number of intervals between two dates.

DateDiff(interval, date1, date2 [,firstdayofweek[, firstweekofyear]])

The DateDiff function syntax has these parts:

Arguments

interval
Required. String expression that is the interval you want to use to calculate the differences between date1 and date2. See Settings section for values.
date1, date2
Required. Date expressions. Two dates you want to use in the calculation.
firstdayofweek
Optional. Constant that specifies the day of the week. If not specified, Sunday is assumed. See Settings section for values.
firstweekofyear
Optional. Constant that specifies the first week of the year. If not specified, the first week is assumed to be the week in which January 1 occurs. See Settings section for values.

Settings

The interval argument can have the following values:

Setting | Description
yyyy | Year
q | Quarter
m | Month
y | Day of year
d | Day
w | Weekday
ww | Week of year
h | Hour
n | Minute
s | Second

The firstdayofweek argument can have the following values:

Constant | Value | 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.

Remarks

You can use the DateDiff function to determine how many specified time intervals exist between two dates. For example, you might use DateDiff to calculate the number of days between two dates, or the number of weeks between today and the end of the year.

To calculate the number of days between date1 and date2, you can use either Day of year ("y") or Day ("d"). When interval is Weekday ("w"), DateDiff returns the number of weeks between the two dates. If date1 falls on a Monday, DateDiff counts the number of Mondays until date2. It counts date2 but not date1. If interval is Week ("ww"), however, the DateDiff function returns the number of calendar weeks between the two dates. It counts the number of Sundays between date1 and date2. DateDiff counts date2 if it falls on a Sunday; but it doesn't count date1, even if it does fall on a Sunday.

If date1 refers to a later point in time than date2, the DateDiff function returns a negative number.

The firstdayofweek argument affects calculations that use the "w" and "ww" interval symbols.

If date1 or date2 is a date literal, the specified year becomes a permanent part of that date. However, if date1 or date2 is enclosed in quotation marks (" ") and you omit the year, the current year is inserted in your code each time the date1 or date2 expression is evaluated. This makes it possible to write code that can be used in different years.

When comparing December 31 to January 1 of the immediately succeeding year, DateDiff for Year ("yyyy") returns 1 even though only a day has elapsed.

The following example uses the DateDiff function to display the number of days between a given date and today:

Function DiffADate(theDate)
   DiffADate = "Days from today: " & DateDiff("d", Now, theDate)
End Function

Requirements

Version 2

See Also

DateAdd Function | DatePart Function


DatePart Function

Returns the specified part of a given date.

DatePart(interval, date[, firstdayofweek[, firstweekofyear]])

Arguments

interval
Required. String expression that is the interval of time you want to return. See Settings section for values.
date
Required. Date expression you want to evaluate.
firstdayof week
Optional. Constant that specifies the day of the week. If not specified, Sunday is assumed. See Settings section for values.
firstweekofyear
Optional. Constant that specifies the first week of the year. If not specified, the first week is assumed to be the week in which January 1 occurs. See Settings section for values.

Settings

The interval argument can have the following values:

Setting | Description
yyyy | Year
q | Quarter
m | Month
y | Day of year
d | Day
w | Weekday
ww | Week of year
h | Hour
n | Minute
s | Second

The firstdayofweek argument can have the following values:

Constant | Value | 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.

Remarks

You can use the DatePart function to evaluate a date and return a specific interval of time. For example, you might use DatePart to calculate the day of the week or the current hour.

The firstdayofweek argument affects calculations that use the "w" and "ww" interval symbols.

If date is a date literal, the specified year becomes a permanent part of that date. However, if date is enclosed in quotation marks (" "), and you omit the year, the current year is inserted in your code each time the date expression is evaluated. This makes it possible to write code that can be used in different years.

This example takes a date and, using the DatePart function, displays the quarter of the year in which it occurs.

Function GetQuarter(TheDate)
   GetQuarter = DatePart("q", TheDate)
End Function

Requirements

Version 2

See Also

DateAdd Function | DateDiff Function


DateSerial Function

Returns a Variant of subtype Date for a specified year, month, and day.

DateSerial(year, month, day)

Arguments

year
Number between 100 and 9999, inclusive, or a numeric expression.
month
Any numeric expression.
day
Any numeric expression.

Remarks

To specify a date, such as December 31, 1991, the range of numbers for each DateSerial argument should be in the accepted range for the unit; that is, 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.

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.

Requirements

Version 1

See Also

Date Function | DateValue Function | Day Function | Month Function | Now Function | TimeSerial Function | TimeValue Function | Weekday Function | Year Function


DateValue Function

Returns a Variant of subtype Date.

DateValue(date)

The date argument is normally a string expression representing a date from January 1, 100 through December 31, 9999. However, date can also be any expression that can represent a date, a time, or both a date and time, in that range.

Remarks

If the date argument includes time information, DateValue doesn't return it. However, if date includes invalid time information (such as "89:98"), an error occurs.

If date is a string that includes only numbers separated by valid date separators, DateValue recognizes the order for month, day, and year according to the short date format you specified for your system. DateValue also recognizes unambiguous dates that contain month names, either in long or abbreviated form. For example, in addition to recognizing 12/30/1991 and 12/30/91, DateValue also recognizes December 30, 1991 and Dec 30, 1991.

If the year part of date is omitted, DateValue uses the current year from your computer's system date.

The following example uses the DateValue function to convert a string to a date. You can also use date literals to directly assign a date to a Variant variable, for example, MyDate = #9/11/63#.

Dim MyDate
MyDate = DateValue("September 11, 1963")   ' Return a date.

Requirements

Version 1

See Also

CDate Function | DateSerial Function | Day Function | Month Function | Now Function | TimeSerial Function | TimeValue Function | Weekday Function | Year Function


Day Function

Returns a whole number between 1 and 31, inclusive, representing the day of the month.

Day(date)

The date argument is any expression that can represent a date. If date contains Null, Null is returned.

The following example uses the Day function to obtain the day of the month from a specified date:

Dim MyDay
MyDay = Day("October 19, 1962")   ' MyDay contains 19.

Requirements

Version 1

See Also

Date Function | Hour Function | Minute Function | Month Function | Now Function | Second Function | Weekday Function | Year Function


Derived Math Functions

The following non-intrinsic math functions can be derived from the intrinsic math 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

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


Eval Function

Visual Basic Scripting Edition

Eval

Evaluates an expression and returns the result.

[result = ]Eval(expression)

Arguments

result
Optional. Variable to which return value assignment is made. If result is not specified, consider using the Execute statement instead.
expression
Required. String containing any legal VBScript expression.

Remarks

In VBScript, x = y can be interpreted two ways. The first is as an assignment statement, where the value of y is assigned to x. The second interpretation is as an expression that tests if x and y have the same value. If they do, result is True; if they are not, result is False. The Eval method always uses the second interpretation, whereas the Execute statement always uses the first.

Note In Microsoft® JScript™, no confusion exists between assignment and comparison, because the assignment operator (=) is different from the comparison operator (==).

The following example illustrates the use of the Eval function:

Sub GuessANumber
   Dim Guess, RndNum
   RndNum = Int((100) * Rnd(1) + 1)
   Guess = CInt(InputBox("Enter your guess:",,0))
   Do
      If Eval("Guess = RndNum") Then
         MsgBox "Congratulations! You guessed it!"
         Exit Sub
      Else
         Guess = CInt(InputBox("Sorry! Try again.",,0))
      End If
   Loop Until Guess = 0
End Sub

Requirements

Version 5

See Also

Execute Statement


Exp Function

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

Exp(number)

The number argument can be any valid numeric expression.

Remarks

If the value of number exceeds 709.782712893, an error occurs. The constant e is approximately 2.718282.

Note The Exp function complements the action of the Log function and is sometimes referred to as the antilogarithm.

The following example uses the Exp function to return e raised to a power:

Dim MyAngle, MyHSin   ' Define angle in radians.
MyAngle = 1.3   ' Calculate hyperbolic sine.
MyHSin = (Exp(MyAngle) - Exp(-1 * MyAngle)) / 2

Requirements

Version 1

See Also

Derived Math Functions | Log Function


Filter Function

Returns a zero-based array containing a subset of a string array based on a specified filter criteria.

Filter(InputStrings, Value[, Include[, Compare]])

Arguments

InputStrings
Required. One-dimensional array of strings to be searched.
Value
Required. String to search for.
Include
Optional. Boolean value indicating whether to return substrings that include or exclude Value. If Include is True, Filter returns the subset of the array that contains Value as a substring. If Include is False, Filter returns the subset of the array that does not contain Value as a substring.
Compare
Optional. Numeric value indicating the kind of string comparison to use. See Settings section for values.

Settings

The Compare argument can have the following values:

Constant | Value | Description
vbBinaryCompare | 0 | Perform a binary comparison.
vbTextCompare | 1 | Perform a textual comparison.

Remarks

If no matches of Value are found within InputStrings, Filter returns an empty array. An error occurs if InputStrings is Null or is not a one-dimensional array.

The array returned by the Filter function contains only enough elements to contain the number of matched items.

The following example uses the Filter function to return the array containing the search criteria "Mon":

Dim MyIndex
Dim MyArray (3)
MyArray(0) = "Sunday"
MyArray(1) = "Monday"
MyArray(2) = "Tuesday"
MyIndex = Filter(MyArray, "Mon") ' MyIndex(0) contains "Monday".

Requirements

Version 2

See Also

Replace Function


FormatCurrency Function

Returns an expression formatted as a currency value using the currency symbol defined in the system control panel.

FormatCurrency(Expression[,NumDigitsAfterDecimal [,IncludeLeadingDigit [,UseParensForNegativeNumbers [,GroupDigits]]]])

Arguments

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

Settings

The IncludeLeadingDigit, UseParensForNegativeNumbers, and GroupDigits arguments have the following settings:

Constant | Value | Description
TristateTrue | -1 | True
TristateFalse | 0 | False
TristateUseDefault | -2 | Use the setting from the computer's regional settings.

Remarks

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

Note All settings information comes from the Regional Settings Currency tab, except leading zero, which comes from the Number tab.

The following example uses the FormatCurrency function to format the expression as a currency and assign it to MyCurrency:

Dim MyCurrency
MyCurrency = FormatCurrency(1000)   ' MyCurrency contains $1000.00.

Requirements

Version 2

See Also

FormatDateTime Function | FormatNumber Function | FormatPercent Function


FormatDateTime Function

Returns an expression formatted as a date or time.

FormatDateTime(Date[, NamedFormat])

Arguments

Date
Required. Date expression to be formatted.
NamedFormat
Optional. Numeric value that indicates the date/time format used. If omitted, vbGeneralDate is used.

Settings

The NamedFormat argument has the following settings:

Constant | Value | 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).

Remarks

The following example uses the FormatDateTime function to format the expression as a long date and assign it to MyDateTime:

Function GetCurrentDate
   ' FormatDateTime formats Date in long date.
   GetCurrentDate = FormatDateTime(Date, 1)
End Function

Requirements

Version 2

See Also

FormatCurrency Function | FormatNumber Function | FormatPercent Function


FormatNumber Function

Returns an expression formatted as a number.

FormatNumber(Expression [,NumDigitsAfterDecimal [,IncludeLeadingDigit [,UseParensForNegativeNumbers [,GroupDigits]]]])

Arguments

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

Settings

The IncludeLeadingDigit, UseParensForNegativeNumbers, and GroupDigits arguments have the following settings:

Constant | Value | Description
TristateTrue | -1 | True
TristateFalse | 0 | False
TristateUseDefault | -2 | Use the setting from the computer's regional settings.

Remarks

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

Note All settings information comes from the Regional Settings Number tab.

The following example uses the FormatNumber function to format a number to have four decimal places:

Function FormatNumberDemo
   Dim MyAngle, MySecant, MyNumber
   MyAngle = 1.3   ' Define angle in radians.
   MySecant = 1 / Cos(MyAngle)   ' Calculate secant.
   FormatNumberDemo = FormatNumber(MySecant,4) ' Format MySecant to four decimal places.
End Function

Requirements

Version 2

See Also

FormatCurrency Function | FormatDateTime Function | FormatPercent Function


FormatPercent Function

Returns an expression formatted as a percentage (multiplied by 100) with a trailing % character.

FormatPercent(Expression[,NumDigitsAfterDecimal [,IncludeLeadingDigit [,UseParensForNegativeNumbers [,GroupDigits]]]])

The FormatPercent function syntax has these parts:

Arguments

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

Settings

The IncludeLeadingDigit, UseParensForNegativeNumbers, and GroupDigits arguments have the following settings:

Constant | Value | Description
TristateTrue | -1 | True
TristateFalse | 0 | False
TristateUseDefault | -2 | Use the setting from the computer's regional settings.

Remarks

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

Note All settings information comes from the Regional Settings Number tab.

The following example uses the FormatPercent function to format an expression as a percent:

Dim MyPercent
MyPercent = FormatPercent(2/32) ' MyPercent contains 6.25%.

Requirements

Version 2

See Also

FormatCurrency Function | FormatDateTime Function | FormatNumber Function


GetLocale Function

Returns the current locale ID value.

GetLocale()

Remarks

A locale is a set of user preference information related to the user's language, country/region, and cultural conventions. The locale determines such things as keyboard layout, alphabetic sort order, as well as date, time, number, and currency formats.

The return value can be any of the 32-bit values shown in the Locale ID chart:

The following example illustrates the use of the GetLocale function. To use this code, paste the entire example between the <BODY> tags of a standard HTML page.

Enter Date in UK format: <input type="text" id="UKDate" size="20"><p>
Here's the US equivalent: <input type="text" id="USdate" size="20"><p>
<input type="button" value="Convert" id="button1"><p>
Enter a price in German: &nbsp; <input type="text" id="GermanNumber" size="20">
<p>
Here's the UK equivalent: <input type="text" id="USNumber" size="20"><p>
<input type="button" value="Convert" id="button2"><p>

<script language="vbscript">
Dim currentLocale
' Get the current locale
currentLocale = GetLocale

Sub Button1_onclick
  Dim original
  original = SetLocale("en-gb")
  mydate = CDate(UKDate.value)
  ' IE always sets the locale to US English so use the
  ' currentLocale variable to set the locale to US English
  original = SetLocale(currentLocale)
  USDate.value = FormatDateTime(mydate,vbShortDate)
End Sub

Sub button2_onclick
  Dim original
  original = SetLocale("de")
  myvalue = CCur(GermanNumber.value)
  original = SetLocale("en-gb")
  USNumber.value = FormatCurrency(myvalue)
End Sub

</script>

See Also

SetLocale Function | Locale ID (LCID) Chart


GetObject Function

Returns a reference to an Automation object from a file.

GetObject([pathname] [, class])

Arguments

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

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

Arguments

appname
Required; String. Name of the application providing the object.
objectype
Required; String. Type or class of object to create.

Remarks

Use the GetObject function to access an Automation object from a file and assign the object to an object variable. Use the Set statement to assign the object returned by GetObject to the object variable. For example:

Dim CADObject
Set CADObject = GetObject("C:\CAD\SCHEMA.CAD")

When this code is executed, the application associated with the specified pathname is started and the object in the specified file is activated. If pathname is a zero-length string (""), GetObject returns a new object instance of the specified type. If the pathname argument is omitted, GetObject returns a currently active object of the specified type. If no object of the specified type exists, an error occurs.

Some applications allow you to activate part of a file. Add an exclamation point (!) to the end of the file name and follow it with a string that identifies the part of the file you want to activate. For information on how to create this string, see the documentation for the application that created the object.

For example, in a drawing application you might have multiple layers to a drawing stored in a file. You could use the following code to activate a layer within a drawing called SCHEMA.CAD:

Set LayerObject = GetObject("C:\CAD\SCHEMA.CAD!Layer3")

If you don't specify the object's class, Automation determines the application to start and the object to activate, based on the file name you provide. Some files, however, may support more than one class of object. For example, a drawing might support three different types of objects: an Application object, a Drawing object, and a Toolbar object, all of which are part of the same file. To specify which object in a file you want to activate, use the optional class argument. For example:

Dim MyObject
Set MyObject = GetObject("C:\DRAWINGS\SAMPLE.DRW", "FIGMENT.DRAWING")

In the preceding example, FIGMENT is the name of a drawing application and DRAWING is one of the object types it supports. Once an object is activated, you reference it in code using the object variable you defined. In the preceding example, you access properties and methods of the new object using the object variable MyObject. For example:

MyObject.Line 9, 90
MyObject.InsertText 9, 100, "Hello, world."
MyObject.SaveAs "C:\DRAWINGS\SAMPLE.DRW"
Note Use the GetObject function when there is a current instance of the object or if you want to create the object with a file already loaded. If there is no current instance, and you don't want the object started with a file loaded, use the CreateObject function.

If an object has registered itself as a single-instance object, only one instance of the object is created, no matter how many times CreateObject is executed. With a single-instance object, GetObject always returns the same instance when called with the zero-length string ("") syntax, and it causes an error if the pathname argument is omitted.

Requirements

Version 5

See Also

CreateObject Function


GetRef Function

Returns a reference to a procedure that can be bound to an event.

Set object.eventname = GetRef(procname)

Arguments

object
Required. Name of the object with which event is associated.
event
Required. Name of the event to which the function is to be bound.
procname
Required. String containing the name of the Sub or Function procedure being associated with the event.

Remarks

The GetRef function allows you to connect a VBScript procedure (Function or Sub) to any available event on your DHTML (Dynamic HTML) pages. The DHTML object model provides information about what events are available for its various objects.

In other scripting and programming languages, the functionality provided by GetRef is referred to as a function pointer, that is, it points to the address of a procedure to be executed when the specified event occurs.

The following example illustrates the use of the GetRef function.

<SCRIPT LANGUAGE="VBScript">

Function GetRefTest()
   Dim Splash
   Splash = "GetRefTest Version 1.0"   & vbCrLf
   Splash = Splash & Chr(169) & " YourCompany 1999 "
   MsgBox Splash
End Function

Set Window.Onload = GetRef("GetRefTest")
</SCRIPT>

Requirements

Version 5

See Also

Function Statement | Set Statement | Sub Statement


Hex Function

Returns a string representing the hexadecimal value of a number.

Hex(number)

The number argument is any valid expression.

Remarks

If number is not already a whole number, it is rounded to the nearest whole number before being evaluated.

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

Dim MyHex
MyHex = Hex(5)   ' Returns 5.
MyHex = Hex(10)   ' Returns A.
MyHex = Hex(459)   ' Returns 1CB.

Requirements

Version 1

See Also

Oct Function


Hour Function

Returns a whole number between 0 and 23, inclusive, representing the hour of the day.

Hour(time)

The time argument is any expression that can represent a time. If time contains Null, Null is returned.

The following example uses the Hour function to obtain the hour from the current time:

Dim MyTime, MyHour
MyTime = Now
MyHour = Hour(MyTime) ' MyHour contains the number representing
                      ' the current hour.

Requirements

Version 1

See Also

Day Function | Minute Function | Now Function | Second Function | Time Function


InputBox Function

Displays a prompt in a dialog box, waits for the user to input text or click a button, and returns the contents of the text box.

InputBox(prompt[, title][, default][, xpos][, ypos][, helpfile, context])

Arguments

prompt
String expression displayed as the message in the dialog box. The maximum length of prompt is approximately 1024 characters, depending on the width of the characters used. If prompt consists of more than one line, you can separate the lines using a carriage return character (Chr(13)), a linefeed character (Chr(10)), or carriage 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.

Remarks

When both helpfile and context are supplied, a Help button is automatically added to the dialog box.

If the user clicks OK or presses ENTER, the InputBox function returns whatever is in the text box. If the user clicks Cancel, the function returns a zero-length string ("").

The following example uses the InputBox function to display an input box and assign the string to the variable Input:

Dim Input
Input = InputBox("Enter your name")
MsgBox ("You entered: " & Input)

Requirements

Version 1

See Also

MsgBox Function


InStr Function

Returns the position of the first occurrence of one string within another.

InStr([start, ]string1, string2[, compare])

Arguments

start
Optional. Numeric expression that sets the starting position for each search. If omitted, search begins at the first character position. If start contains Null, an error occurs. The start argument is required if compare is specified.
string1
Required. String expression being searched.
string2
Required. String expression searched for.
compare
Optional. Numeric value indicating the kind of comparison to use when evaluating substrings. See Settings section for values. If omitted, a binary comparison is performed.

Settings

The compare argument can have the following values:

Constant | Value | Description
vbBinaryCompare | 0 | Perform a binary comparison.
vbTextCompare | 1 | Perform a textual comparison.

Return Values

The InStr function returns the following values:

If | 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

Remarks

The following examples use InStr to search a string:

Dim SearchString, SearchChar, MyPos
SearchString ="XXpXXpXXPXXP"   ' String to search in.
SearchChar = "P"   ' Search for "P".
MyPos = Instr(4, SearchString, SearchChar, 1)   ' A textual comparison starting at position 4. Returns 6.
MyPos = Instr(1, SearchString, SearchChar, 0)   ' A binary comparison starting at position 1. Returns 9.
MyPos = Instr(SearchString, SearchChar)   ' Comparison is binary by default (last argument is omitted). Returns 9.
MyPos = Instr(1, SearchString, "W")   ' A binary comparison starting at position 1. Returns 0 ("W" is not found).
Note The InStrB function is used with byte data contained in a string. Instead of returning the character position of the first occurrence of one string within another, InStrB returns the byte position.

Requirements

Version 1

See Also

InStrRev Function


InStrRev Function

Returns the position of an occurrence of one string within another, from the end of string.

InStrRev(string1, string2[, start[, compare]])

Arguments

string1
Required. String expression being searched.
string2
Required. String expression being searched for.
start
Optional. Numeric expression that sets the starting position for each search. If omitted, -1 is used, which means that the search begins at the last character position. If start contains Null, an error occurs.
compare
Optional. Numeric value indicating the kind of comparison to use when evaluating substrings. If omitted, a binary comparison is performed. See Settings section for values.

Settings

The compare argument can have the following values:

Constant | Value | Description
vbBinaryCompare | 0 | Perform a binary comparison.
vbTextCompare | 1 | Perform a textual comparison.

Return Values

InStrRev returns the following values:

If | 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

Remarks

The following examples use the InStrRev function to search a string:

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 The syntax for the InStrRev function is not the same as the syntax for the InStr function.

Requirements

Version 2

See Also

InStr Function


Int, Fix Functions

Returns the integer portion of a number.

Int(number)
Fix(number)

The number argument can be any valid numeric expression. If number contains Null, Null is returned.

Remarks

Both Int and Fix remove the fractional part of number and return the resulting integer value.

The difference between Int and Fix is that if number is negative, Int returns the first negative integer less than or equal to number, whereas Fix returns the first negative integer greater than or equal to number. For example, Int converts -8.4 to -9, and Fix converts -8.4 to -8.

Fix(number) is equivalent to:

Sgn(number) * Int(Abs(number))

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

MyNumber = 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.

Requirements

Version 1

See Also

CInt Function | Round Function


IsArray Function

Returns a Boolean value indicating whether a variable is an array.

IsArray(varname)

The varname argument can be any variable.

Remarks

IsArray returns True if the variable is an array; otherwise, it returns False. IsArray is especially useful with variants containing arrays.

The following example uses the IsArray function to test whether MyVariable is an array:

Dim MyVariable
Dim MyArray(3)
MyArray(0) = "Sunday"
MyArray(1) = "Monday"
MyArray(2) = "Tuesday"
MyVariable = IsArray(MyArray) ' MyVariable contains "True".

Requirements

Version 1

See Also

IsDate Function | IsEmpty Function | IsNull Function | IsNumeric Function | IsObject Function | VarType Function


IsDate Function

Returns a Boolean value indicating whether an expression can be converted to a date.

IsDate(expression)

The expression argument can be any date expression or string expression recognizable as a date or time.

Remarks

IsDate returns True if the expression is a date or can be converted to a valid date; otherwise, it returns False. In Microsoft Windows, the range of valid dates is January 1, 100 A.D. through December 31, 9999 A.D.; the ranges vary among operating systems.

The following example uses the IsDate function to determine whether an expression can be converted to a date:

Dim MyDate, YourDate, NoDate, MyCheck
MyDate = "October 19, 1962": YourDate = #10/19/62#: NoDate = "Hello"
MyCheck = IsDate(MyDate)   ' Returns True.
MyCheck = IsDate(YourDate)   ' Returns True.
MyCheck = IsDate(NoDate)   ' Returns False.

Requirements

Version 1

See Also

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


IsEmpty Function

Returns a Boolean value indicating whether a variable has been initialized.

IsEmpty(expression)

The expression argument can be any expression. However, because IsEmpty is used to determine if individual variables are initialized, the expression argument is most often a single variable name.

Remarks

IsEmpty returns True if the variable is uninitialized, or is explicitly set to Empty; otherwise, it returns False. False is always returned if expression contains more than one variable.

The following example uses the IsEmpty function to determine whether a variable has been initialized:

Dim MyVar, MyCheck
MyCheck = IsEmpty(MyVar)   ' Returns True.
MyVar = Null   ' Assign Null.
MyCheck = IsEmpty(MyVar)   ' Returns False.
MyVar = Empty   ' Assign Empty.
MyCheck = IsEmpty(MyVar)   ' Returns True.

Requirements

Version 1

See Also

IsArray Function | IsDate Function | IsNull Function | IsNumeric Function | IsObject Function | VarType Function


IsNull Function

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

IsNull(expression)

The expression argument can be any expression.

Remarks

IsNull returns True if expression is Null, that is, it contains no valid data; otherwise, IsNull returns False. If expression consists of more than one variable, Null in any constituent variable causes True to be returned for the entire expression.

The Null value indicates that the variable contains no valid data. Null is not the same as Empty, which indicates that a variable has not yet been initialized. It is also not the same as a zero-length string (""), which is sometimes referred to as a null string.

Caution Use the IsNull function to determine whether an expression contains a Null value. Expressions that you might expect to evaluate to True under some circumstances, such as If Var = Null and If Var <> Null, are always False. This is because any expression containing a Null is itself Null, and therefore, False.

The following example uses the IsNull function to determine whether a variable contains a Null:

Dim MyVar, MyCheck
MyCheck = IsNull(MyVar)   ' Returns False.
MyVar = Null   ' Assign Null.
MyCheck = IsNull(MyVar)   ' Returns True.
MyVar = Empty   ' Assign Empty.
MyCheck = IsNull(MyVar)   ' Returns False.

Requirements

Version 1

See Also

IsArray Function | IsDate Function | IsEmpty Function | IsNumeric Function | IsObject Function | VarType Function


IsNumeric Function

Returns a Boolean value indicating whether an expression can be evaluated as a number.

IsNumeric(expression)

The expression argument can be any expression.

Remarks

IsNumeric returns True if the entire expression is recognized as a number; otherwise, it returns False. IsNumeric returns False if expression is a date expression.

The following example uses the IsNumeric function to determine whether a variable can be evaluated as a number:

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

Requirements

Version 1

See Also

IsArray Function | IsDate Function | IsEmpty Function | IsNull Function | IsObject Function | VarType Function


IsObject Function

Returns a Boolean value indicating whether an expression references a valid Automation object.

IsObject(expression)

The expression argument can be any expression.

Remarks

IsObject returns True if expression is a variable of Object subtype or a user-defined object; otherwise, it returns False.

The following example uses the IsObject function to determine if an identifier represents an object variable:

Dim MyInt, MyCheck, MyObject
Set MyObject = Me
MyCheck = IsObject(MyObject)   ' Returns True.
MyCheck = IsObject(MyInt)   ' Returns False.

Requirements

Version 1

See Also

IsArray Function | IsDate Function | IsEmpty Function | IsNull Function | IsNumeric Function | Set Statement | VarType Function


Join Function

Returns a string created by joining a number of substrings contained in an array.

Join(list[, delimiter])

Arguments

list
Required. One-dimensional array containing substrings to be joined.
delimiter
Optional. String character used to separate the substrings in the returned string. If omitted, the space character (" ") is used. If delimiter is a zero-length string, all items in the list are concatenated with no delimiters.

Remarks

The following example uses the Join function to join the substrings of MyArray:

Dim MyString
Dim MyArray(3)
MyArray(0) = "Mr."
MyArray(1) = "John "
MyArray(2) = "Doe "
MyArray(3) = "III"
MyString = Join(MyArray) ' MyString contains "Mr. John Doe III".

Requirements

Version 2

See Also

Split Function


LBound Function

Returns the smallest available subscript for the indicated dimension of an array.

LBound(arrayname[, dimension])

Arguments

arrayname
Name of the array variable; follows standard variable naming conventions.
dimension
Whole number indicating which dimension's lower bound is returned. Use 1 for the first dimension, 2 for the second, and so on. If dimension is omitted, 1 is assumed.

Remarks

The LBound function is used with the UBound function to determine the size of an array. Use the UBound function to find the upper limit of an array dimension.

The lower bound for any dimension is always 0.

Requirements

Version 1

See Also

Dim Statement | ReDim Statement | UBound Function


LCase Function

Returns a string that has been converted to lowercase.

LCase(string)

The string argument is any valid string expression. If string contains Null, Null is returned.

Remarks

Only uppercase letters are converted to lowercase; all lowercase letters and non-letter characters remain unchanged.

The following example uses the LCase function to convert uppercase letters to lowercase:

Dim MyString
Dim LCaseString
MyString = "VBSCript"
LCaseString = LCase(MyString)   ' LCaseString contains "vbscript".

Requirements

Version 1

See Also

UCase Function


Left Function

Returns a specified number of characters from the left side of a string.

Left(string, length)

Arguments

string
String expression from which the leftmost characters are returned. If string contains Null, Null is returned.
length
Numeric expression indicating how many characters to return. If 0, a zero-length string("") is returned. If greater than or equal to the number of characters in string, the entire string is returned.

Remarks

To determine the number of characters in string, use the Len function.

The following example uses the Left function to return the first three characters of MyString:

Dim MyString, LeftString
MyString = "VBSCript"
LeftString = Left(MyString, 3) ' LeftString contains "VBS".
Note The LeftB function is used with byte data contained in a string. Instead of specifying the number of characters to return, length specifies the number of bytes.

Requirements

Version 1

See Also

Len Function | Mid Function | Right Function


Len Function

Returns the number of characters in a string or the number of bytes required to store a variable.

Len(string | varname)

Arguments

string
Any valid string expression. If string contains Null, Null is returned.
varname
Any valid variable name. If varname contains Null, Null is returned.

Remarks

The following example uses the Len function to return the number of characters in a string:

Dim MyString
MyString = Len("VBSCRIPT") ' MyString contains 8.
Note The LenB function is used with byte data contained in a string. Instead of returning the number of characters in a string, LenB returns the number of bytes used to represent that string.

Requirements

Version 1

See Also

InStr Function


LoadPicture Function

Returns a picture object. Available only on 32-bit platforms.

LoadPicture(picturename)

The picturename argument is a string expression that indicates the name of the picture file to be loaded.

Remarks

Graphics formats recognized by LoadPicture include bitmap (.bmp) files, icon (.ico) files, run-length encoded (.rle) files, metafile (.wmf) files, enhanced metafiles (.emf), GIF (.gif) files, and JPEG (.jpg) files.

Requirements

Version 2


Log Function

Returns the natural logarithm of a number.

Log(number)

The number argument can be any valid numeric expression greater than 0.

Remarks

The natural logarithm is the logarithm to the base e. The constant e is approximately 2.718282.

You can calculate base-n logarithms for any number x by dividing the natural logarithm of x by the natural logarithm of n as follows:

Logn(x) = Log(x) / Log(n)

The following example illustrates a custom Function that calculates base-10 logarithms:

Function Log10(X)
   Log10 = Log(X) / Log(10)
End Function

Requirements

Version 1

See Also

Derived Math Functions | Exp Function


LTrim; RTrim; and Trim Functions

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

LTrim(string)
RTrim(string)
Trim(string)

The string argument is any valid string expression. If string contains Null, Null is returned.

Remarks

The following example uses the LTrim, RTrim, and Trim functions to trim leading spaces, trailing spaces, and both leading and trailing spaces, respectively:

Dim MyVar
MyVar = LTrim("   vbscript ")   ' MyVar contains "vbscript ".
MyVar = RTrim("   vbscript ")   ' MyVar contains "   vbscript".
MyVar = Trim("   vbscript ")   ' MyVar contains "vbscript".

Requirements

Version 1

See Also

Left Function | Right Function


Math Functions

Abs Function

Atn Function

Cos Function

Exp Function

Fix Function

Int Function

Log Function

Rnd Function

Sgn Function

Sin Function

Sqr Function

Tan Function

Derived Math Functions


Mid Function

Returns a specified number of characters from a string.

Mid(string, start[, length])

Arguments

string
String expression from which characters are returned. If string contains Null, Null is returned.
start
Character position in string at which the part to be taken begins. If start is greater than the number of characters in string, Mid returns a zero-length string ("").
length
Number of characters to return. If omitted or if there are fewer than length characters in the text (including the character at start), all characters from the start position to the end of the string are returned.

Remarks

To determine the number of characters in string, use the Len function.

The following example uses the Mid function to return six characters, beginning with the fourth character, in a string:

Dim MyVar
MyVar = Mid("VB Script is fun!", 4, 6) ' MyVar contains "Script".
Note The MidB function is used with byte data contained in a string. Instead of specifying the number of characters, the arguments specify numbers of bytes.

Requirements

Version 1

See Also

Left Function | Len Function | LTrim, RTrim, and Trim Functions | Right Function


Minute

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

Minute(time)

The time argument is any expression that can represent a time. If time contains Null, Null is returned.

Remarks

The following example uses the Minute function to return the minute of the hour:

Dim MyVar
MyVar = Minute(Now)

Requirements

Version 1

See Also

Day Function | Hour Function | Now Function | Second Function | Time Function


Month Function

Returns a whole number between 1 and 12, inclusive, representing the month of the year.

Month(date)

The date argument is any expression that can represent a date. If date contains Null, Null is returned.

Remarks

The following example uses the Month function to return the current month:

Dim MyVar
MyVar = Month(Now) ' MyVar contains the number corresponding to
                   ' the current month.

Requirements

Version 1

See Also

Date Function | Day Function | Now Function | Weekday Function | Year Function


MonthName Function

Returns a string indicating the specified month.

MonthName(month[, abbreviate])

Arguments

month
Required. The numeric designation of the month. For example, January is 1, February is 2, and so on.
abbreviate
Optional. Boolean value that indicates if the month name is to be abbreviated. If omitted, the default is False, which means that the month name is not abbreviated.

Remarks

The following example uses the MonthName function to return an abbreviated month name for a date expression:

Dim MyVar
MyVar = MonthName(10, True) ' MyVar contains "Oct".

Requirements

Version 2

See Also

WeekdayName Function


MsgBox Function

Displays a message in a dialog box, waits for the user to click a button, and returns a value indicating which button the user clicked.

MsgBox(prompt[, buttons][, title][, helpfile, context])

Arguments

prompt
String expression displayed as the message in the dialog box. The maximum length of prompt is approximately 1024 characters, depending on the width of the characters used. If prompt consists of more than one line, you can separate the lines using a carriage return character (Chr(13)), a linefeed character (Chr(10)), or carriage 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.

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.

Return Values

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

Remarks

When both helpfile and context are provided, the user can press F1 to view the Help topic corresponding to the context.

If the dialog box displays a Cancel button, pressing the ESC key has the same effect as clicking Cancel. If the dialog box contains a Help button, context-sensitive Help is provided for the dialog box. However, no value is returned until one of the other buttons is clicked.

When the MsgBox function is used with Microsoft Internet Explorer, the title of any dialog presented always contains "VBScript:" to differentiate it from standard system dialogs.

The following example uses the MsgBox function to display a message box and return a value describing which button was clicked:

Dim MyVar
MyVar = MsgBox ("Hello World!", 65, "MsgBox Example")
   ' MyVar contains either 1 or 2, depending on which button is clicked.

Requirements

Version 1

See Also

InputBox Function


Now Function

Visual Basic Scripting Edition

Now

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

Now

Remarks

The following example uses the Now function to return the current date and time:

Dim MyVar
MyVar = Now ' MyVar contains the current date and time.

Requirements

Version 1

See Also

Date Function | Day Function | Hour Function | Minute Function | Month Function | Second Function | Time Function | Weekday Function | Year Function


Oct

Returns a string representing the octal value of a number.

Oct(number)

The number argument is any valid expression.

Remarks

If number is not already a whole number, it is rounded to the nearest whole number before being evaluated.

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

Dim MyOct
MyOct = Oct(4)     ' Returns 4.
MyOct = Oct(8)     ' Returns 10.
MyOct = Oct(459)   ' Returns 713.

Requirements

Version 1

See Also

Hex Function


Replace Function

Returns a string in which a specified substring has been replaced with another substring a specified number of times.

Replace(expression, find, replacewith[, start[, count[, compare]]])

Arguments

expression
Required. String expression containing substring to replace.
find
Required. Substring being searched for.
replacewith
Required. Replacement substring.
start
Optional. Position within expression where substring search is to begin. If omitted, 1 is assumed. Must be used in conjunction with count.
count
Optional. Number of substring substitutions to perform. If omitted, the default value is -1, which means make all possible substitutions. Must be used in conjunction with start.
compare
Optional. Numeric value indicating the kind of comparison to use when evaluating substrings. See Settings section for values. If omitted, the default value is 0, which means perform a binary comparison.

Settings

The compare argument can have the following values:

Constant | Value | Description
vbBinaryCompare | 0 | Perform a binary comparison.
vbTextCompare | 1 | Perform a textual comparison.

Return Values

Replace returns the following values:

If | 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 occurences of find removed.
start > Len(expression) | Zero-length string.
count is 0 | Copy of expression.

Remarks

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

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

Dim MyString
MyString = Replace("XXpXXPXXp", "p", "Y")   ' A binary comparison starting at the beginning of the string. Returns "XXYXXPXXY".
MyString = Replace("XXpXXPXXp", "p", "Y",   ' A textual comparison starting at position 3. Returns "YXXYXXY". 3, -1, 1)

Requirements

Version 2

See Also

Filter Function


RGB Function

Returns a whole number representing an RGB color value.

RGB(red, green, blue)

Arguments

red
Required. Number in the range 0-255 representing the red component of the color.
green
Required. Number in the range 0-255 representing the green component of the color.
blue
Required. Number in the range 0-255 representing the blue component of the color.

Remarks

Application methods and properties that accept a color specification expect that specification to be a number representing an RGB color value. An RGB color value specifies the relative intensity of red, green, and blue to cause a specific color to be displayed.

The low-order byte contains the value for red, the middle byte contains the value for green, and the high-order byte contains the value for blue.

For applications that require the byte order to be reversed, the following function will provide the same information with the bytes reversed:

Function RevRGB(red, green, blue)
   RevRGB= CLng(blue + (green * 256) + (red * 65536))
End Function

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

Requirements

Version 2


Right Function

Returns a specified number of characters from the right side of a string.

Right(string, length)

Arguments

string
String expression from which the rightmost characters are returned. If string contains Null, Null is returned.
length
Numeric expression indicating how many characters to return. If 0, a zero-length string is returned. If greater than or equal to the number of characters in string, the entire string is returned.

Remarks

To determine the number of characters in string, use the Len function.

The following example uses the Right function to return a specified number of characters from the right side of a string:

Dim AnyString, MyStr
AnyString = "Hello World"      ' Define string.
MyStr = Right(AnyString, 1)    ' Returns "d".
MyStr = Right(AnyString, 6)    ' Returns " World".
MyStr = Right(AnyString, 20)   ' Returns "Hello World".
Note The RightB function is used with byte data contained in a string. Instead of specifying the number of characters to return, length specifies the number of bytes.

Requirements

Version 1

See Also

Left Function | Len Function | Mid Function


Rnd Function

Returns a random number.

Rnd[(number)]

The number argument can be any valid numeric expression.

Remarks

The Rnd function returns a value less than 1 but greater than or equal to 0. The value of number determines how Rnd generates a random number:

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

Int((upperbound - lowerbound + 1) * Rnd + lowerbound)

Here, upperbound is the highest number in the range, and lowerbound is the lowest number in the range.

Note To repeat sequences of random numbers, call Rnd with a negative argument immediately before using Randomize with a numeric argument. Using Randomize with the same value for number does not repeat the previous sequence.

Requirements

Version 1

See Also

Randomize Statement


Round Function

Returns a number rounded to a specified number of decimal places.

Round(expression[, numdecimalplaces])

Arguments

expression
Required. Numeric expression being rounded.
numdecimalplaces
Optional. Number indicating how many places to the right of the decimal are included in the rounding. If omitted, integers are returned by the Round function.

Remarks

The following example uses the Round function to round a number to two decimal places:

Dim MyVar, pi
pi = 3.14159
MyVar = Round(pi, 2) ' MyVar contains 3.14.

Requirements

Version 2

See Also

Int, Fix Functions


ScriptEngine Function

Returns a string representing the scripting language in use.

ScriptEngine

Return Values

The ScriptEngine function can return any of the following strings:

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

Remarks

The following example uses the ScriptEngine function to return a string describing the scripting language in use:

Function GetScriptEngineInfo
   Dim s
   s = ""   ' Build string with necessary info.
   s = ScriptEngine & " Version "
   s = s & ScriptEngineMajorVersion & "."
   s = s & ScriptEngineMinorVersion & "."
   s = s & ScriptEngineBuildVersion
   GetScriptEngineInfo = s   ' Return the results.
End Function

Requirements

Version 2

See Also

ScriptEngineBuildVersion Function | ScriptEngineMajorVersion Function | ScriptEngineMinorVersion Function


ScriptEngineBuildVersion Function

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

ScriptEngineBuildVersion

Remarks

The return value corresponds directly to the version information contained in the DLL for the scripting language in use.

The following example uses the ScriptEngineBuildVersion function to return the build version number of the scripting engine:

Function GetScriptEngineInfo
   Dim s
   s = ""   ' Build string with necessary info.
   s = ScriptEngine & " Version "
   s = s & ScriptEngineMajorVersion & "."
   s = s & ScriptEngineMinorVersion & "."
   s = s & ScriptEngineBuildVersion
   GetScriptEngineInfo = s   ' Return the results.
End Function

Requirements

Version 2

See Also

ScriptEngine Function | ScriptEngineMajorVersion Function | ScriptEngineMinorVersion Function


ScriptEngineMajorVersion Function

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

ScriptEngineMajorVersion

Remarks

The return value corresponds directly to the version information contained in the DLL for the scripting language in use.

The following example uses the ScriptEngineMajorVersion function to return the version number of the scripting engine:

Function GetScriptEngineInfo
   Dim s
   s = ""   ' Build string with necessary info.
   s = ScriptEngine & " Version "
   s = s & ScriptEngineMajorVersion & "."
   s = s & ScriptEngineMinorVersion & "."
   s = s & ScriptEngineBuildVersion
   GetScriptEngineInfo = s   ' Return the results.
End Function

Requirements

Version 2

See Also

ScriptEngine Function | ScriptEngineBuildVersion Function | ScriptEngineMinorVersion Function


ScriptEngineMinorVersion Function

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

ScriptEngineMinorVersion

Remarks

The return value corresponds directly to the version information contained in the DLL for the scripting language in use.

The following example uses the ScriptEngineMinorVersion function to return the minor version number of the scripting engine:

Function GetScriptEngineInfo
   Dim s
   s = ""   ' Build string with necessary info.
   s = ScriptEngine & " Version "
   s = s & ScriptEngineMajorVersion & "."
   s = s & ScriptEngineMinorVersion & "."
   s = s & ScriptEngineBuildVersion
   GetScriptEngineInfo = s   ' Return the results.
End Function

Requirements

Version 2

See Also

ScriptEngine Function | ScriptEngineBuildVersion Function | ScriptEngineMajorVersion Function


Second Function

Returns a whole number between 0 and 59, inclusive, representing the second of the minute.

Second(time)

The time argument is any expression that can represent a time. If time contains Null, Null is returned.

Remarks

The following example uses the Second function to return the current second:

Dim MySec
MySec = Second(Now)
   ' MySec contains the number representing the current second.

Requirements

Version 1

See Also

Day Function | Hour Function | Minute Function | Now Function | Time Function


SetLocale Function

Sets the global locale and returns the previous locale.

SetLocale(lcid)

The lcid argument can be any valid 32-bit value or short string that uniquely identifies a geographical locale. Recognized values can be found in the Locale ID chart.

Remarks

If lcid is zero, the locale is set to match the current system setting.

A locale is a set of user preference information related to the user's language, country/region, and cultural conventions. The locale determines such things as keyboard layout, alphabetic sort order, as well as date, time, number, and currency formats.

The following example illustrates the use of the SetLocale function. To use this code, paste the entire example between the <BODY> tags of a standard HTML page.

Enter Date in UK format: <input type="text" id="UKDate" size="20"><p>
Here's the US equivalent: <input type="text" id="USdate" size="20"><p>
<input type="button" value="Convert" id="button1"><p>
Enter a price in German: &nbsp; <input type="text" id="GermanNumber" size="20">
<p>
Here's the UK equivalent: <input type="text" id="USNumber" size="20"><p>
<input type="button" value="Convert" id="button2"><p>

<script language="vbscript">
Dim currentLocale
' Get the current locale
currentLocale = GetLocale

Sub Button1_onclick
  Dim original
  original = SetLocale("en-gb")
  mydate = CDate(UKDate.value)
  ' IE always sets the locale to US English so use the
  ' currentLocale variable to set the locale to US English
  original = SetLocale(currentLocale)
  USDate.value = FormatDateTime(mydate,vbShortDate)
End Sub

Sub button2_onclick
  Dim original
  original = SetLocale("de")
  myvalue = CCur(GermanNumber.value)
  original = SetLocale("en-gb")
  USNumber.value = FormatCurrency(myvalue)
End Sub

</script>

See Also

GetLocale Function | Locale ID (LCID) Chart


Sgn Function

Returns an integer indicating the sign of a number.

Sgn(number)

The number argument can be any valid numeric expression.

Return Values

The Sgn function has the following return values:

If number is | Sgn returns
Greater than zero | 1
Equal to zero | 0
Less than zero | -1

Remarks

The sign of the number argument determines the return value of the Sgn function.

The following example uses the Sgn function to determine the sign of a number:

Dim MyVar1, MyVar2, MyVar3, MySign
MyVar1 = 12: MyVar2 = -2.4: MyVar3 = 0
MySign = Sgn(MyVar1)   ' Returns 1.
MySign = Sgn(MyVar2)   ' Returns -1.
MySign = Sgn(MyVar3)   ' Returns 0.

Requirements

Version 1

See Also

Abs Function


Sin Function

Returns the sine of an angle.

Sin(number)

The number argument can be any valid numeric expression that expresses an angle in radians.

Remarks

The Sin function takes an angle and returns the ratio of two sides of a right triangle. The ratio is the length of the side opposite the angle divided by the length of the hypotenuse. The result lies in the range -1 to 1.

To convert degrees to radians, multiply degrees by pi /180. To convert radians to degrees, multiply radians by 180/pi.

The following example uses the Sin function to return the sine of an angle:

Dim MyAngle, MyCosecant
MyAngle = 1.3   ' Define angle in radians.
MyCosecant = 1 / Sin(MyAngle)   ' Calculate cosecant.

Requirements

Version 1

See Also

Atn Function | Cos Function | Derived Math Functions | Tan Function


Space Function

Returns a string consisting of the specified number of spaces.

Space(number)

The number argument is the number of spaces you want in the string.

Remarks

The following example uses the Space function to return a string consisting of a specified number of spaces:

Dim MyString
MyString = Space(10)   ' Returns a string with 10 spaces.
MyString = "Hello" & Space(10) & "World" ' Insert 10 spaces between two strings.

Requirements

Version 1

See Also

String Function


Split Function

Returns a zero-based, one-dimensional array containing a specified number of substrings.

Split(expression[, delimiter[, count[, compare]]])

Arguments

expression
Required. String expression containing substrings and delimiters. If expression is a zero-length string, Split returns an empty array, that is, an array with no elements and no data.
delimiter
Optional. String character used to identify substring limits. If omitted, the space character (" ") is assumed to be the delimiter. If delimiter is a zero-length string, a single-element array containing the entire expression string is returned.
count
Optional. Number of substrings to be returned; -1 indicates that all substrings are returned.
compare
Optional. Numeric value indicating the kind of comparison to use when evaluating substrings. See Settings section for values.

Settings

The compare argument can have the following values:

Constant | Value | Description
vbBinaryCompare | 0 | Perform a binary comparison.
vbTextCompare | 1 | Perform a textual comparison.

Remarks

The following example uses the Split function to return an array from a string. The function performs a textual comparison of the delimiter, and returns all of the substrings.

Dim MyString, MyArray, Msg
MyString = "VBScriptXisXfun!"
MyArray = Split(MyString, "x", -1, 1)
' MyArray(0) contains "VBScript".
' MyArray(1) contains "is".
' MyArray(2) contains "fun!".
Msg = MyArray(0) & " " & MyArray(1)
Msg = Msg   & " " & MyArray(2)
MsgBox Msg

Requirements

Version 2

See Also

Join Function


Sqr Function

Returns the square root of a number.

Sqr(number)

The number argument can be any valid numeric expression greater than or equal to 0.

Remarks

The following example uses the Sqr function to calculate the square root of a number:

Dim MySqr
MySqr = Sqr(4)   ' Returns 2.
MySqr = Sqr(23)   ' Returns 4.79583152331272.
MySqr = Sqr(0)   ' Returns 0.
MySqr = Sqr(-4)   ' Generates a run-time error.

Requirements

Version 1


StrComp Function

Returns a value indicating the result of a string comparison.

StrComp(string1, string2[, compare])

Arguments

string1
Required. Any valid string expression.
string2
Required. Any valid string expression.
compare
Optional. Numeric value indicating the kind of comparison to use when evaluating strings. If omitted, a binary comparison is performed. See Settings section for values.

Settings

The compare argument can have the following values:

Constant | Value | Description
vbBinaryCompare | 0 | Perform a binary comparison.
vbTextCompare | 1 | Perform a textual comparison.

Return Values

The StrComp function has the following return values:

If | 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

Remarks

The following example uses the StrComp function to return the results of a string comparison. If the third argument is 1, a textual comparison is performed; if the third argument is 0 or omitted, a binary comparison is performed.

Dim MyStr1, MyStr2, MyComp
MyStr1 = "ABCD": MyStr2 = "abcd"   ' Define variables.
MyComp = StrComp(MyStr1, MyStr2, 1)   ' Returns 0.
MyComp = StrComp(MyStr1, MyStr2, 0)   ' Returns -1.
MyComp = StrComp(MyStr2, MyStr1)   ' Returns 1.

Requirements

Version 1


String Function

Returns a repeating character string of the length specified.

String(number, character)

Arguments

number
Length of the returned string. If number contains Null, Null is returned.
character
Character code specifying the character or string expression whose first character is used to build the return string. If character contains Null, Null is returned.

Remarks

If you specify a number for character greater than 255, String converts the number to a valid character code using the formula:

character Mod 256

The following example uses the String function to return repeating character strings of the length specified:

Dim MyString
MyString = String(5, "*")   ' Returns "*****".
MyString = String(5, 42)   ' Returns "*****".
MyString = String(10, "ABC")   ' Returns "AAAAAAAAAA".

Requirements

Version 1

See Also

Space Function


StrReverse Function

Returns a string in which the character order of a specified string is reversed.

StrReverse(string1)

The string1 argument is the string whose characters are to be reversed. If string1 is a zero-length string (""), a zero-length string is returned. If string1 is Null, an error occurs.

Remarks

The following example uses the StrReverse function to return a string in reverse order:

Dim MyStr
MyStr = StrReverse("VBScript") ' MyStr contains "tpircSBV".

Requirements

Version 2


Tan Function

Returns the tangent of an angle.

Tan(number)

The number argument can be any valid numeric expression that expresses an angle in radians.

Remarks

Tan takes an angle and returns the ratio of two sides of a right triangle. The ratio is the length of the side opposite the angle divided by the length of the side adjacent to the angle.

To convert degrees to radians, multiply degrees by pi /180. To convert radians to degrees, multiply radians by 180/pi.

The following example uses the Tan function to return the tangent of an angle:

Dim MyAngle, MyCotangent
MyAngle = 1.3   ' Define angle in radians.
MyCotangent = 1 / Tan(MyAngle)   ' Calculate cotangent.

Requirements

Version 1

See Also

Atn Function | Cos Function | Derived Math Functions | Sin Function


Time Function

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

Time

Remarks

The following example uses the Time function to return the current system time:

Dim MyTime
MyTime = Time   ' Return current system time.

Requirements

Version 1

See Also

Date Function


Timer Function

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

Timer

Remarks

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

Function TimeIt(N)
   Dim StartTime, EndTime
   StartTime = Timer
   For I = 1 To N
   Next
   EndTime = Timer
   TimeIt = EndTime - StartTime
End Function

Requirements

Version 5

See Also

Randomize Statement


TimeSerial Function

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

TimeSerial(hour, minute, second)

Arguments

hour
Number between 0 (12:00 A.M.) and 23 (11:00 P.M.), inclusive, or a numeric expression.
minute
Any numeric expression.
second
Any numeric expression.

Remarks

To specify a time, such as 11:59:59, the range of numbers for each TimeSerial argument should be in the accepted range for the unit; that is, 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.

Dim MyTime1
MyTime1 = TimeSerial(12 - 6, -15, 0) ' Returns 5:45:00 AM.

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

Requirements

Version 1

See Also

DateSerial Function | DateValue Function | Hour Function | Minute Function | Now Function | Second Function | TimeValue Function


TimeValue

Returns a Variant of subtype Date containing the time.

TimeValue(time)

The time argument is usually a string expression representing a time from 0:00:00 (12:00:00 A.M.) to 23:59:59 (11:59:59 P.M.), inclusive. However, time can also be any expression that represents a time in that range. If time contains Null, Null is returned.

Remarks

You can enter valid times using a 12-hour or 24-hour clock. For example, "2:24PM" and "14:24" are both valid time arguments. If the time argument contains date information, TimeValue doesn't return the date information. However, if time includes invalid date information, an error occurs.

The following example uses the TimeValue function to convert a string to a time. You can also use date literals to directly assign a time to a Variant (for example, MyTime = #4:35:17 PM#).

Dim MyTime
MyTime = TimeValue("4:35:17 PM")   ' MyTime contains 4:35:17 PM.

Requirements

Version 1

See Also

DateSerial Function | DateValue Function | Hour Function | Minute Function | Now Function | Second Function | TimeSerial Function


TypeName Function

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

TypeName(varname)

The required varname argument can be any variable.

Return Values

The TypeName function has the following return values:

Value | 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 | Unitialized
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

Remarks

The following example uses the TypeName function to return information about a variable:

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

Requirements

Version 2

See Also

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


UBound Function

Returns the largest available subscript for the indicated dimension of an array.

UBound(arrayname[, dimension])

Arguments

arrayname
Required. Name of the array variable; follows standard variable naming conventions.
dimension
Optional. Whole number indicating which dimension's upper bound is returned. Use 1 for the first dimension, 2 for the second, and so on. If dimension is omitted, 1 is assumed.

Remarks

The UBound function is used with the LBound function to determine the size of an array. Use the LBound function to find the lower limit of an array dimension.

The lower bound for any dimension is always 0. As a result, UBound returns the following values for an array with these dimensions:

Dim A(100,3,4)
Statement | Return Value
UBound(A, 1) | 100
UBound(A, 2) | 3
UBound(A, 3) | 4

Requirements

Version 1

See Also

Dim Statement | LBound Function | ReDim Statement


UCase Function

Returns a string that has been converted to uppercase.

UCase(string)

The string argument is any valid string expression. If string contains Null, Null is returned.

Remarks

Only lowercase letters are converted to uppercase; all uppercase letters and non-letter characters remain unchanged.

The following example uses the UCase function to return an uppercase version of a string:

Dim MyWord
MyWord = UCase("Hello World")   ' Returns "HELLO WORLD".

Requirements

Version 1

See Also

LCase Function


VarType Function

Returns a value indicating the subtype of a variable.

VarType(varname)

The varname argument can be any variable.

Return Values

The VarType function returns the following values:

Constant | 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 These constants are specified by VBScript. As a result, the names can be used anywhere in your code in place of the actual values.

Remarks

The VarType function never returns the value for Array by itself. It is always added to some other value to indicate an array of a particular type. The value for Variant is only returned when it has been added to the value for Array to indicate that the argument to the VarType function is an array. For example, the value returned for an array of integers is calculated as 2 + 8192, or 8194. If an object has a default property, VarType (object) returns the type of its default property.

The following example uses the VarType function to determine the subtype of a variable.

Dim MyCheck
MyCheck = VarType(300)          ' Returns 2.
MyCheck = VarType(#10/19/62#)   ' Returns 7.
MyCheck = VarType("VBScript")   ' Returns 8.

Requirements

Version 1

See Also

IsArray Function | IsDate Function | IsEmpty Function | IsNull Function | IsNumeric Function | IsObject Function | TypeName Function


Weekday Function

Returns a whole number representing the day of the week.

Weekday(date, [firstdayofweek])

Arguments

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

Settings

The firstdayofweek argument has these settings:

Constant | Value | 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

Return Values

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

Remarks

The following example uses the Weekday function to obtain the day of the week from a specified date:

Dim MyDate, MyWeekDay
MyDate = #October 19, 1962#   ' Assign a date.
MyWeekDay = Weekday(MyDate)   ' MyWeekDay contains 6 because MyDate represents a Friday.

Requirements

Version 1

See Also

Date Function | Day Function | Month Function | Now Function | Year Function


WeekdayName Function

Returns a string indicating the specified day of the week.

WeekdayName(weekday, abbreviate, firstdayofweek)

Arguments

weekday
Required. The numeric designation for the day of the week. Numeric value of each day depends on setting of the firstdayofweek setting.
abbreviate
Optional. Boolean value that indicates if the weekday name is to be abbreviated. If omitted, the default is False, which means that the weekday name is not abbreviated.
firstdayofweek
Optional. Numeric value indicating the first day of the week. See Settings section for values.

Settings

The firstdayofweek argument can have the following values:

Constant | Value | 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

Remarks

The following example uses the WeekDayName function to return the specified day:

Dim MyDate
MyDate = WeekDayName(6, True)   ' MyDate contains Fri.

Requirements

Version 2

See Also

MonthName Function


Year Function

Returns a whole number representing the year.

Year(date)

The date argument is any expression that can represent a date. If date contains Null, Null is returned.

Remarks

The following example uses the Year function to obtain the year from a specified date:

Dim MyDate, MyYear
MyDate = #October 19, 1962#   ' Assign a date.
MyYear = Year(MyDate)         ' MyYear contains 1962.

Requirements

Version 1

See Also

Date Function | Day Function | Month Function | Now Function | Weekday Function


VBScript Keywords

Empty

False

Nothing

Null

True

Related Sections

VBScript Langauge Reference


Empty

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

See Also

Null


False

The False keyword has a value equal to 0.

See Also

True


Nothing

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

Set MyObject = Nothing

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

See Also

Dim Statement | Set Statement


Null

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

See Also

Empty


True

The True keyword has a value equal to -1.

See Also

False


Methods

In This Section

Clear Method

Execute Method

Raise Method

Replace Method

Test Method

Related Sections

VBScript Langauge Reference


Clear Method

Clears all property settings of the Err object.

object.Clear

The object is always the Err object.

Remarks

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

  • On Error Resume Next
  • Exit Sub
  • Exit Function

The following example illustrates use of the Clear method.

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

Requirements

Version 1

See Also

Description Property | Err Object | Number Property | OnError Statement | Raise Method | Source Property

Applies To: Err Object


Execute Method

Executes a regular expression search against a specified string.

object.Execute(string)

Arguments

object
Required. Always the name of a RegExp object.
string
Required. The text string upon which the regular expression is executed.

Remarks

The actual pattern for the regular expression search is set using the Pattern property of the RegExp object.

The Execute method returns a Matches collection containing a Match object for each match found in string. Execute returns an empty Matches collection if no match is found.

The following code illustrates the use of the Execute method.

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

Requirements

Version 5

See Also

Replace Method | Test Method

Applies To: RegExp Object


Raise Method

Generates a run-time error.

object.Raise(number, source, description, helpfile, helpcontext)

Arguments

object
Always the Err object.
number
A Long integer subtype that identifies the nature of the error. VBScript errors (both VBScript-defined and user-defined errors) are in the range 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.

Remarks

All the arguments are optional except number. If you use Raise, however, without specifying some arguments, and the property settings of the Err object contain values that have not been cleared, those values become the values for your error.

When setting the number property to your own error code in an Automation object, you add your error code number to the constant vbObjectError. For example, to generate the error number 1050, assign vbObjectError + 1050 to the number property.

The following example illustrates use of the Raise method.

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

Requirements

Version 1

See Also

Clear Method | Description Property | Err Object | Number Property Source Property

Applies To: Err Object


Replace Method

Replaces text found in a regular expression search.

object.Replace(string1, string2)

Arguments

object
Required. Always the name of a RegExp object.
string1
Required. String1 is the text string in which the text replacement is to occur.
string2
Required. String2 is the replacement text string.

Remarks

The actual pattern for the text being replaced is set using the Pattern property of the RegExp object.

The Replace method returns a copy of string1 with the text of RegExp.Pattern replaced with string2. If no match is found, a copy of string1 is returned unchanged.

The following code illustrates use of the Replace method.

Function ReplaceTest(patrn, replStr)
  Dim regEx, str1               ' Create variables.
  str1 = "The quick brown fox jumped over the lazy dog."
  Set regEx = New RegExp            ' Create regular expression.
  regEx.Pattern = patrn            ' Set pattern.
  regEx.IgnoreCase = True            ' Make case insensitive.
  ReplaceTest = regEx.Replace(str1, replStr)   ' Make replacement.
End Function

MsgBox(ReplaceTest("fox", "cat"))      ' Replace 'fox' with 'cat'.

In addition, the Replace method can replace subexpressions in the pattern. The following call to the function shown in the previous example swaps each pair of words in the original string:

MsgBox(ReplaceText("(\S+)(\s+)(\S+)", "$3$2$1"))   ' Swap pairs of words.

Requirements

Version 5

See Also

Execute Method | Test Method

Applies To: RegExp Object


Test Method

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

object.Test(string)

Arguments

object
Required. Always the name of a RegExp object.
string
Required. The text string upon which the regular expression is executed.

Remarks

The actual pattern for the regular expression search is set using the Pattern property of the RegExp object. The RegExp.Global property has no effect on the Test method.

The Test method returns True if a pattern match is found; False if no match is found.

The following code illustrates the use of the Test method.

Function RegExpTest(patrn, strng)
  Dim regEx, retVal            ' Create variable.
  Set regEx = New RegExp         ' Create regular expression.
  regEx.Pattern = patrn         ' Set pattern.
  regEx.IgnoreCase = False      ' Set case sensitivity.
  retVal = regEx.Test(strng)      ' Execute the search test.
  If retVal Then
    RegExpTest = "One or more matches were found."
  Else
    RegExpTest = "No match was found."
  End If
End Function
MsgBox(RegExpTest("is.", "IS1 is2 IS3 is4"))

Requirements

Version 5

See Also

Execute Method | Replace Method

Applies To: RegExp Object


Miscellaneous

In This Section

Character Set (0 - 127)

Character Set (128 - 255)

Locale ID (LCID) Chart

Related Sections

VBScript Langauge Reference


Character Set (0 - 127)

The following table lists 0 - 127.

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

Character Set (128 - 255)


Character Set (128 - 255)

The following table lists 128 - 255.

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

Character Set (0 - 127)


Locale ID (LCID) Chart

The following table lists Locale IDs (LCID).

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 | FYRO Macedonian | 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 - Bokmål | 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 S.A.R. | zh-hk | 0x0C04 | 3076 | Setsuana | tn | 0x0432 | 1074
Chinese – Macau S.A.R | 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 – The 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 – Carribbean | 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 | Sutu | sx | 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

In This Section

Class Object

Err Object

Matches Collection

Match Object

Regular Expression (RegExp) Object

SubMatches Collection

Related Sections

VBScript Langauge Reference


Class Object

The object created using the Class statement. Provides access to the events of the class.

Remarks

You cannot explicitly declare a variable to be of type Class. In the VBScript context, the term "class object" refers to any object defined using the VBScript Class statement.

Once you have created a class definition using the Class statement, you can create an instance of the class using the following form:

Dim X
Set X = New classname

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

Dim X as New classname

-or-

Dim X
X = New classname

-or-

Set X = New Scripting.FileSystemObject

Events

Class Object Events

Requirements

Version 5

See Also

Class Statement | Dim Statement | Set Statement


Class Object Events

The Class object provides access to the events of the class.

Events

Initialize Event

Terminate Event


Matches Collection

Collection of regular expression Match objects.

Remarks

A Matches collection contains individual Match objects, and can be only created using the Execute method of the RegExp object. The Matches collection's one property is read-only, as are the individual Match object properties.

When a regular expression is executed, zero or more Match objects can result. Each Match object provides access to the string found by the regular expression, the length of the string, and an index to where the match was found.

The following code illustrates how to obtain a Matches collection from a regular expression search and how to iterate the collection:

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

Requirements

Version 1

See Also

For Each...Next Statement | Match Object | RegExp Object | SubMatches Collection


Err Object

Contains information about run-time errors. Accepts the Raise and Clear methods for generating and clearing run-time errors.

Remarks

The Err object is an intrinsic object with global scope — there is no need to create an instance of it in your code. The properties of the Err object are set by the generator of an error — Visual Basic, an Automation object, or the VBScript programmer.

The default property of the Err object is Number. Err.Number contains an integer and can be used by an Automation object to return an SCODE.

When a run-time error occurs, the properties of the Err object are filled with information that uniquely identifies the error and information that can be used to handle it. To generate a run-time error in your code, use the Raise method.

The Err object's properties are reset to zero or zero-length strings ("") after an On Error Resume Next statement. The Clear method can be used to explicitly reset Err.

The following example illustrates use of the Err object:

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

Properties and Methods

Err Object Properties and Methods

Requirements

Version 1

See Also

On Error Statement


Err Object Properties and Methods

The Err object contains information about run-time errors.

Properties

Description Property

HelpContext Property

HelpFile Property

Number Property

Source Property

Methods

Clear Method

Raise Method


Match Object

Provides access to the read-only properties of a regular expression match.

Remarks

A Match object can be only created using the Execute method of the RegExp object, which actually returns a collection of Match objects. All Match object properties are read-only.

When a regular expression is executed, zero or more Match objects can result. Each Match object provides access to the string found by the regular expression, the length of the string, and an index to where the match was found.

The following code illustrates the use of the Match object:

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

Properties

Match Object Properties

Requirements

Version 5

See Also

Matches Collection | RegExp Object | SubMatches Colleciton


Match Object Properties

The Match object provides access to the read-only properties of a regular expression match.

Properties

FirstIndex Property

Length Property

Value Property


Regular Expression (RegExp) Object

Provides simple regular expression support.

Remarks

The following code illustrates the use of the RegExp object.

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

Properties and Methods

Regular Expression Object Properties and Methods

Requirements

Version 5

See Also

Match Object | Matches Collection


Regular Expression Object Properties and Methods

The Regular Expression object provides simple regular expression support.

Properties

Global Property

IgnoreCase Property

Pattern Property

Methods

Execute Method

Replace Method

Test Method


SubMatches Collection

Collection of regular expression submatch strings.

Remarks

A SubMatches collection contains individual submatch strings, and can only be created using the Execute method of the RegExp object. The SubMatches collection's properties are read-only

When a regular expression is executed, zero or more submatches can result when subexpressions are enclosed in capturing parentheses. Each item in the SubMatches collection is the string found and captured by the regular expression.

The following code illustrates how to obtain a SubMatches collection from a regular expression search and how to access its individual members:

Function SubMatchTest(inpStr)
  Dim oRe, oMatch, oMatches
  Set oRe = New RegExp
  ' Look for an e-mail address (not a perfect RegExp)
  oRe.Pattern = "(\w+)@(\w+)\.(\w+)"
  ' Get the Matches collection
  Set oMatches = oRe.Execute(inpStr)
  ' Get the first item in the Matches collection
  Set oMatch = oMatches(0)
  ' Create the results string.
  ' The Match object is the entire match - dragon@xyzzy.com
  retStr = "Email address is: " & oMatch & vbNewline
  ' Get the sub-matched parts of the address.
  retStr = retStr & "Email alias is: " & oMatch.SubMatches(0)  ' dragon
  retStr = retStr & vbNewline
  retStr = retStr & "Organization is: " & oMatch. SubMatches(1)' xyzzy
  SubMatchTest = retStr
End Function

MsgBox(SubMatchTest("Please send mail to dragon@xyzzy.com. Thanks!"))

Requirements

Version 5.5

See Also

For Each...Next Statement | Match Object | Matches Collection |RegExp Object


Operators

In This Section

Operator Precedence

Operator Summary

Arithmetic Operators

Comparison Operators

Concatenation Operators

Logical Operators

Related Sections

VBScript Langauge Reference


Operator Precedence

When several operations occur in an expression, each part is evaluated and resolved in a predetermined order called operator precedence. Parentheses can be used to override the order of precedence and force some parts of an expression to be evaluated before other parts. Operations within parentheses are always performed before those outside. Within parentheses, however, normal operator precedence is maintained.

When expressions contain operators from more than one category, arithmetic operators are evaluated first, comparison operators are evaluated next, and logical operators are evaluated last. Comparison operators all have equal precedence; that is, they are evaluated in the left-to-right order in which they appear. Arithmetic and logical operators are evaluated in the following order of precedence:

Arithmetic | Comparison | 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.

Requirements

Version 1

See Also

Is Operator | Operator Summary


Operator Summary

Arithmetic Operators
Operators used to perform mathematical calculations.

Assignment Operator
Operator used to assign a value to a property or variable.

Comparison Operators
Operators used to perform comparisons.

Concatenation Operators
Operators used to combine strings.

Logical Operators
Operators used to perform logical operations.

See Also

Operator Precedence


Addition Operator (+)

Sums two numbers.

result = expression1 + expression2

Arguments

result
Any numeric variable.
expression1
Any expression.
expression2
Any expression.

Remarks

Although you can also use the + operator to concatenate two character strings, you should use the & operator for concatenation to eliminate ambiguity and provide self-documenting code.

When you use the + operator, you may not be able to determine whether addition or string concatenation will occur.

The underlying subtype of the expressions determines the behavior of the + operator in the following way:

If | Then
Both expressions are numeric | Add.
Both expressions are strings | Concatenate.
One expression is numeric and the other is a string | Add.

If one or both expressions are Null expressions, result is Null. If both expressions are Empty, result is an Integer subtype. However, if only one expression is Empty, the other expression is returned unchanged as result.

Requirements

Version 1

See Also

& Operator | - Operator | Arithmetic Operators | Concatenation Operators | Operator Precedence | Operator Summary


And Operator

Performs a logical conjunction on two expressions.

result = expression1 And expression2

Arguments

result
Any numeric variable.
expression1
Any expression.
expression2
Any expression.

Remarks

If, and only if, both expressions evaluate to True, result is True. If either expression evaluates to False, result is False. The following table illustrates how result is determined:

If expression1 is | 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

Requirements

Version 1

See Also

Logical Operators | Not Operator | Operator Precedence | Operator Summary | Or Operator | Xor Operator


Assignment Operator (=)

Assigns a value to a variable or property.

variable = value

Arguments

variable
Any variable or any writable property.
value
Any numeric or string literal, constant, or expression.

Remarks

The name on the left side of the equal sign can be a simple scalar variable or an element of an array. Properties on the left side of the equal sign can only be those properties that are writable at run time.

Requirements

Version 1

See Also

Comparison Operators | Operator Precedence | Operator Summary | Set Statement


Concatenation Operator (&)

Forces string concatenation of two expressions.

result = expression1 & expression2

Arguments

result
Any variable.
expression1
Any expression.
expression2
Any expression.

Remarks

Whenever an expression is not a string, it is converted to a String subtype. If both expressions are Null, result is also Null. However, if only one expression is Null, that expression is treated as a zero-length string ("") when concatenated with the other expression. Any expression that is Empty is also treated as a zero-length string.

Requirements

Version 1

See Also

Concatenation Operators | Operator Precedence | Operator Summary


Division Operator (/)

Divides two numbers and returns a floating-point result.

result = number1/number2

Arguments

result
Any numeric variable.
number1
Any numeric expression.
number2
Any numeric expression.

Remarks

If one or both expressions are Null expressions, result is Null. Any expression that is Empty is treated as 0.

Requirements

Version 1

See Also

* Operator | \ Operator | Arithmetic Operators | Operator Precedence | Operator Summary


Eqv Operator

Performs a logical equivalence on two expressions.

result = expression1 Eqv expression2

Arguments

result
Any numeric variable.
expression1
Any expression.
expression2
Any expression.

Remarks

If either expression is Null, result is also Null. When neither expression is Null, result is determined according to the following table:

If expression1 is | 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

Requirements

Version 1

See Also

Imp Operator | Logical Operators | Operator Precedence | Operator Summary


Exponentiation Operator (^)

Raises a number to the power of an exponent.

result = number^exponent

Arguments

result
Any numeric variable.
number
Any numeric expression.
exponent
Any numeric expression.

Remarks

Number can be negative only if exponent is an integer value. When more than one exponentiation is performed in a single expression, the ^ operator is evaluated as it is encountered from left to right.

If either number or exponent is a Null expression, result is also Null.

Requirements

Version 1

See Also

Arithmetic Operators | Operator Precedence | Operator Summary


Imp Operator

Performs a logical implication on two expressions.

result = expression1 Imp expression2

Arguments

result
Any numeric variable.
expression1
Any expression.
expression2
Any expression.

Remarks

The following table illustrates how result is determined:

If expression1 is | 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

Requirements

Version 1

See Also

Eqv Operator | Logical Operators | Operator Precedence | Operator Summary


Integer Division Operator (\)

Divides two numbers and returns an integer result.

result = number1\number2

Arguments

result
Any numeric variable.
number1
Any numeric expression.
number2
Any numeric expression.

Remarks

Before division is performed, numeric expressions are rounded to Byte, Integer, or Long subtype expressions.

If any expression is Null, result is also Null. Any expression that is Empty is treated as 0.

Requirements

Version 1

See Also

* Operator | / Operator | Arithmetic Operators | Operator Precedence | Operator Summary


Is Operator

Compares two object reference variables.

result = object1 Is object2

Arguments

result
Any numeric variable.
object1
Any object name.
object2
Any object name.

Remarks

If object1 and object2 both refer to the same object, result is True; if they do not, result is False. Two variables can be made to refer to the same object in several ways.

In the following example, A has been set to refer to the same object as B:

Set A = B

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

Set A = C
Set B = C

Requirements

Version 1

See Also

Comparison Operators | Operator Precedence | Operator Summary


Mod Operator

Divides two numbers and returns only the remainder.

result = number1 Mod number2

Arguments

result
Any numeric variable.
number1
Any numeric expression.
number2
Any numeric expression.

Remarks

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

A = 19 Mod 6.7

If any expression is Null, result is also Null. Any expression that is Empty is treated as 0.

Requirements

Version 1

See Also

Arithmetic Operators | Operator Precedence | Operator Summary


Multiplication Operator (*)

Multiplies two numbers.

result = number1*number2

Arguments

result
Any numeric variable.
number1
Any numeric expression.
number2
Any numeric expression.

Remarks

If one or both expressions are Null expressions, result is Null. If an expression is Empty, it is treated as if it were 0.

Requirements

Version 1

See Also

\ Operator | Arithmetic Operators | Operator Precedence | Operator Summary


Not Operator

Performs logical negation on an expression.

result = Not expression

Arguments

result
Any numeric variable.
expression
Any expression.

Remarks

The following table illustrates how result is determined:

If expression is | Then result is
True | False
False | True
Null | Null

In addition, the Not operator inverts the bit values of any variable and sets the corresponding bit in result according to the following table:

Bit in expression | Bit in result
0 | 1
1 | 0

Requirements

Version 1

See Also

And Operator | Logical Operators | Operator Precedence | Operator Summary | Or Operator | Xor Operator


Or Operator

Performs a logical disjunction on two expressions.

result = expression1 Or expression2

Arguments

result
Any numeric variable.
expression1
Any expression.
expression2
Any expression.

Remarks

If either or both expressions evaluate to True, result is True. The following table illustrates how result is determined:

If expression1 is | 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

Requirements

Version 1

See Also

And Operator | Logical Operators | Not Operator | Operator Precedence | Operator Summary | Xor Operator


Subtraction Operator (-)

Finds the difference between two numbers or indicates the negative value of a numeric expression.

Syntax 1

result = number1-number2

Syntax 2

-number

Arguments

result
Any numeric variable.
number
Any numeric expression.
number1
Any numeric expression.
number2
Any numeric expression.

Remarks

In Syntax 1, the - operator is the arithmetic subtraction operator used to find the difference between two numbers. In Syntax 2, the - operator is used as the unary negation operator to indicate the negative value of an expression.

If one or both expressions are Null expressions, result is Null. If an expression is Empty, it is treated as if it were 0.

Requirements

Version 1

See Also

+ Operator | Arithmetic Operators | Operator Precedence | Operator Summary


Xor Operator

Performs a logical exclusion on two expressions.

result = expression1 Xor expression2

Arguments

result
Any numeric variable.
expression1
Any expression.
expression2
Any expression.

Remarks

If one, and only one, of the expressions evaluates to True, result is True. However, if either expression is Null, result is also Null. When neither expression is Null, result is determined according to the following table:

If expression1 is | 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

Requirements

Version 1

See Also

And Operator | Logical Operators | Not Operator | Operator Precedence | Operator Summary | Or Operator


Arithmetic Operators

^ Operator

* Operator

/ Operator

\ Operator

Mod Operator

+ Operator

- Operator

Concatenation Operators


Comparison Operators

Used to compare expressions.

result = expression1 comparisonoperator expression2
result = object1 Is object2

Parts

result
Any numeric variable.
expression
Any expression.
comparisonoperator
Any comparison operator.
object
Any object name.

Remarks

The Is operator has specific comparison functionality that differs from the operators in the following table. The following table contains a list of the comparison operators and the conditions that determine whether result is True, False, or Null:

Operator | Description | 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.

Requirements

Version 1

See Also

= Operator | Is Operator | Operator Precedence | Operator Summary


Concatenation Operators

& Operator

+ Operator


Logical Operators

And Operator

Not Operator

Or Operator

Xor Operator


Properties

In This Section

Description Property

FirstIndex Property

Global Property

HelpContext Property

HelpFile Property

IgnoreCase Property

Length Property

Number Property

Pattern Property

Source Property

Value Property

Related Sections

VBScript Langauge Reference


Description Property

Returns or sets a descriptive string associated with an error.

object.Description [= stringexpression]

Arguments

object
Always the Err object.
stringexpression
A string expression containing a description of the error.

Remarks

The Description property consists of a short description of the error. Use this property to alert the user to an error that you can't or don't want to handle. When generating a user-defined error, assign a short description of your error to this property. If Description isn't filled in, and the value of Number corresponds to a VBScript run-time error, the descriptive string associated with the error is returned.

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

Requirements

Version 1

See Also

Err Object | HelpContext Property | HelpFile Property | Number Property | Source Property

Applies To: Err Object


FirstIndex Property

Returns the position in a search string where a match occurs.

object.FirstIndex

The object argument is always a Match object.

Remarks

The FirstIndex property uses a zero-based offset from the beginning of the search string. In other words, the first character in the string is identified as character zero (0). The following code illustrates the use of the FirstIndex property.

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

Requirements

Version 5

See Also

Length Property | Value Property

Applies To: Match Object


Global Property

Sets or returns a Boolean value that indicates if a pattern should match all occurrences in an entire search string or just the first one.

object.Global [= True | False ]

The object argument is always a RegExp object. The value of the Global property is True if the search applies to the entire string, False if it does not. Default is False.

Remarks

The following code illustrates the use of the Global property (change the value assigned to Global property to see its effect):

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

Requirements

Version 5

See Also

IgnoreCase Property | Pattern Property

Applies To: RegExp Object


HelpContext Property

Sets or returns a context ID for a topic in a Help File.

object.HelpContext [= contextID]

Arguments

object
Required. Always the Err object.
contextID
Optional. A valid identifier for a Help topic within the Help file.

Remarks

If a Help file is specified in HelpFile, the HelpContext property is used to automatically display the Help topic identified. If both HelpFile and HelpContext are empty, the value of the Number property is checked. If it corresponds to a VBScript run-time error value, then the VBScript Help context ID for the error is used. If the Number property doesn't correspond to a VBScript error, the contents screen for the VBScript Help file is displayed.

The following example illustrates use of the HelpContext property:

On Error Resume Next
Dim Msg
Err.Clear
Err.Raise 6   ' Generate "Overflow" error.
Err.Helpfile = "yourHelp.hlp"
Err.HelpContext = yourContextID
If Err.Number <> 0 Then
   Msg = "Press F1 or Help to see " & Err.Helpfile & " topic for" & _
   " the following HelpContext: " & Err.HelpContext
   MsgBox Msg, , "error: " & Err.Description, Err.Helpfile, Err.HelpContext
End If

Requirements

Version 2

See Also

Description Property | HelpFile Property | Number Property | Source Property

Applies To: Err Object


HelpFile Property

Sets or returns a fully qualified path to a Help File.

object.HelpFile [= contextID]

Arguments

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

Remarks

If a Help file is specified in HelpFile, it is automatically called when the user clicks the Help button (or presses the F1 key) in the error message dialog box. If the HelpContext property contains a valid context ID for the specified file, that topic is automatically displayed. If no HelpFile is specified, the VBScript Help file is displayed.

On Error Resume Next
Dim Msg
Err.Clear
Err.Raise 6   ' Generate "Overflow" error.
Err.Helpfile = "yourHelp.hlp"
Err.HelpContext = yourContextID
If Err.Number <> 0 Then
   Msg = "Press F1 or Help to see " & Err.Helpfile & " topic for" & _
   " the following HelpContext: " & Err.HelpContext
   MsgBox Msg, , "error: " & Err.Description, Err.Helpfile, Err.HelpContext
End If

Requirements

Version 2

See Also

Description Property | HelpContext Property | Number Property | Source Property

Applies To: Err Object


IgnoreCase Property

Sets or returns a Boolean value that indicates if a pattern search is case-sensitive or not.

object.IgnoreCase [= True | False ]

The object argument is always a RegExp object. The value of the IgnoreCase property is False if the search is case-sensitive, True if it is not. Default is False.

Remarks

The following code illustrates the use of the IgnoreCase property (change the value assigned to IgnoreCase property to see its effect):

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

Requirements

Version 5

See Also

Global Property | Pattern Property

Applies To: RegExp Object


Length Property

Returns the length of a match found in a search string.

object.Length

The object argument is always a Match object.

Remarks

The following code illustrates the use of the Length property:

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

Requirements

Version 5

See Also

FirstIndex Property | Value Property

Applies To: Match Object


Number Property

Returns or sets a numeric value specifying an error. Number is the Err object's default property.

object.Number [= errornumber]

Arguments

object
Always the Err object.
errornumber
An integer representing a VBScript error number or an SCODE error value.

Remarks

When returning a user-defined error from an Automation object, set Err.Number by adding the number you selected as an error code to the constant vbObjectError.

The following code illustrates the use of the Number property.

On Error Resume Next
Err.Raise vbObjectError + 1, "SomeObject"    ' Raise Object Error #1.
MsgBox ("Error # " & CStr(Err.Number) & " " & Err.Description)
Err.Clear   ' Clear the error.

Requirements

Version 1

See Also

Description Property | HelpContext Property | HelpFile Property | Err Object | Source Property

Applies To: Err Object


Pattern Property

Sets or returns the regular expression pattern being searched for.

object.Pattern [= "searchstring"]

Arguments

object
Required. Always a RegExp object variable.
searchstring
Optional. Regular string expression being searched for. May include any of the regular expression characters defined in the table in the Settings section.

Settings

Special characters and sequences are used in writing patterns for regular expressions. The following table describes and gives an example of the characters and sequences that can be used.

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

Remarks

The following code illustrates the use of the Pattern property.

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

Requirements

Version 2

See Also

Global Property | IgnoreCase Property

Applies To: RegExp Object


Source Property

Returns or sets the name of the object or application that originally generated the error.

object.Source [= stringexpression]

Arguments

object
Always the Err object.
stringexpression
A string expression representing the application that generated the error.

Remarks

The Source property specifies a string expression that is usually the class name or programmatic ID of the object that caused the error. Use Source to provide your users with information when your code is unable to handle an error generated in an accessed object. For example, if you access Microsoft Excel and it generates a Division by zero error, Microsoft Excel sets Err.Number to its error code for that error and sets Source to Excel.Application. Note that if the error is generated in another object called by Microsoft Excel, Excel intercepts the error and sets Err.Number to its own code for Division by zero. However, it leaves the other Err object (including Source) as set by the object that generated the error.

Source always contains the name of the object that originally generated the error — your code can try to handle the error according to the error documentation of the object you accessed. If your error handler fails, you can use the Err object information to describe the error to your user, using Source and the other Err to inform the user which object originally caused the error, its description of the error, and so forth.

When generating an error from code, Source is your application's programmatic ID.

The following code illustrates use of the Source property.

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

Requirements

Version 1

See Also

Description Property | Err Object | HelpContext Property | HelpFile Property | Number Property | On Error Statement

Applies To: Err Object


Value Property

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

object.Value

The object argument is always a Match object.

Remarks

The following code illustrates the use of the Value property.

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

Requirements

Version 1

See Also

FirstIndex Property | Length Property

Applies To: Match Object


Statements

In This Section

Call Statement

Class Statement

Const Statement

Dim Statement

Do...Loop Statement

Erase Statement

Execute Statement

ExecuteGlobal Statement

Exit Statement

For Each...Next Statement

For...Next Statement

Function Statement

If...Then...Else Statement

On Error Statement

Option Explicit Statement

Private Statement

Property Get Statement

Property Let Statement

Property Set Statement

Public Statement

Randomize Statement

ReDim Statement

Rem Statement

Select Case Statement

Set Statement

Sub Statement

While...Wend Statement

With Statement

Related Sections

VBScript Langauge Reference


Call Statement

Transfers control to a Sub or Function procedure.

[Call] name [argumentlist]

Arguments

Call
Optional keyword. If specified, you must enclose argumentlist in parentheses. For example:

Call MyProc(0)

name
Required. Name of the procedure to call.
argumentlist
Optional. Comma-delimited list of variables, arrays, or expressions to pass to the procedure.

Remarks

You are not required to use the Call keyword when calling a procedure. However, if you use the Call keyword to call a procedure that requires arguments, argumentlist must be enclosed in parentheses. If you omit the Call keyword, you also must omit the parentheses around argumentlist. If you use either Call syntax to call any intrinsic or user-defined function, the function's return value is discarded.

Call MyFunction("Hello World")
Function MyFunction(text)
   MsgBox text
End Function

Requirements

Version 1


Class Statement

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

Class name
   statements
End Class

Arguments

name
Required. Name of the Class; follows standard variable naming conventions.
statements
Required. One or more statements that define the variables, properties, and methods of the Class.

Remarks

Within a Class block, members are declared as either Private or Public using the appropriate declaration statements. Anything declared as Private is visible only within the Class block. Anything declared as Public is visible within the Class block, as well as by code outside the Class block. Anything not explicitly declared as either Private or Public is Public by default. Procedures (either Sub or Function) declared Public within the class block become methods of the class. Public variables serve as properties of the class, as do properties explicitly declared using Property Get, Property Let, and Property Set. Default properties and methods for the class are specified in their declarations using the Default keyword. See the individual declaration statement topics for information on how this keyword is used.

Requirements

Version 5

See Also

Dim Statement | Function Statement | Private Statement | Property Get Statement | Property Let Statement | Property Set Statement | Public Statement | Set Statement | Sub Statement


Const Statement

Declares constants for use in place of literal values.

[Public | Private] Const constname = expression

Arguments

Public
Optional. Keyword used at script level to declare constants that are available to all procedures in all scripts. Not allowed in procedures.
Private
Optional. Keyword used at script level to declare constants that are available only within the script where the declaration is made. Not allowed in procedures.
constname
Required. Name of the constant; follows standard variable naming conventions.
expression
Required. Literal or other constant, or any combination that includes all arithmetic or logical operators except Is.

Remarks

Constants are public by default. Within procedures, constants are always private; their visibility can't be changed. Within a script, the default visibility of a script-level constant can be changed using the Private keyword.

To combine several constant declarations on the same line, separate each constant assignment with a comma. When constant declarations are combined in this way, the Public or Private keyword, if used, applies to all of them.

You can't use variables, user-defined functions, or intrinsic VBScript functions (such as Chr) in constant declarations. By definition, they can't be constants. You also can't create a constant from any expression that involves an operator, that is, only simple constants are allowed. Constants declared in a Sub or Function procedure are local to that procedure. A constant declared outside a procedure is defined throughout the script in which it is declared. You can use constants anywhere you can use an expression. The following code illustrates the use of the Const statement:

Const MyVar = 459   ' Constants are Public by default.
Private Const MyString = "HELP"   ' Declare Private constant.
Const MyStr = "Hello", MyNumber = 3.4567   ' Declare multiple constants on same line.
Note Constants can make your scripts self-documenting and easy to modify. Unlike variables, constants cannot be inadvertently changed while your script is running.

Requirements

Version 5

See Also

Dim Statement | Function Statement | Private Statement | Public Statement | Sub Statement


Dim Statement

Declares variables and allocates storage space.

Dim varname[([subscripts])][, varname[([subscripts])]] . . .

Arguments

varname
Name of the variable; follows standard variable naming conventions.
subscripts
Dimensions of an array variable; up to 60 multiple dimensions may be declared. The subscripts argument uses the following syntax:

upperbound [,upperbound] . . .

The lower bound of an array is always zero.

Remarks

Variables declared with Dim at the script level are available to all procedures within the script. At the procedure level, variables are available only within the procedure.

You can also use the Dim statement with empty parentheses to declare a dynamic array. After declaring a dynamic array, use the ReDim statement within a procedure to define the number of dimensions and elements in the array. If you try to redeclare a dimension for an array variable whose size was explicitly specified in a Dim statement, an error occurs.

Note When you use the Dim statement in a procedure, you generally put the Dim statement at the beginning of the procedure.

The following examples illustrate the use of the Dim statement:

Dim Names(9)       ' Declare an array with 10 elements.
Dim Names()        ' Declare a dynamic array.
Dim MyVar, MyNum   ' Declare two variables.

Requirements

Version 1

See Also

Private Statement | Public Statement | ReDim Statement | Set Statement


Do...Loop Statement

Repeats a block of statements while a condition is True or until a condition becomes True.

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

Or, you can use this syntax:

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

Arguments

condition
Numeric or string expression that is True or False. If condition is Null, condition is treated as False.
statements
One or more statements that are repeated while or until condition is True.

Remarks

The Exit Do can only be used within a Do...Loop control structure to provide an alternate way to exit a Do...Loop. Any number of Exit Do statements may be placed anywhere in the Do...Loop. Often used with the evaluation of some condition (for example, If...Then), Exit Do transfers control to the statement immediately following the Loop.

When used within nested Do...Loop statements, Exit Do transfers control to the loop that is nested one level above the loop where it occurs.

The following examples illustrate use of the Do...Loop statement:

Do Until DefResp = vbNo
   MyNum = Int (6 * Rnd + 1)   ' Generate a random integer between 1 and 6.
   DefResp = MsgBox (MyNum & " Do you want another number?", vbYesNo)
Loop

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

Requirements

Version 1

See Also

Exit Statement | For...Next Statement | While...Wend Statement


Erase Statement

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

Erase array

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

Remarks

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

Type of array | 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.

Dim NumArray(9)
Dim DynamicArray()
ReDim DynamicArray(9)   ' Allocate storage space.
Erase NumArray   ' Each element is reinitialized.
Erase DynamicArray   ' Free memory used by array.

Requirements

Version 1

See Also

Dim Statement | Nothing | ReDim Statement


Execute Statement

Executes one or more specified statements.

Execute statement

The required statement argument is a string expression containing one or more statements for execution. Include multiple statements in the statement argument, using colons or embedded line breaks to separate them.

Remarks

In VBScript, x = y can be interpreted two ways. The first is as an assignment statement, where the value of y is assigned to x. The second interpretation is as an expression that tests if x and y have the same value. If they do, result is True; if they are not, result is False. The Execute statement always uses the first interpretation, whereas the Eval method always uses the second.

Note In Microsoft® JScript™, no confusion exists between assignment and comparison, because the assignment operator (=) is different from the comparison operator(==).

The context in which the Execute statement is invoked determines what objects and variables are available to the code being run. In-scope objects and variables are available to code running in an Execute statement. However, it is important to understand that if you execute code that creates a procedure, that procedure does not inherit the scope of the procedure in which it occurred.

Like any procedure, the new procedure's scope is global, and it inherits everything in the global scope. Unlike any other procedure, its context is not global scope, so it can only be executed in the context of the procedure where the Execute statement occurred. However, if the same Execute statement is invoked outside of a procedure (i.e., in global scope), not only does it inherit everything in global scope, but it can also be called from anywhere, since its context is global. The following example illustrates this behavior:

Dim X   ' Declare X in global scope.
X = "Global"   ' Assign global X a value.
Sub Proc1   ' Declare procedure.
   Dim X   ' Declare X in local scope.
   X = "Local"   ' Assign local X a value.
            ' The Execute statement here creates a
            ' procedure that, when invoked, prints X.
            ' It print the global X because Proc2
            ' inherits everything in global scope.
   Execute "Sub Proc2: Print X: End Sub"
   Print Eval("X")   ' Print local X.
   Proc2   ' Invoke Proc2 in Proc1's scope.
End Sub
Proc2   ' This line causes an error since
        ' Proc2 is unavailable outside Proc1.
Proc1   ' Invoke Proc1.
   Execute "Sub Proc2: Print X: End Sub"
Proc2   ' This invocation succeeds because Proc2
        ' is now available globally.

The following example shows how the Execute statement can be rewritten so you don't have to enclose the entire procedure in the quotation marks:

S = "Sub Proc2" & vbCrLf
S = S & "   Print X" & vbCrLf
S = S & "End Sub"
Execute S

Requirements

Version 1

See Also

Eval Function | ExecuteGlobal Statement


ExecuteGlobal Statement

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

ExecuteGlobal statement

The required statement argument is a string expression containing one or more statements for execution. Include multiple statements in the statement argument, using colons or embedded line breaks to separate them.

Remarks

In VBScript, x = y can be interpreted two ways. The first is as an assignment statement, where the value of y is assigned to x. The second interpretation is as an expression that tests if x and y have the same value. If they do, result is True; if they are not, result is False. The ExecuteGlobal statement always uses the first interpretation, whereas the Eval method always uses the second.

Note In Microsoft® JScript™, no confusion exists between assignment and comparison, because the assignment operator (=) is different from the comparison operator.

All statements used with ExecuteGlobal are executed in the script's global namespace. This allows code to be added to the program so that any procedure can access it. For example, a VBScript Class statement can be executed at run time and functions can subsequently create new instances of the class.

Adding procedures and classes at runtime can be useful, but also introduces the possibility of overwriting existing global variable and functions at runtime. Because this can cause significant programming problems, care should be exercised when using the ExecuteGlobal statement. If you don't need access to a variable or function outside of a procedure, use the Execute statement that will only affect the namespace of the calling function.

The following example illustrates the use of the ExecuteGlobal statement:

Dim X         ' Declare X in global scope.
X = "Global"      ' Assign global X a value.
Sub Proc1   ' Declare procedure.
  Dim X      ' Declare X in local scope.
  X = "Local"   ' Assign local X a value.
         ' The Execute statement here creates a
         ' procedure that, when invoked, prints X.
         ' It print the global X because Proc2
         ' inherits everything in global scope.
  ExecuteGlobal "Sub Proc2: Print X: End Sub"
  Print Eval("X")   ' Print local X.
  Proc2      ' Invoke Proc2 in Global scope resulting
         ' in "Global" being printed.
End Sub
Proc2         ' This line causes an error since
         ' Proc2 is unavailable outside Proc1.
Proc1         ' Invoke Proc1.
  Execute "Sub Proc2: Print X: End Sub"
Proc2         ' This invocation succeeds because Proc2
         ' is now available globally.

The following example shows how the ExecuteGlobal statement can be rewritten so you don't have to enclose the entire procedure in the quotation marks:

S = "Sub Proc2" & vbCrLf
S = S & "  Print X" & vbCrLf
S = S & "End Sub"
ExecuteGlobal S

Requirements

Version 1


Exit Statement

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

Exit Do
Exit For
Exit Function
Exit Property
Exit Sub

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:

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

Requirements

Version 1

See Also

Do...Loop Statement | For Each...Next Statement | For...Next Statement | Function Statement | Sub Statement


For Each...Next Statement

Repeats a group of statements for each element in an array or collection.

For Each element In group
   [statements]
   [Exit For]
   [statements]
Next [element]

Arguments

element
Variable used to iterate through the elements of the collection or array. For collections, element can only be a Variant variable, a generic Object variable, or any specific Automation object variable. For arrays, element can only be a Variant variable.
group
Name of an object collection or array.
statements
One or more statements that are executed on each item in group.

Remarks

The For Each block is entered if there is at least one element in group. Once the loop has been entered, all the statements in the loop are executed for the first element in group. As long as there are more elements in group, the statements in the loop continue to execute for each element. When there are no more elements in group, the loop is exited and execution continues with the statement following the Next statement.

The Exit For can only be used within a For Each...Next or For...Next control structure to provide an alternate way to exit. Any number of Exit For statements may be placed anywhere in the loop. The Exit For is often used with the evaluation of some condition (for example, If...Then), and transfers control to the statement immediately following Next.

You can nest For Each...Next loops by placing one For Each...Next loop within another. However, each loop element must be unique.

Note If you omit element in a Next statement, execution continues as if you had included it. If a Next statement is encountered before it's corresponding For statement, an error occurs.

The following example illustrates use of the For Each...Next statement:

Function ShowFolderList(folderspec)
   Dim fso, f, f1, fc, s
   Set fso = CreateObject("Scripting.FileSystemObject")
   Set f = fso.GetFolder(folderspec)
   Set fc = f.Files
   For Each f1 in fc
      s = s & f1.name
      s = s & "<BR>"
   Next
   ShowFolderList = s
End Function

Requirements

Version 2

See Also

Do...Loop Statement | Exit Statement | For...Next Statement | While...Wend Statement


For...Next Statement

Repeats a group of statements a specified number of times.

For counter = start To end [Step step]
    [statements]
    [Exit For]
    [statements]
Next

Arguments

counter
Numeric variable used as a loop counter. The variable can't be an array element or an element of a user-defined type.
start
Initial value of counter.
end
Final value of counter.
step
Amount counter is changed each time through the loop. If not specified, step defaults to one.
statements
One or more statements between For and Next that are executed the specified number of times.

Remarks

The step argument can be either positive or negative. The value of the step argument determines loop processing as follows:

Value | 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 Changing the value of counter while inside a loop can make it more difficult to read and debug your code.

Exit For can only be used within a For Each...Next or For...Next control structure to provide an alternate way to exit. Any number of Exit For statements may be placed anywhere in the loop. Exit For is often used with the evaluation of some condition (for example, If...Then), and transfers control to the statement immediately following Next.

You can nest For...Next loops by placing one For...Next loop within another. Give each loop a unique variable name as its counter. The following construction is correct:

For I = 1 To 10
      For J = 1 To 10
            For K = 1 To 10
            . . .
            Next
      Next
Next

Requirements

Version 1

See Also

Do...Loop Statement | Exit Statement | For Each...Next Statement | While...Wend Statement


Function Statement

Declares the name, arguments, and code that form the body of a Function procedure.

[Public [Default] | Private] Function name [(arglist)]
   [statements]
   [name = expression]
   [Exit Function]
   [statements]
   [name = expression]
End Function

Arguments

Public
Indicates that the Function procedure is accessible to all other procedures in all scripts.
Default
Used only with the Public keyword in a Class block to indicate that the Function procedure is the default method for the class. An error occurs if more than one Default procedure is specified in a class.
Private
Indicates that the Function procedure is accessible only to other procedures in the script where it is declared or if the function is a member of a class, and that the Function procedure is accessible only to other procedures in that class.
name
Name of the Function; follows standard variable naming conventions.
arglist
List of variables representing arguments that are passed to the Function procedure when it is called. Commas separate multiple variables.
statements
Any group of statements to be executed within the body of the Function procedure.
expression
Return value of the Function.

The arglist argument has the following syntax and parts:

[ByVal | ByRef] varname[( )]

Arguments

ByVal
Indicates that the argument is passed by value.
ByRef
Indicates that the argument is passed by reference.
varname
Name of the variable representing the argument; follows standard variable naming conventions.

Remarks

If not explicitly specified using either Public or Private, Function procedures are public by default, that is, they are visible to all other procedures in your script. The value of local variables in a Function is not preserved between calls to the procedure.

You cannot define a Function procedure inside any other procedure (e.g. Sub or Property Get).

The Exit Function statement causes an immediate exit from a Function procedure. Program execution continues with the statement that follows the statement that called the Function procedure. Any number of Exit Function statements can appear anywhere in a Function procedure.

Like a Sub procedure, a Function procedure is a separate procedure that can take arguments, perform a series of statements, and change the values of its arguments. However, unlike a Sub procedure, you can use a Function procedure on the right side of an expression in the same way you use any intrinsic function, such as Sqr, Cos, or Chr, when you want to use the value returned by the function.

You call a Function procedure using the function name, followed by the argument list in parentheses, in an expression. See the Call statement for specific information on how to call Function procedures.

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

To return a value from a function, assign the value to the function name. Any number of such assignments can appear anywhere within the procedure. If no value is assigned to name, the procedure returns a default value: a numeric function returns 0 and a string function returns a zero-length string (""). A function that returns an object reference returns Nothing if no object reference is assigned to name (using Set) within the Function.

The following example shows how to assign a return value to a function named BinarySearch. In this case, False is assigned to the name to indicate that some value was not found.

Function BinarySearch(. . .)
      . . .
      ' Value not found. Return a value of False.
      If lower > upper Then
            BinarySearch = False
            Exit Function
      End If
      . . .
End Function

Variables used in Function procedures fall into two categories: those that are explicitly declared within the procedure and those that are not. Variables that are explicitly declared in a procedure (using Dim or the equivalent) are always local to the procedure. Variables that are used but not explicitly declared in a procedure are also local unless they are explicitly declared at some higher level outside the procedure.

Caution A procedure can use a variable that is not explicitly declared in the procedure, but a naming conflict can occur if anything you have defined at the script level has the same name. If your procedure refers to an undeclared variable that has the same name as another procedure, constant, or variable, it is assumed that your procedure is referring to that script-level name. To avoid this kind of conflict, use an Option Explicit statement to force explicit declaration of variables.
Caution VBScript may rearrange arithmetic expressions to increase internal efficiency. Avoid using a Function procedure in an arithmetic expression when the function changes the value of variables in the same expression.

Requirements

Version 1

See Also

Call Statement | Dim Statement | Exit Statement | Nothing | Set Statement | Sub Statement


If...Then...Else Statement

Conditionally executes a group of statements, depending on the value of an expression.

If condition Then statements [Else elsestatements ]

Or, you can use the block form syntax:

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

Arguments

condition
One or more of the following two types of expressions:

A numeric or string expression that evaluates to True or False. If condition is Null, condition is treated as False.

An expression of the form TypeOf objectname Is objecttype. The objectname is any object reference and objecttype is any valid object type. The expression is True if objectname is of the object type specified by objecttype; otherwise it is False.

statements
One or more statements separated by colons; executed if condition is True.
condition-n
Same as condition.
elseifstatements
One or more statements executed if the associated condition-n is True.
elsestatements
One or more statements executed if no previous condition or condition-n expression is True.

Remarks

You can use the single-line form (first syntax) for short, simple tests. However, the block form (second syntax) provides more structure and flexibility than the single-line form and is usually easier to read, maintain, and debug.

Note With the single-line syntax, it is possible to have multiple statements executed as the result of an If...Then decision, but they must all be on the same line and separated by colons, as in the following statement:
If A > 10 Then A = A + 1 : B = B + A : C = C + B

When executing a block If (second syntax), condition is tested. If condition is True, the statements following Then are executed. If condition is False, each ElseIf (if any) is evaluated in turn. When a True condition is found, the statements following the associated Then are executed. If none of the ElseIf statements are True (or there are no ElseIf clauses), the statements following Else are executed. After executing the statements following Then or Else, execution continues with the statement following End If.

The Else and ElseIf clauses are both optional. You can have as many ElseIf statements as you want in a block If, but none can appear after the Else clause. Block If statements can be nested; that is, contained within one another.

What follows the Then keyword is examined to determine whether or not a statement is a block If. If anything other than a comment appears after Then on the same line, the statement is treated as a single-line If statement.

A block If statement must be the first statement on a line. The block If must end with an End If statement.

Requirements

Version 1


On Error Statement

Enables or disables error-handling.

On Error Resume Next
On Error GoTo 0

Remarks

If you don't use an On Error Resume Next statement anywhere in your code, any run-time error that occurs can cause an error message to be displayed and code execution stopped. However, the host running the code determines the exact behavior. The host can sometimes opt to handle such errors differently. In some cases, the script debugger may be invoked at the point of the error. In still other cases, there may be no apparent indication that any error occurred because the host does not to notify the user. Again, this is purely a function of how the host handles any errors that occur.

Within any particular procedure, an error is not necessarily fatal as long as error-handling is enabled somewhere along the call stack. If local error-handling is not enabled in a procedure and an error occurs, control is passed back through the call stack until a procedure with error-handling enabled is found and the error is handled at that point. If no procedure in the call stack is found to have error-handling enabled, an error message is displayed at that point and execution stops or the host handles the error as appropriate.

On Error Resume Next causes execution to continue with the statement immediately following the statement that caused the run-time error, or with the statement immediately following the most recent call out of the procedure containing the On Error Resume Next statement. This allows execution to continue despite a run-time error. You can then build the error-handling routine inline within the procedure.

An On Error Resume Next statement becomes inactive when another procedure is called, so you should execute an On Error Resume Next statement in each called routine if you want inline error handling within that routine. When a procedure is exited, the error-handling capability reverts to whatever error-handling was in place before entering the exited procedure.

Use On Error GoTo 0 to disable error handling if you have previously enabled it using On Error Resume Next.

The following example illustrates use of the On Error Resume Next statement.

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

Requirements

Version 1

See Also

Err Object | Exit Statement


Option Explicit Statement

Forces explicit declaration of all variables in a script.

Option Explicit

Remarks

If used, the Option Explicit statement must appear in a script before any other statements.

When you use the Option Explicit statement, you must explicitly declare all variables using the Dim, Private, Public, or ReDim statements. If you attempt to use an undeclared variable name, an error occurs.

Tip Use Option Explicit to avoid incorrectly typing the name of an existing variable or to avoid confusion in code where the scope of the variable is not clear.

The following example illustrates use of the Option Explicit statement.

Option Explicit   ' Force explicit variable declaration.
Dim MyVar   ' Declare variable.
MyInt = 10   ' Undeclared variable generates error.
MyVar = 10   ' Declared variable does not generate error.

Requirements

Version 1


Private Statement

Declares private variables and allocates storage space. Declares, in a Class block, a private variable.

Private varname[([subscripts])][, varname[([subscripts])]] . . .

Arguments

varname
Name of the variable; follows standard variable naming conventions.
subscripts
Dimensions of an array variable; up to 60 multiple dimensions may be declared. The subscripts argument uses the following syntax:

upper [, upper] . . .

The lower bound of an array is always zero.

Remarks

Private statement variables are available only to the script in which they are declared.

A variable that refers to an object must be assigned an existing object using the Set statement before it can be used. Until it is assigned an object, the declared object variable is initialized as Empty.

You can also use the Private statement with empty parentheses to declare a dynamic array. After declaring a dynamic array, use the ReDim statement within a procedure to define the number of dimensions and elements in the array. If you try to redeclare a dimension for an array variable whose size was explicitly specified in a Private, Public, or Dim statement, an error occurs.

Note When you use the Private statement in a procedure, you generally put the Private statement at the beginning of the procedure.

The following example illustrates use of the Private statement.

Private MyNumber   ' Private Variant variable.
Private MyArray(9)   ' Private array variable.
   ' Multiple Private declarations of Variant variables.
Private MyNumber, MyVar, YourNumber

Requirements

Version 1

See Also

Dim Statement | Public Statement | ReDim Statement | Set Statement


Property Get Statement

Declares, in a Class block, the name, arguments, and code that form the body of a Property procedure that gets (returns) the value of a property.

[Public [Default] | Private] Property Get name [(arglist)]
   [statements]
   [[Set] name = expression]
   [Exit Property]
   [statements]
   [[Set] name = expression]
End Property

Arguments

Public
Indicates that the Property Get procedure is accessible to all other procedures in all scripts.
Default
Used only with the Public keyword to indicate that the property defined in the Property Get procedure is the default property for the class.
Private
Indicates that the Property Get procedure is accessible only to other procedures in the Class block where it's declared.
name
Name of the Property Get procedure; follows standard variable naming conventions, except that the name can be the same as a Property Let or Property Set procedure in the same Class block.
arglist
List of variables representing arguments that are passed to the Property Get procedure when it is called. Commas separate multiple arguments. The name of each argument in a Property Get procedure must be the same as the corresponding argument in a Property Let procedure (if one exists).
statements
Any group of statements to be executed within the body of the Property Get procedure.
Set
Keyword used when assigning an object as the return value of a Property Get procedure.
expression
Return value of the Property Get procedure.

Remarks

If not explicitly specified using either Public or Private, Property Get procedures are public by default, that is, they are visible to all other procedures in your script. The value of local variables in a Property Get procedure is not preserved between calls to the procedure.

You can't define a Property Get procedure inside any other procedure (e.g. Function or Property Let).

The Exit Property statement causes an immediate exit from a Property Get procedure. Program execution continues with the statement that follows the statement that called the Property Get procedure. Any number of Exit Property statements can appear anywhere in a Property Get procedure.

Like a Sub and Property Let procedure, a Property Get procedure is a separate procedure that can take arguments, perform a series of statements, and change the value of its arguments. However, unlike a Sub and Property Let, you can use a Property Get procedure on the right side of an expression in the same way you use a Function or property name when you want to return the value of a property.

Requirements

Version 5

See Also

Class Statement | Dim Statement | Exit Statement | Function Statement | Private Statement | Property Let Statement | Property Set Statement | Public Statement | Set Statement | Sub Statement


Property Let Statement

Declares, in a Class block, the name, arguments, and code that form the body of a Property procedure that assigns (sets) the value of a property.

[Public | Private] Property Let name ([arglist,] value)
   [statements]
   [Exit Property]
   [statements]
End Property

Arguments

Public
Indicates that the Property Let procedure is accessible to all other procedures in all scripts.
Private
Indicates that the Property Let procedure is accessible only to other procedures in the Class block where it's declared.
name
Name of the Property Let procedure; follows standard variable naming conventions, except that the name can be the same as a Property Get or Property Set procedure in the same Class block.
arglist
List of variables representing arguments that are passed to the Property Let procedure when it is called. Commas separate multiple arguments. The name of each argument in a Property Let procedure must be the same as the corresponding argument in a Property Get procedure. In addition, the Property Let procedure will always have one more argument than its corresponding Property Get procedure. That argument is the value being assigned to the property.
value
Variable to contain the value to be assigned to the property. When the procedure is called, this argument appears on the right side of the calling expression.
statements
Any group of statements to be executed within the body of the Property Let procedure.

Remarks

If not explicitly specified using either Public or Private, Property Let procedures are public by default, that is, they are visible to all other procedures in your script. The value of local variables in a Property Let procedure is not preserved between calls to the procedure.

You can't define a Property Let procedure inside any other procedure (e.g. Function or Property Get).

The Exit Property statement causes an immediate exit from a Property Let procedure. Program execution continues with the statement that follows the statement that called the Property Let procedure. Any number of Exit Property statements can appear anywhere in a Property Let procedure.

Note Every Property Let statement must define at least one argument for the procedure it defines. That argument (or the last argument if there is more than one) contains the actual value to be assigned to the property when the procedure defined by the Property Let statement is invoked. That argument is referred to as value in the preceding syntax.

Like a Function and Property Get procedure, a Property Let procedure is a separate procedure that can take arguments, perform a series of statements, and change the value of its arguments. However, unlike a Function and Property Get procedure, both of which return a value, you can only use a Property Let procedure on the left side of a property assignment expression.

Requirements

Version 5

See Also

Class Statement | Dim Statement | Exit Statement | Function Statement | Private Statement | Property Get Statement | Property Set Statement | Public Statement | Set Statement | Sub Statement


Property Set Statement

Declares, in a Class block, the name, arguments, and code that form the body of a Property procedure that sets a reference to an object.

[Public | Private] Property Set name([arglist,] reference)
   [statements]
   [Exit Property]
   [statements]
End Property

Arguments

Public
Indicates that the Property Set procedure is accessible to all other procedures in all scripts.
Private
Indicates that the Property Set procedure is accessible only to other procedures in the Class block where it's declared.
name
Name of the Property Set procedure; follows standard variable naming conventions, except that the name can be the same as a Property Get or Property Let procedure in the same Class block.
arglist
List of variables representing arguments that are passed to the Property Set procedure when it is called. Commas separate multiple arguments. In addition, the Property Set procedure will always have one more argument than its corresponding Property Get procedure. That argument is the object being assigned to the property.
reference
Variable containing the object reference used on the right side of the object reference assignment.
statements
Any group of statements to be executed within the body of the Property Set procedure.

Remarks

If not explicitly specified using either Public or Private, Property Set procedures are public by default, that is, they are visible to all other procedures in your script. The value of local variables in a Property Set procedure is not preserved between calls to the procedure.

You can't define a Property Set procedure inside any other procedure (e.g. Function or Property Let).

The Exit Property statement causes an immediate exit from a Property Set procedure. Program execution continues with the statement that follows the statement that called the Property Set procedure. Any number of Exit Property statements can appear anywhere in a Property Set procedure.

Note Every Property Set statement must define at least one argument for the procedure it defines. That argument (or the last argument if there is more than one) contains the actual object reference for the property when the procedure defined by the Property Set statement is invoked. That argument is referred to as reference in the preceding syntax.

Like a Function and Property Get procedure, a Property Set procedure is a separate procedure that can take arguments, perform a series of statements, and change the value of its arguments. However, unlike a Function and Property Get procedure, both of which return a value, you can only use a Property Set procedure on the left side of an object reference assignment (Set statement).

Requirements

Version 5

See Also

Class Statement | Dim Statement | Exit Statement | Function Statement | Private Statement | Property Get Statement | Property Let Statement | Public Statement | Set Statement | Sub Statement


Public Statement

Declares public variables and allocates storage space. Declares, in a Class block, a private variable.

Public varname[([subscripts])][, varname[([subscripts])]] . . .

Arguments

varname
Name of the variable; follows standard variable naming conventions.
subscripts
Dimensions of an array variable; up to 60 multiple dimensions may be declared. The subscripts argument uses the following syntax:

upper [, upper] . . .

The lower bound of an array is always zero.

Remarks

Public statement variables are available to all procedures in all scripts.

A variable that refers to an object must be assigned an existing object using the Set statement before it can be used. Until it is assigned an object, the declared object variable is initialized as Empty.

You can also use the Public statement with empty parentheses to declare a dynamic array. After declaring a dynamic array, use the ReDim statement within a procedure to define the number of dimensions and elements in the array. If you try to redeclare a dimension for an array variable whose size was explicitly specified in a Private, Public, or Dim statement, an error occurs.

The following example illustrates the use of the Public statement:

Public MyNumber   ' Public Variant variable.
Public MyArray(9)   ' Public array variable.
   ' Multiple Public declarations of Variant variables.
Public MyNumber, MyVar, YourNumber

Requirements

Version 1

See Also

Dim Statement | Private Statement | ReDim Statement | Set Statement


Randomize Statement

Initializes the random-number generator.

Randomize [number]

The number argument can be any valid numeric expression.

Remarks

Randomize uses number to initialize the Rnd function's random-number generator, giving it a new seed value. If you omit number, the value returned by the system timer is used as the new seed value.

If Randomize is not used, the Rnd function (with no arguments) uses the same number as a seed the first time it is called, and thereafter uses the last generated number as a seed value.

Note To repeat sequences of random numbers, call Rnd with a negative argument immediately before using Randomize with a numeric argument. Using Randomize with the same value for number does not repeat the previous sequence.

The following example illustrates use of the Randomize statement.

Dim MyValue, Response
Randomize   ' Initialize random-number generator.
Do Until Response = vbNo
   MyValue = Int((6 * Rnd) + 1)   ' Generate random value between 1 and 6.
   MsgBox MyValue
   Response = MsgBox ("Roll again? ", vbYesNo)
Loop

Requirements

Version 1

See Also

Rnd Function | Timer Function


ReDim Statement

Declares dynamic-array variables, and allocates or reallocates storage space at procedure level.

ReDim [Preserve] varname(subscripts) [, varname(subscripts)] . . .

Arguments

Preserve
Preserves the data in an existing array when you change the size of the last dimension.
varname
Name of the variable; follows standard variable naming conventions.
subscripts
Dimensions of an array variable; up to 60 multiple dimensions may be declared. The subscripts argument uses the following syntax:

upper [,upper] . . .

The lower bound of an array is always zero.

Remarks

The ReDim statement is used to size or resize a dynamic array that has already been formally declared using a Private, Public, or Dim statement with empty parentheses (without dimension subscripts). You can use the ReDim statement repeatedly to change the number of elements and dimensions in an array.

If you use the Preserve keyword, you can resize only the last array dimension, and you can't change the number of dimensions at all. For example, if your array has only one dimension, you can resize that dimension because it is the last and only dimension. However, if your array has two or more dimensions, you can change the size of only the last dimension and still preserve the contents of the array.

The following example shows how you can increase the size of the last dimension of a dynamic array without erasing any existing data contained in the array.

ReDim X(10, 10, 10)
. . .
ReDim Preserve X(10, 10, 15)
Caution If you make an array smaller than it was originally, data in the eliminated elements is lost.

When variables are initialized, a numeric variable is initialized to 0 and a string variable is initialized to a zero-length string (""). A variable that refers to an object must be assigned an existing object using the Set statement before it can be used. Until it is assigned an object, the declared object variable has the special value Nothing.

Requirements

Version 1

See Also

Dim Statement | Set Statement


Rem Statement

Includes explanatory remarks in a program.

Rem comment

-or-

' comment

The comment argument is the text of any comment you want to include. After the Rem keyword, a space is required before comment.

Remarks

As shown in the syntax section, you can use an apostrophe (') instead of the Rem keyword. If the Rem keyword follows other statements on a line, it must be separated from the statements by a colon. However, when you use an apostrophe, the colon is not required after other statements.

The following example illustrates the use of the Rem statement.

Dim MyStr1, MyStr2
MyStr1 = "Hello" : Rem Comment after a statement separated by a colon.
MyStr2 = "Goodbye" ' This is also a comment; no colon is needed.
Rem Comment on a line with no code; no colon is needed.

Requirements

Version 1


Select Case Statement

Executes one of several groups of statements, depending on the value of an expression.

Select Case testexpression
   [Case expressionlist-n
      [statements-n]] . . .
   [Case Else expressionlist-n
      [elsestatements-n]]
End Select

Arguments

testexpression
Any numeric or string expression.
expressionlist-n
Required if Case appears. Delimited list of one or more expressions.
statements-n
One or more statements executed if testexpression matches any part of expressionlist-n.
elsestatements-n
One or more statements executed if testexpression doesn't match any of the Case clauses.

Remarks

If testexpression matches any Case expressionlist expression, the statements following that Case clause are executed up to the next Case clause, or for the last clause, up to End Select. Control then passes to the statement following End Select. If testexpression matches an expressionlist expression in more than one Case clause, only the statements following the first match are executed.

The Case Else clause is used to indicate the elsestatements to be executed if no match is found between the testexpression and an expressionlist in any of the other Case selections. Although not required, it is a good idea to have a Case Else statement in your Select Case block to handle unforeseen testexpression values. If no Case expressionlist matches testexpression and there is no Case Else statement, execution continues at the statement following End Select.

Select Case statements can be nested. Each nested Select Case statement must have a matching End Select statement.

The following example illustrates the use of the Select Case statement.

Dim Color, MyVar
Sub ChangeBackground (Color)
   MyVar = lcase (Color)
   Select Case MyVar
      Case "red"     document.bgColor = "red"
      Case "green"   document.bgColor = "green"
      Case "blue"    document.bgColor = "blue"
      Case Else      MsgBox "pick another color"
   End Select
End Sub

Requirements

Version 1

See Also

If...Then...Else Statement


Set Statement

Assigns an object reference to a variable or property, or associates a procedure reference with an event.

Set objectvar = {objectexpression | New classname | Nothing}

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

Remarks

To be valid, objectvar must be an object type consistent with the object being assigned to it.

The Dim, Private, Public, or ReDim statements only declare a variable that refers to an object. No actual object is referred to until you use the Set statement to assign a specific object.

Generally, when you use Set to assign an object reference to a variable, no copy of the object is created for that variable. Instead, a reference to the object is created. More than one object variable can refer to the same object. Because these variables are references to (rather than copies of) the object, any change in the object is reflected in all variables that refer to it.

Function ShowFreeSpace(drvPath)
   Dim fso, d, s
   Set fso = CreateObject("Scripting.FileSystemObject")
   Set d = fso.GetDrive(fso.GetDriveName(drvPath))
   s = "Drive " & UCase(drvPath) & " - "
   s = s & d.VolumeName  & "<BR>"
   s = s & "Free Space: " & FormatNumber(d.FreeSpace/1024, 0)
   s = s & " Kbytes"
   ShowFreeSpace = s
End Function

Using the New keyword allows you to concurrently create an instance of a class and assign it to an object reference variable. The variable to which the instance of the class is being assigned must already have been declared with the Dim (or equivalent) statement.

Refer to the documentation for the GetRef function for information on using Set to associate a procedure with an event.

Requirements

Version 1

See Also

= Operator | Dim Statement | GetRef Function | ReDim Statement


Sub Statement

Declares the name, arguments, and code that form the body of a Sub procedure.

[Public [Default] | Private] Sub name [(arglist)]
   [statements]
   [Exit Sub]
   [statements]
End Sub

Arguments

Public
Indicates that the Sub procedure is accessible to all other procedures in all scripts.
Default
Used only with the Public keyword in a Class block to indicate that the Sub procedure is the default method for the class. An error occurs if more than one Default procedure is specified in a class.
Private
Indicates that the Sub procedure is accessible only to other procedures in the script where it is declared.
name
Name of the Sub; follows standard variable naming conventions.
arglist
List of variables representing arguments that are passed to the Sub procedure when it is called. Commas separate multiple variables.
statements
Any group of statements to be executed within the body of the Sub procedure.

The arglist argument has the following syntax and parts:

[ByVal | ByRef] varname[( )]

Arguments

ByVal
Indicates that the argument is passed by value.
ByRef
Indicates that the argument is passed by reference.
varname
Name of the variable representing the argument; follows standard variable naming conventions.

Remarks

If not explicitly specified using either Public or Private, Sub procedures are public by default, that is, they are visible to all other procedures in your script. The value of local variables in a Sub procedure is not preserved between calls to the procedure.

You can't define a Sub procedure inside any other procedure (e.g. Function or Property Get).

The Exit Sub statement causes an immediate exit from a Sub procedure. Program execution continues with the statement that follows the statement that called the Sub procedure. Any number of Exit Sub statements can appear anywhere in a Sub procedure.

Like a Function procedure, a Sub procedure is a separate procedure that can take arguments, perform a series of statements, and change the value of its arguments. However, unlike a Function procedure, which returns a value, a Sub procedure can't be used in an expression.

You call a Sub procedure using the procedure name followed by the argument list. See the Call statement for specific information on how to call Sub procedures.

Caution 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 A procedure can use a variable that is not explicitly declared in the procedure, but a naming conflict can occur if anything you have defined at the script level has the same name. If your procedure refers to an undeclared variable that has the same name as another procedure, constant or variable, it is assumed that your procedure is referring to that script-level name. To avoid this kind of conflict, use an Option Explicit statement to force explicit declaration of variables.

Requirements

Version 1

See Also

Call Statement | Dim Statement | Exit Statement | Function Statement


While...Wend Statement

Executes a series of statements as long as a given condition is True.

While condition
   Version [statements]
Wend

Arguments

condition
Numeric or string expression that evaluates to True or False. If condition is Null, condition is treated as False.
statements
One or more statements executed while condition is True.

Remarks

If condition is True, all statements in statements are executed until the Wend statement is encountered. Control then returns to the While statement and condition is again checked. If condition is still True, the process is repeated. If it is not True, execution resumes with the statement following the Wend statement.

While...Wend loops can be nested to any level. Each Wend matches the most recent While.

Note The Do...Loop statement provides a more structured and flexible way to perform looping.

The following example illustrates use of the While...Wend statement:

Dim Counter
Counter = 0   ' Initialize variable.
While Counter < 20   ' Test value of Counter.
   Counter = Counter + 1   ' Increment Counter.
   Alert Counter
Wend   ' End While loop when Counter > 19.

Requirements

Version 1

See Also

Do...Loop Statement


With Statement

Executes a series of statements on a single object.

With object
   statements
End With

Arguments

object
Required. Name of an object or a function that returns an object.
statements
Required. One or more statements to be executed on object.

Remarks

The With statement allows you to perform a series of statements on a specified object without requalifying the name of the object. For example, to change a number of different properties on a single object, place the property assignment statements within the With control structure, referring to the object once instead of referring to it with each property assignment. The following example illustrates use of the With statement to assign values to several properties of the same object.

With MyLabel
   .Height = 2000
   .Width = 2000
   .Caption = "This is MyLabel"
End With

While property manipulation is an important aspect of With functionality, it is not the only use. Any legal code can be used within a With block.

Note Once a With block is entered, object can't be changed. As a result, you can't use a single With statement to affect a number of different objects.

You can nest With statements by placing one With block within another. However, because members of outer With blocks are masked within the inner With blocks, you must provide a fully qualified object reference in an inner With block to any member of an object in an outer With block.

Important Do not jump into or out of With blocks. If statements in a With block are executed, but either the With or End With statement is not executed, you may get errors or unpredictable behavior.

Requirements

Version 1

See Also

Set Statement


FileSystemObject

In This Section

Scripting Run-Time Reference
List of elements that make up Scripting Run-Time Reference.
FileSystemObject Basics
A guide to the fundamentals of the FileSystemObject.


Dictionary Object

Object that stores data key, item pairs.

Remarks

A Dictionary object is the equivalent of a PERL associative array. Items can be any form of data, and are stored in the array. Each item is associated with a unique key. The key is used to retrieve an individual item and is usually a integer or a string, but can be anything except an array.

The following code illustrates how to create a Dictionary object:

[JScript]
var y = new ActiveXObject("Scripting.Dictionary");
y.add ("a", "test");
if (y.Exists("a"))
   document.write("true");
...
[VBScript]
Dim d   ' Create a variable.
Set d = CreateObject("Scripting.Dictionary")
d.Add "a", "Athens"   ' Add some keys and items.
d.Add "b", "Belgrade"
d.Add "c", "Cairo"
...

Methods

Add Method (Dictionary) | Exists Method | Items Method | Keys Method | Remove Method | RemoveAll Method

Properties

Count Property | Item Property | Key Property

See Also

FileSystemObject Object | TextStream Object


Count Property

Returns the number of items in a collection or Dictionary object. Read-only.

object.Count

The object is always the name of one of the items in the Applies To list.

Remarks

The following code illustrates use of the Count property:

[JScript]
function CountDemo()
{
   var a, d, i, s;                 // Create some variables.
   d = new ActiveXObject("Scripting.Dictionary");
   d.Add ("a", "Athens");          // Add some keys and items.
   d.Add ("b", "Belgrade");
   d.Add ("c", "Cairo");
   a = (new VBArray(d.Keys()));    // Get the keys.
   s = "";
   for (i = 0; i < d.Count; i++)   //Iterate the dictionary.
   {
      s += a.getItem(i) + " - " + d(a.getItem(i)) + "<br>";
   }
   return(s);                      // Return the results.
}
[VBScript]
Function ShowKeys
   Dim a, d, i, s   ' Create some variables.
   Set d = CreateObject("Scripting.Dictionary")
   d.Add "a", "Athens"   ' Add some keys and items.
   d.Add "b", "Belgrade"
   d.Add "c", "Cairo"
   a = d.Keys   ' Get the keys.
   For i = 0 To d.Count -1 ' Iterate the array.
      s = s & a(i) & "<BR>" ' Create return string.
   Next
   ShowKeys = s
End Function

See Also

CompareMode Property | Item Property | Key Property

Applies To: Dictionary Object | Drives Collection | Files Collection | Folders Collection


Item Property

Sets or returns an item for a specified key in a Dictionary object. For collections, returns an item based on the specified key. Read/write.

object.Item(key)[ = newitem]

Arguments

object
Required. Always the name of a collection or Dictionary object.
key
Required. Key associated with the item being retrieved or added.
newitem
Optional. Used for Dictionary object only; no application for collections. If provided, newitem is the new value associated with the specified key.

Remarks

If key is not found when changing an item, a new key is created with the specified newitem. If key is not found when attempting to return an existing item, a new key is created and its corresponding item is left empty.

The following example illustrates the use of the Item property.

[JScript]
function DicTest(keyword)
{
   var a, d;
   d = new ActiveXObject("Scripting.Dictionary");
   d.Add("a", "Athens");
   d.Add("b", "Belgrade");
   d.Add("c", "Cairo");
   a = d.Item(keyword);
   return(a);
}
[VBScript]
Function ItemDemo
   Dim d   ' Create some variables.
   Set d = CreateObject("Scripting.Dictionary")
   d.Add "a", "Athens"   ' Add some keys and items.
   d.Add "b", "Belgrade"
   d.Add "c", "Cairo"
   ItemDemo = d.Item("c")   ' Get the item.
End Function

See Also

CompareMode Property | Count Property | Key Property

Applies To: Dictionary Object | Drives Collection | Files Collection | Folders Collection


Key Property

Sets a key in a Dictionary object.

object.Key(key) = newkey

Arguments

object
Required. Always the name of a Dictionary object.
key
Required. Key value being changed.
newkey
Required. New value that replaces the specified key.

Remarks

If key is not found when changing a key, a new key is created and its associated item is left empty.

The following example illustrates the use of the Key property:

[JScript]
var d;
d = new ActiveXObject("Scripting.Dictionary");

function AddStuff()
{
   var a;
   d.Add("a", "Athens");
   d.Add("b", "Belgrade");
   d.Add("c", "Cairo");
}

function ChangeKey(oldkey, newkey)
{
   var s;
   d.Key("c") = "Ca";
   s = "Key " + oldkey + " changed to " + newkey;
   return(s);
}
[VBScript]
Function DicDemo
   Dim d   ' Create some variables.
   Set d = CreateObject("Scripting.Dictionary")
   d.Add "a", "Athens"   ' Add some keys and items.
   d.Add "b", "Belgrade"
   d.Add "c", "Cairo"
   d.Key("c") = "d"   ' Set key for "c" to "d".
   DicDemo = d.Item("d")   ' Return associate item.
End Function

See Also

CompareMode Property | Count Property | Item Property

Applies To: Dictionary Object


Add Method (Dictionary)

Adds a key and item pair to a Dictionary object.

object.Add (key, item)

Arguments

object
Required. Always the name of a Dictionary object.
key
Required. The key associated with the item being added.
item
Required. The item associated with the key being added.

Remarks

An error occurs if the key already exists.

The following example illustrates the use of the Add method.

[JScript]
var d;
d = new ActiveXObject("Scripting.Dictionary");
d.Add("a", "Athens");
d.Add("b", "Belgrade");
d.Add("c", "Cairo");
[VBScript]
Dim d   ' Create a variable.
Set d = CreateObject("Scripting.Dictionary")
d.Add "a", "Athens"   ' Add some keys and items.
d.Add "b", "Belgrade"
d.Add "c", "Cairo"

See Also

Add Method (Folders) | Exists Method | Items Method | Keys Method | Remove Method | RemoveAll Method

Applies To: Dictionary Object


Exists Method

Returns true if a specified key exists in the Dictionary object, false if it does not.

object.Exists(key)

Arguments

object
Required. Always the name of a Dictionary object.
key
Required. Key value being searched for in the Dictionary object.

Remarks

The following example illustrates the use of the Exists method.

[JScript]
function keyExists(k)
{
   var fso, s = "";
   d = new ActiveXObject("Scripting.Dictionary");
   d.Add("a", "Athens");
   d.Add("b", "Belgrade");
   d.Add("c", "Cairo");
   if (d.Exists(k))
      s += "Specified key exists.";
   else
      s += "Specified key doesn't exist.";
   return(s);
}
[VBScript]
Function KeyExistsDemo
   Dim d, msg   ' Create some variables.
   Set d = CreateObject("Scripting.Dictionary")
   d.Add "a", "Athens"   ' Add some   keys and items.
   d.Add "b", "Belgrade"
   d.Add "c", "Cairo"
   If d.Exists("c") Then
      msg = "Specified key exists."
   Else
      msg = "Specified key doesn't exist."
   End If
   KeyExistsDemo = msg
End Function

See Also

Add Method (Dictionary) | Items Method | Keys Method | Remove Method | RemoveAll Method
Applies To: Dictionary Object


Items Method

Returns an array containing all the items in a Dictionary object.

object.Items( )

The object is always the name of a Dictionary object.

Remarks

The following code illustrates use of the Items method:

[JScript]
function ItemsDemo()
{
   var a, d, i, s;                  // Create some variables.
   d = new ActiveXObject("Scripting.Dictionary");
   d.Add ("a", "Athens");              // Add some keys and items.
   d.Add ("b", "Belgrade");
   d.Add ("c", "Cairo");
   a = (new VBArray(d.Items())).toArray();   // Get the items.
   s = "";
   for (i in a)                  // Iterate the dictionary.
   {
      s += a[i] + "<br>";
   }
   return(s);                     // Return the results.
}
[VBScript]
Function DicDemo
   Dim a, d, i, s   ' Create some variables.
   Set d = CreateObject("Scripting.Dictionary")
   d.Add "a", "Athens"   ' Add some keys and items.
   d.Add "b", "Belgrade"
   d.Add "c", "Cairo"
   a = d.Items   ' Get the items.
   For i = 0 To d.Count -1 ' Iterate the array.
      s = s & a(i) & "<BR>" ' Create return string.
   Next
   DicDemo = s
End Function

See Also

Add Method (Dictionary) | Exists Method | Keys Method | Remove Method | RemoveAll Method
Applies To: Dictionary Object


Keys Method

Returns an array containing all existing keys in a Dictionary object.

object.Keys( )

The object is always the name of a Dictionary object.

Remarks

The following code illustrates use of the Keys method:

[JScript]
function KeysDemo()
{
   var a, d, i, s;                  // Create some variables.
   d = new ActiveXObject("Scripting.Dictionary");
   d.Add ("a", "Athens");              // Add some keys and items.
   d.Add ("b", "Belgrade");
   d.Add ("c", "Cairo");
   a = (new VBArray(d.Keys())).toArray();   // Get the keys.
   s = "";
   for (i in a)                  // Iterate the dictionary.
   {
      s += a[i] + " - " + d(a[i]) + "<br>";
   }
   return(s);                     // Return the results.
}
[VBScript]
Function DicDemo
   Dim a, d, i   ' Create some variables.
   Set d = CreateObject("Scripting.Dictionary")
   d.Add "a", "Athens"   ' Add some keys and items.
   d.Add "b", "Belgrade"
   d.Add "c", "Cairo"
   a = d.Keys   ' Get the keys.
   For i = 0 To d.Count -1 ' Iterate the array.
      s = s & a(i) & "<BR>" ' Return results.
   Next
   DicDemo = s
End Function

See Also

Add Method (Dictionary) | Exists Method | Items Method | Remove Method | RemoveAll Method
Applies To: Dictionary Object


Remove Method

Removes a key, item pair from a Dictionary object.

object.Remove(key)

Arguments

object
Required. Always the name of a Dictionary object.
key
Required. Key associated with the key, item pair you want to remove from the Dictionary object.

Remarks

An error occurs if the specified key, item pair does not exist.

The following code illustrates use of the Remove method:

[JScript]
var a, d, i, s;              // Create some variables.
d = new ActiveXObject("Scripting.Dictionary");
d.Add ("a", "Athens");       // Add some keys and items.
d.Add ("b", "Belgrade");
d.Add ("c", "Cairo");
...
d.Remove("b");               // Remove second pair.
[VBScript]
Dim a, d   ' Create some variables.
Set d = CreateObject("Scripting.Dictionary")
d.Add "a", "Athens"   ' Add some keys and items.
d.Add "b", "Belgrade"
d.Add "c", "Cairo"
...
d.Remove("b")   ' Remove second pair.

See Also

Add Method (Dictionary) | Exists Method | Items Method | Keys Method | RemoveAll Method
Applies To: Dictionary Object


RemoveAll Method

The RemoveAll method removes all key, item pairs from a Dictionary object.

object.RemoveAll( )

The object is always the name of a Dictionary object.

Remarks

The following code illustrates use of the RemoveAll method:

[JScript]
var a, d, i;             // Create some variables.
d = new ActiveXObject("Scripting.Dictionary");
d.Add ("a", "Athens");   // Add some keys and items.
d.Add ("b", "Belgrade");
d.Add ("c", "Cairo");
...
d.RemoveAll( );       // Clear the dictionary.
[VBScript]
Dim a, d, i   ' Create some variables.
Set d = CreateObject("Scripting.Dictionary")
d.Add "a", "Athens"   ' Add some keys and items.
d.Add "b", "Belgrade"
d.Add "c", "Cairo"
...
a = d.RemoveAll   ' Clear the dictionary.

See Also

Add Method (Dictionary) | Exists Method | Items Method | Keys Method | Remove Method
Applies To: Dictionary Object


FileSystemObject Basics

When writing scripts for Active Server Pages, the Windows Script Host, or other applications where scripting can be used, it's often important to add, move, change, create, or delete folders (directories) and files on the Web server. It may also be necessary to get information about and manipulate drives attached to the Web server.

Scripting allows you to process drives, folders, and files using the FileSystemObject (FSO) object model, which is explained in the following sections:

The FileSystemObject Object Model

The FileSystemObject object model allows you to use the familiar object.method syntax with a rich set of properties, methods, and events to process folders and files.

FileSystemObject Objects

A list of the objects and collections in FileSystemObject object model.

Programming the FileSystemObject

Description of how to program with the FileSystemObject.

Working with Drives and Folders

Describes how you use the FileSystemObject to copy and move folders, as well as get information about drives and folders.

Working with Files

Describes how you use the FileSystemObject to manipulate files.

FileSystemObject Sample Code

A real-world example that demonstrates many of the features available in the FileSystemObject object model.


The FileSystemObject Object Model

The FileSystemObject (FSO) object model allows you to use the familiar object.method syntax with a rich set of properties, methods, and events to process folders and files.

Use this object-based tool with:

  • HTML to create Web pages
  • Windows Scripting Host to create batch files for Microsoft Windows
  • Script Control to provide a scripting capability to applications developed in other languages

Because use of the FSO on the client side raises serious security issues about providing potentially unwelcome access to a client's local file system, this documentation assumes use of the FSO object model to create scripts executed by Internet Web pages on the server side. Since the server side is used, the Internet Explorer default security settings do not allow client-side use of the FileSystemObject object. Overriding those defaults could subject a local computer to unwelcome access to the file system, which could result in total destruction of the file system's integrity, causing loss of data, or worse.

The FSO object model gives your server-side applications the ability to create, alter, move, and delete folders, or to detect if particular folders exist, and if so, where. You can also find out information about folders, such as their names, the date they were created or last modified, and so forth.

The FSO object model also makes it easy to process files. When processing files, the primary goal is to store data in a space- and resource-efficient, easy-to-access format. You need to be able to create files, insert and change the data, and output (read) the data. Since storing data in a database, such as Access or SQL Server, adds a significant amount of overhead to your application, storing your data in a binary or text file may be the most efficient solution. You may prefer not to have this overhead, or your data access requirements may not require all the extra features associated with a full-featured database.

  • The FSO object model, which is contained in the Scripting type library (Scrrun.dll), supports text file creation and manipulation through the TextStream object. Although it does not yet support the creation or manipulation of binary files, future support of binary files is planned.


FileSystemObject Objects

The FileSystemObject (FSO) object model contains the following 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

To program with the FileSystemObject (FSO) object model:

  • Use the CreateObject method to create a FileSystemObject object.
  • Use the appropriate method on the newly created object.
  • Access the object's properties.

The FSO object model is contained in the Scripting type library, which is located in the Scrrun.dll file. Therefore, you must have Scrrun.dll in the appropriate system directory on your Web server to use the FSO object model.

Creating a FileSystemObject Object

First, create a FileSystemObject object by using the CreateObject method.

The following code displays how to create an instance of the FileSystemObject:

[VBScript]
Dim fso
Set fso = CreateObject("Scripting.FileSystemObject")
[JScript]
var fso;
fso = new ActiveXObject("Scripting.FileSystemObject");

In both of these examples, Scripting is the name of the type library and FileSystemObject is the name of the object that you want to create. You can create only one instance of the FileSystemObject object, regardless of how many times you try to create another.

Using the Appropriate Method

Second, use the appropriate method of the FileSystemObject object. For example, to create a new object, use either CreateTextFile or CreateFolder (the FSO object model doesn't support the creation or deletion of drives).

To delete objects, use the DeleteFile and DeleteFolder methods of the FileSystemObject object, or the Delete method of the File and Folder objects. You can also copy and move files and folders, by using the appropriate methods.

Note Some functionality in the FileSystemObject object model is redundant. For example, you can copy a file using either the CopyFile method of the FileSystemObject object, or you can use the Copy method of the File object. The methods work the same; both exist to offer programming flexibility.

Accessing Existing Drives, Files, and Folders

To gain access to an existing drive, file, or folder, use the appropriate "get" method of the FileSystemObject object:

  • GetDrive
  • GetFolder
  • GetFile

To gain access to an existing file:

[VBScript]
Dim fso, f1
Set fso = CreateObject("Scripting.FileSystemObject")
Set f1 = fso.GetFile("c:\test.txt")
[JScript]
var fso, f1;
fso = new ActiveXObject("Scripting.FileSystemObject");
f1 = fso.GetFile("c:\\test.txt");

Do not use the "get" methods for newly created objects, since the "create" functions already return a handle to that object. For example, if you create a new folder using the CreateFolder method, don't use the GetFolder method to access its properties, such as Name, Path, Size, and so forth. Just set a variable to the CreateFolder function to gain a handle to the newly created folder, then access its properties, methods, and events.

To set a variable to the CreateFolder function, use this syntax:

[VBScript]
Sub CreateFolder
   Dim fso, fldr
   Set fso = CreateObject("Scripting.FileSystemObject")
   Set fldr = fso.CreateFolder("C:\MyTest")
   Response.Write "Created folder: " & fldr.Name
End Sub
[JScript]
function CreateFolder()
{
   var fso, fldr;
   fso = new ActiveXObject("Scripting.FileSystemObject");
   fldr = fso.CreateFolder("C:\\MyTest");
   Response.Write("Created folder: " + fldr.Name);
}

Accessing the Object's Properties

Once you have a handle to an object, you can access its properties. For example, to get the name of a particular folder, first create an instance of the object, then get a handle to it with the appropriate method (in this case, the GetFolder method, since the folder already exists).

Use this code to get a handle to the GetFolder method:

[VBScript]
Set fldr = fso.GetFolder("c:\")
[JScript]
var fldr = fso.GetFolder("c:\\");

Now that you have a handle to a Folder object, you can check its Name property.

[VBScript]
Response.Write "Folder name is: " & fldr.Name
[JScript]
Response.Write("Folder name is: " + fldr.Name);

To find out the last time a file was modified, use the following syntax:

[VBScript]
Dim fso, f1
Set fso = CreateObject("Scripting.FileSystemObject")
' Get a File object to query.
Set f1 = fso.GetFile("c:\detlog.txt")
' Print information.
Response.Write "File last modified: " & f1.DateLastModified
[JScript]
var fso, f1;
fso = new ActiveXObject("Scripting.FileSystemObject");
// Get a File object to query.
f1 = fso.GetFile("c:\\detlog.txt");
// Print information.
Response.Write("File last modified: " + f1.DateLastModified);


Working with Drives and Folders

With the FileSystemObject (FSO) object model, you can work with drives and folders programmatically just as you can in the Windows Explorer interactively. You can copy and move folders, get information about drives and folders, and so forth.

Getting Information About Drives

The Drive object allows you to gain information about the various drives attached to a system, either physically or over a network. Its properties allow you to obtain information about:

  • The total size of the drive in bytes (TotalSize property)
  • How much space is available on the drive in bytes (AvailableSpace or FreeSpace properties)
  • What letter is assigned to the drive (DriveLetter property)
  • What type of drive it is, such as removable, fixed, network, CD-ROM, or RAM disk (DriveType property)
  • The drive's serial number (SerialNumber property)
  • The type of file system the drive uses, such as FAT, FAT32, NTFS, and so forth (FileSystem property)
  • Whether a drive is available for use (IsReady property)
  • The name of the share and/or volume (ShareName and VolumeName properties)
  • The path or root folder of the drive (Path and RootFolder properties)

View the sample code to see how these properties are used in FileSystemObject.

Example Usage of the Drive Object

Use the Drive object to gather information about a drive. You won't see a reference to an actual Drive object in the following code; instead, use the GetDrive method to get a reference to an existing Drive object (in this case, drv).

The following example demonstrates how to use the Drive object:

[VBScript]
Sub ShowDriveInfo(drvPath)
   Dim fso, drv, s
   Set fso = CreateObject("Scripting.FileSystemObject")
   Set drv = fso.GetDrive(fso.GetDriveName(drvPath))
   s = "Drive " & UCase(drvPath) & " - "
   s = s & drv.VolumeName & "<br>"
   s = s & "Total Space: " & FormatNumber(drv.TotalSize / 1024, 0)
   s = s & " Kb" & "<br>"
   s = s & "Free Space: " & FormatNumber(drv.FreeSpace / 1024, 0)
   s = s & " Kb" & "<br>"
   Response.Write s
End Sub
[JScript]
function ShowDriveInfo1(drvPath)
{
   var fso, drv, s ="";
   fso = new ActiveXObject("Scripting.FileSystemObject");
   drv = fso.GetDrive(fso.GetDriveName(drvPath));
   s += "Drive " + drvPath.toUpperCase()+ " - ";
   s += drv.VolumeName + "<br>";
   s += "Total Space: " + drv.TotalSize / 1024;
   s += " Kb" + "<br>";
   s += "Free Space: " + drv.FreeSpace / 1024;
   s += " Kb" + "<br>";
   Response.Write(s);
}

Working with Folders

Common folder tasks and the methods for performing them are described in the following table.

Task | Method
Create a folder. | FileSystemObject.CreateFolder
Delete a folder. | Folder.Delete or FileSystemObject.DeleteFolder
Move a folder. | Folder.Move or FileSystemObject.MoveFolder
Copy a folder. | Folder.Copy or FileSystemObject.CopyFolder
Retrieve the name of a folder. | Folder.Name
Find out if a folder exists on a drive. | FileSystemObject.FolderExists
Get an instance of an existing Folder object. | FileSystemObject.GetFolder
Find out the name of a folder's parent folder. | FileSystemObject.GetParentFolderName
Find out the path of system folders. | FileSystemObject.GetSpecialFolder

View the sample code to see how many of these methods and properties are used in FileSystemObject.

The following example demonstrates how to use the Folder and FileSystemObject objects to manipulate folders and gain information about them.

[VBScript]
Sub ShowFolderInfo()
   Dim fso, fldr, s
   ' Get instance of FileSystemObject.
   Set fso = CreateObject("Scripting.FileSystemObject")
   ' Get Drive object.
   Set fldr = fso.GetFolder("c:")
   ' Print parent folder name.
   Response.Write "Parent folder name is: " & fldr & "<br>"
   ' Print drive name.
   Response.Write "Contained on drive " & fldr.Drive & "<br>"
   ' Print root file name.
   If fldr.IsRootFolder = True Then
      Response.Write "This is the root folder." & ""<br>"<br>"
   Else
      Response.Write "This folder isn't a root folder." & "<br><br>"
   End If
   ' Create a new folder with the FileSystemObject object.
   fso.CreateFolder ("C:\Bogus")
   Response.Write "Created folder C:\Bogus" & "<br>"
   ' Print the base name of the folder.
   Response.Write "Basename = " & fso.GetBaseName("c:\bogus") & "<br>"
   ' Delete the newly created folder.
   fso.DeleteFolder ("C:\Bogus")
   Response.Write "Deleted folder C:\Bogus" & "<br>"
End Sub
[JScript]
function ShowFolderInfo()
{
   var fso, fldr, s = "";
   // Get instance of FileSystemObject.
   fso = new ActiveXObject("Scripting.FileSystemObject");
   // Get Drive object.
   fldr = fso.GetFolder("c:");
   // Print parent folder name.
   Response.Write("Parent folder name is: " + fldr + "<br>");
   // Print drive name.
   Response.Write("Contained on drive " + fldr.Drive + "<br>");
   // Print root file name.
   if (fldr.IsRootFolder)
     Response.Write("This is the root folder.");
   else
     Response.Write("This folder isn't a root folder.");
   Response.Write("<br><br>");
   // Create a new folder with the FileSystemObject object.
   fso.CreateFolder ("C:\\Bogus");
   Response.Write("Created folder C:\\Bogus" + "<br>");
   // Print the base name of the folder.
   Response.Write("Basename = " + fso.GetBaseName("c:\\bogus") + "<br>");
   // Delete the newly created folder.
   fso.DeleteFolder ("C:\\Bogus");
   Response.Write("Deleted folder C:\\Bogus" + "<br>");
}


Working with Files

There are two major categories of file manipulation:

  • Creating, adding, or removing data, and reading files
  • Moving, copying, and deleting files

Creating Files

There are three ways to create an empty text file (sometimes referred to as a "text stream").

The first way is to use the CreateTextFile method. The following example demonstrates how to create a text file using the CreateTextFileMethod method.

[VBScript]
Dim fso, f1
Set fso = CreateObject("Scripting.FileSystemObject")
Set f1 = fso.CreateTextFile("c:\testfile.txt", True)
[JScript]
var fso, f1;
fso = new ActiveXObject("Scripting.FileSystemObject");
f1 = fso.CreateTextFile("c:\\testfile.txt", true);

The second way to create a text file is to use the OpenTextFile method of the FileSystemObject object with the ForWriting flag set.

[VBScript]
Dim fso, ts
Const ForWriting = 2
Set fso = CreateObject("Scripting. FileSystemObject")
Set ts = fso.OpenTextFile("c:\test.txt", ForWriting, True)
[JScript]
var fso, ts;
var ForWriting= 2;
fso = new ActiveXObject("Scripting.FileSystemObject");
ts = fso.OpenTextFile("c:\\test.txt", ForWriting, true);

A third way to create a text file is to use the OpenAsTextStream method with the ForWriting flag set.

[VBScript]
Dim fso, f1, ts
Const ForWriting = 2
Set fso = CreateObject("Scripting.FileSystemObject")
fso.CreateTextFile ("c:\test1.txt")
Set f1 = fso.GetFile("c:\test1.txt")
Set ts = f1.OpenAsTextStream(ForWriting, True)
[JScript]
var fso, f1, ts;
var ForWriting = 2;
fso = new ActiveXObject("Scripting.FileSystemObject");
fso.CreateTextFile ("c:\\test1.txt");
f1 = fso.GetFile("c:\\test1.txt");
ts = f1.OpenAsTextStream(ForWriting, true);

Adding Data to the File

Once the text file is created, add data to the file using the following three steps:

Open the text file.

Write the data.

Close the file.

To open an existing file, use either the OpenTextFile method of the FileSystemObject object or the OpenAsTextStream method of the File object.

To write data to the open text file, use the Write, WriteLine, or WriteBlankLines methods of the TextStream object, according to the tasks outlined in the following table.

Task | Method
Write data to an open text file without a trailing newline character. | Write
Write data to an open text file with a trailing newline character. | WriteLine
Write one or more blank lines to an open text file. | WriteBlankLines

To close an open file, use the Close method of the TextStream object.

Note The newline character contains a character or characters (depending on the operating system) to advance the cursor to the beginning of the next line (carriage return/line feed). Be aware that the end of some strings may already have such nonprinting characters.

The following example demonstrates how to open a file, use all three write methods to add data to the file, and then close the file:

[VBScript]
Sub CreateFile()
   Dim fso, tf
   Set fso = CreateObject("Scripting.FileSystemObject")
   Set tf = fso.CreateTextFile("c:\testfile.txt", True)
   ' Write a line with a newline character.
   tf.WriteLine("Testing 1, 2, 3.")
   ' Write three newline characters to the file.
   tf.WriteBlankLines(3)
   ' Write a line.
   tf.Write ("This is a test.")
   tf.Close
End Sub
[JScript]
function CreateFile()
{
   var fso, tf;
   fso = new ActiveXObject("Scripting.FileSystemObject");
   tf = fso.CreateTextFile("c:\\testfile.txt", true);
   // Write a line with a newline character.
   tf.WriteLine("Testing 1, 2, 3.") ;
   // Write three newline characters to the file.
   tf.WriteBlankLines(3) ;
   // Write a line.
   tf.Write ("This is a test.");
   tf.Close();
}

Reading Files

To read data from a text file, use the Read, ReadLine, or ReadAll method of the TextStream object. The following table describes which method to use for various tasks.

Task | Method
Read a specified number of characters from a file. | Read
Read an entire line (up to, but not including, the newline character). | ReadLine
Read the entire contents of a text file. | ReadAll

If you use the Read or ReadLine method and want to skip to a particular portion of data, use the Skip or SkipLine method. The resulting text of the read methods is stored in a string which can be displayed in a control, parsed by string functions (such as Left, Right, and Mid), concatenated, and so forth.

The following example demonstrates how to open a file, write to it, and then read from it:

[VBScript]
Sub ReadFiles
   Dim fso, f1, ts, s
   Const ForReading = 1
   Set fso = CreateObject("Scripting.FileSystemObject")
   Set f1 = fso.CreateTextFile("c:\testfile.txt", True)
   ' Write a line.
   Response.Write "Writing file <br>"
   f1.WriteLine "Hello World"
   f1.WriteBlankLines(1)
   f1.Close
   ' Read the contents of the file.
   Response.Write "Reading file <br>"
   Set ts = fso.OpenTextFile("c:\testfile.txt", ForReading)
   s = ts.ReadLine
   Response.Write "File contents = '" & s & "'"
   ts.Close
End Sub
[JScript]
function ReadFiles()
{
   var fso, f1, ts, s;
   var ForReading = 1;
   fso = new ActiveXObject("Scripting.FileSystemObject");
   f1 = fso.CreateTextFile("c:\\testfile.txt", true);
   // Write a line.
   Response.Write("Writing file <br>");
   f1.WriteLine("Hello World");
   f1.WriteBlankLines(1);
   f1.Close();
   // Read the contents of the file.
   Response.Write("Reading file <br>");
   ts = fso.OpenTextFile("c:\\testfile.txt", ForReading);
   s = ts.ReadLine();
   Response.Write("File contents = '" + s + "'");
   ts.Close();
}

Moving, Copying, and Deleting Files

The FSO object model has two methods each for moving, copying, and deleting files, as described in the following table.

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

[VBScript]
Sub ManipFiles
   Dim fso, f1, f2, s
   Set fso = CreateObject("Scripting.FileSystemObject")
   Set f1 = fso.CreateTextFile("c:\testfile.txt", True)
   Response.Write "Writing file <br>"
   ' Write a line.
   f1.Write ("This is a test.")
   ' Close the file to writing.
   f1.Close
   Response.Write "Moving file to c:\tmp <br>"
   ' Get a handle to the file in root of C:\.
   Set f2 = fso.GetFile("c:\testfile.txt")
   ' Move the file to \tmp directory.
   f2.Move ("c:\tmp\testfile.txt")
   Response.Write "Copying file to c:\temp <br>"
   ' Copy the file to \temp.
   f2.Copy ("c:\temp\testfile.txt")
   Response.Write "Deleting files <br>"
   ' Get handles to files' current location.
   Set f2 = fso.GetFile("c:\tmp\testfile.txt")
   Set f3 = fso.GetFile("c:\temp\testfile.txt")
   ' Delete the files.
   f2.Delete
   f3.Delete
   Response.Write "All done!"
End Sub
[JScript]
function ManipFiles()
{
   var fso, f1, f2, s;
   fso = new ActiveXObject("Scripting.FileSystemObject");
   f1 = fso.CreateTextFile("c:\\testfile.txt", true);
   Response.Write("Writing file <br>");
   // Write a line.
   f1.Write("This is a test.");
   // Close the file to writing.
   f1.Close();
   Response.Write("Moving file to c:\\tmp <br>");
   // Get a handle to the file in root of C:\.
   f2 = fso.GetFile("c:\\testfile.txt");
   // Move the file to \tmp directory.
   f2.Move ("c:\\tmp\\testfile.txt");
   Response.Write("Copying file to c:\\temp <br>");
   // Copy the file to \temp.
   f2.Copy ("c:\\temp\\testfile.txt");
   Response.Write("Deleting files <br>");
   // Get handles to files' current location.
   f2 = fso.GetFile("c:\\tmp\\testfile.txt");
   f3 = fso.GetFile("c:\\temp\\testfile.txt");
   // Delete the files.
   f2.Delete();
   f3.Delete();
   Response.Write("All done!");
}


FileSystemObject Sample Code

The sample code described in this section provides a real-world example that demonstrates many of the features available in the FileSystemObject object model. This code shows how all the features of the object model work together, and how to use those features effectively in your own code.

Notice that since this code is fairly generic, some additional code and a little tweaking are needed to make this code actually run on your machine. These changes are necessary because of the different ways input and output to the user is handled between Active Server Pages and the Windows Scripting Host.

To run this code on an Active Server Page, use the following steps:

Create a standard web page with an .asp extension.

Copy the following sample code into that file between the <BODY>...</BODY> tags.

Enclose all the code within <%...%> tags.

Move the Option Explicit statement from its current position in the code to the very top of your HTML page, positioning it even before the opening <HTML> tag.

Place <%...%> tags around the Option Explicit statement to ensure that it's run on the server side.

Add the following code to the end of the sample code:

Sub Print(x)
   Response.Write "<PRE>&ltFONT FACE=""Courier New"" SIZE=""1"">"
   Response.Write x
   Response.Write "</FONT></PRE>"
End Sub
Main

The previous code adds a print procedure that will run on the server side, but display results on the client side. To run this code on the Windows Scripting Host, add the following code to the end of the sample code:

Sub Print(x)
   WScript.Echo x
End Sub
Main

The code is contained in the following section:

''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
' FileSystemObject Sample Code
' Copyright 1998 Microsoft Corporation.   All Rights Reserved.
''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''

Option Explicit

''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
' Regarding code quality:
' 1) The following code does a lot of string manipulation by
'    concatenating short strings together with the "&" operator.
'    Since string concatenation is expensive, this is a very
'    inefficient way to write code. However, it is a very
'    maintainable way to write code, and is used here because this
'    program performs extensive disk operations, and because the
'    disk is much slower than the memory operations required to
'    concatenate the strings. Keep in mind that this is demonstration
'    code, not production code.
'
' 2) "Option Explicit" is used, because declared variable access is
'    slightly faster than undeclared variable access. It also prevents
'    bugs from creeping into your code, such as when you misspell
'    DriveTypeCDROM as DriveTypeCDORM.
'
' 3) Error handling is absent from this code, to make the code more
'    readable. Although precautions have been taken to ensure that the
'    code will not error in common cases, file systems can be
'    unpredictable. In production code, use On Error Resume Next and
'    the Err object to trap possible errors.
''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''

''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
' Some handy global variables
''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
Dim TabStop
Dim NewLine

Const TestDrive = "C"
Const TestFilePath = "C:\Test"

''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
' Constants returned by Drive.DriveType
''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
Const DriveTypeRemovable = 1
Const DriveTypeFixed = 2
Const DriveTypeNetwork = 3
Const DriveTypeCDROM = 4
Const DriveTypeRAMDisk = 5

''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
' Constants returned by File.Attributes
''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
Const FileAttrNormal   = 0
Const FileAttrReadOnly = 1
Const FileAttrHidden = 2
Const FileAttrSystem = 4
Const FileAttrVolume = 8
Const FileAttrDirectory = 16
Const FileAttrArchive = 32
Const FileAttrAlias = 64
Const FileAttrCompressed = 128

''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
' Constants for opening files
''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
Const OpenFileForReading = 1
Const OpenFileForWriting = 2
Const OpenFileForAppending = 8

''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
' ShowDriveType
' Purpose:
'    Generates a string describing the drive type of a given Drive object.
' Demonstrates the following
'  - Drive.DriveType
''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
Function ShowDriveType(Drive)

   Dim S

   Select Case Drive.DriveType
   Case DriveTypeRemovable
      S = "Removable"
   Case DriveTypeFixed
      S = "Fixed"
   Case DriveTypeNetwork
      S = "Network"
   Case DriveTypeCDROM
      S = "CD-ROM"
   Case DriveTypeRAMDisk
      S = "RAM Disk"
   Case Else
      S = "Unknown"
   End Select

   ShowDriveType = S

End Function

''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
' ShowFileAttr
' Purpose:
'    Generates a string describing the attributes of a file or folder.
' Demonstrates the following
'  - File.Attributes
'  - Folder.Attributes
''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''

Function ShowFileAttr(File) ' File can be a file or folder

   Dim S
   Dim Attr

   Attr = File.Attributes

   If Attr = 0 Then
      ShowFileAttr = "Normal"
      Exit Function
   End If

   If 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

   ' Two ways to delete a file:

   FSO.DeleteFile(TestFilePath & "\Beatles\OctopusGarden.txt")

   Set File = FSO.GetFile(TestFilePath & "\Beatles\BathroomWindow.txt")
   File.Delete

   ' Two ways to delete a folder:
   FSO.DeleteFolder(TestFilePath & "\Beatles")
   FSO.DeleteFile(TestFilePath & "\ReadMe.txt")
   Set TestFolder = FSO.GetFolder(TestFilePath)
   TestFolder.Delete

End Sub

''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
' CreateLyrics
' Purpose:
'    Builds a couple of text files in a folder.
' Demonstrates the following
'  - FileSystemObject.CreateTextFile
'  - TextStream.WriteLine
'  - TextStream.Write
'  - TextStream.WriteBlankLines
'  - TextStream.Close
''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''

Sub CreateLyrics(Folder)

   Dim TextStream

   Set TextStream = Folder.CreateTextFile("OctopusGarden.txt")

   ' Note that this does not add a line feed to the file.
   TextStream.Write("Octopus' Garden ")
   TextStream.WriteLine("(by Ringo Starr)")
   TextStream.WriteBlankLines(1)
   TextStream.WriteLine("I'd like to be under the sea in an octopus' garden in the shade,")
   TextStream.WriteLine("He'd let us in, knows where we've been -- in his octopus' garden in the shade.")
   TextStream.WriteBlankLines(2)

   TextStream.Close

   Set TextStream = Folder.CreateTextFile("BathroomWindow.txt")
   TextStream.WriteLine("She Came In Through The Bathroom Window (by Lennon/McCartney)")
   TextStream.WriteLine("")
   TextStream.WriteLine("She came in through the bathroom window protected by a silver spoon")
   TextStream.WriteLine("But now she sucks her thumb and wanders by the banks of her own lagoon")
   TextStream.WriteBlankLines(2)
   TextStream.Close

End Sub

''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
' GetLyrics
' Purpose:
'    Displays the contents of the lyrics files.
' Demonstrates the following
'  - FileSystemObject.OpenTextFile
'  - FileSystemObject.GetFile
'  - TextStream.ReadAll
'  - TextStream.Close
'  - File.OpenAsTextStream
'  - TextStream.AtEndOfStream
'  - TextStream.ReadLine
''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''

Function GetLyrics(FSO)

   Dim TextStream
   Dim S
   Dim File

   ' There are several ways to open a text file, and several
   ' ways to read the data out of a file. Here's two ways
   ' to do each:

   Set TextStream = FSO.OpenTextFile(TestFilePath & "\Beatles\OctopusGarden.txt", OpenFileForReading)

   S = TextStream.ReadAll & NewLine & NewLine
   TextStream.Close

   Set File = FSO.GetFile(TestFilePath & "\Beatles\BathroomWindow.txt")
   Set TextStream = File.OpenAsTextStream(OpenFileForReading)
   Do    While Not TextStream.AtEndOfStream
      S = S & TextStream.ReadLine & NewLine
   Loop
   TextStream.Close

   GetLyrics = S

End Function

''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
' BuildTestDirectory
' Purpose:
'    Builds a directory hierarchy to demonstrate the FileSystemObject.
'    We'll build a hierarchy in this order:
'       C:\Test
'       C:\Test\ReadMe.txt
'       C:\Test\Beatles
'       C:\Test\Beatles\OctopusGarden.txt
'       C:\Test\Beatles\BathroomWindow.txt
' Demonstrates the following
'  - FileSystemObject.DriveExists
'  - FileSystemObject.FolderExists
'  - FileSystemObject.CreateFolder
'  - FileSystemObject.CreateTextFile
'  - Folders.Add
'  - Folder.CreateTextFile
'  - TextStream.WriteLine
'  - TextStream.Close
''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''

Function BuildTestDirectory(FSO)

   Dim 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)

   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

In This Section

FileSystemObject Properties
List of properties you can use with the FileSystemObject object model.
FileSystemObject Methods
List of methods you can use with the FileSystemObject object model.
FileSystemObject Objects
List of objects you can use with the FileSystemObject object model.
FileSystemObject Collections
List of collections you can use with the FileSystemObject object model.

Related Section

FileSystemObject Basics
A guide to the fundamentals of the FileSystemObject.


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

Returns true if the file pointer is positioned immediately before the end-of-line marker in a TextStream file; false if it is not. Read-only.

object.AtEndOfLine

The object is always the name of a TextStream object.

Remarks

The AtEndOfLine property applies only to TextStream files that are open for reading; otherwise, an error occurs.

The following code illustrates the use of the AtEndOfLine property:

[JScript]
function GetALine(filespec)
{
   var fso, a, s, ForReading;
   ForReading = 1, s = "";
   fso = new ActiveXObject("Scripting.FileSystemObject");
   a = fso.OpenTextFile(filespec, ForReading, false);
   while (!a.AtEndOfLine)
   {
      s += a.Read(1);
   }
   a.Close( );
   return(s);
}
[VBScript]
Function ReadEntireFile(filespec)
   Const ForReading = 1
   Dim fso, theFile, retstring
   Set fso = CreateObject("Scripting.FileSystemObject")
   Set theFile = fso.OpenTextFile(filespec, ForReading, False)
   Do While theFile.AtEndOfLine <> True
      retstring = theFile.Read(1)
   Loop
   theFile.Close
   ReadEntireFile = retstring
End Function

See Also

AtEndOfStream Property

Applies To: TextStream Object


AtEndOfStream Property

Returns true if the file pointer is at the end of a TextStream file; false if it is not. Read-only.

object.AtEndOfStream

The object is always the name of a TextStream object.

Remarks

The AtEndOfStream property applies only to TextStream files that are open for reading, otherwise, an error occurs.

The following code illustrates the use of the AtEndOfStream property:

[JScript]
function GetALine(filespec)
{
   var fso, f, s, ForReading;
   ForReading = 1, s = "";
   fso = new ActiveXObject("Scripting.FileSystemObject");
   f = fso.OpenTextFile(filespec, ForReading, false);
   while (!f.AtEndOfStream)
      s += f.ReadLine( );
   f.Close( );
   return(s);
}
[VBScript]
Function ReadEntireFile(filespec)
   Const ForReading = 1
   Dim fso, theFile, retstring
   Set fso = CreateObject("Scripting.FileSystemObject")
   Set theFile = fso.OpenTextFile(filespec, ForReading, False)
   Do While theFile.AtEndOfStream <> True
      retstring = theFile.ReadLine
   Loop
   theFile.Close
   ReadEntireFile = retstring
End Function

See Also

AtEndOfLine Property

Applies To: TextStream Object


Attributes Property

Sets or returns the attributes of files or folders. Read/write or read-only, depending on the attribute.

object.Attributes [= newattributes]

Arguments

object
Required. Always the name of a File or Folder object.
newattributes
Optional. If provided, newattributes is the new value for the attributes of the specified object.

Settings

The newattributes argument can have any of the following values or any logical combination of the following values:

Constant | 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 | 64 | Link or shortcut. Attribute is read-only.
Compressed | 128 | Compressed file. Attribute is read-only.

Remarks

The following code illustrates the use of the Attributes property with a file:

[JScript]
function ToggleArchiveBit(filespec)
{
   var fso, f, r, s;
   fso = new ActiveXObject("Scripting.FileSystemObject");
   f = fso.GetFile(filespec)
   if (f.attributes && 32)
   {
      f.attributes = f.attributes - 32;
      s = "Archive bit is cleared.";
   }
   else
   {
      f.attributes = f.attributes + 32;
      s =   "Archive bit is set.";
   }
   return(s);
}
[VBScript]
Function ToggleArchiveBit(filespec)
   Dim fso, f
   Set fso = CreateObject("Scripting.FileSystemObject")
   Set f = fso.GetFile(filespec)
   If f.attributes and 32 Then
      f.attributes = f.attributes - 32
      ToggleArchiveBit = "Archive bit is cleared."
   Else
      f.attributes = f.attributes + 32
      ToggleArchiveBit = "Archive bit is set."
   End If
End Function

See Also

DateCreated Property | DateLastAccessed Property | DateLastModified Property | Drive Property | Files Property | IsRootFolder Property | Name Property | ParentFolder Property | Path Property | ShortName Property | ShortPath Property | Size Property | SubFolders Property | Type Property

Applies To: File Object | Folder Object


AvailableSpace Property

Returns the amount of space available to a user on the specified drive or network share.

object.AvailableSpace

The object is always a Drive object.

Remarks

The value returned by the AvailableSpace property is typically the same as that returned by the FreeSpace property. Differences may occur between the two for computer systems that support quotas.

The following code illustrates the use of the AvailableSpace property:

[JScript]
function ShowAvailableSpace(drvPath)
{
   var fso, d, s;
   fso = new ActiveXObject("Scripting.FileSystemObject");
   d = fso.GetDrive(fso.GetDriveName(drvPath));
   s = "Drive " + drvPath.toUpperCase() + " - ";
   s += d.VolumeName + "<br>";
   s += "Available Space: " + d.AvailableSpace/1024 + " Kbytes";
   return(s);
}
[VBScript]
Function ShowAvailableSpace(drvPath)
   Dim fso, d, s
   Set fso = CreateObject("Scripting.FileSystemObject")
   Set d = fso.GetDrive(fso.GetDriveName(drvPath))
   s = "Drive " & UCase(drvPath) & " - "
   s = s & d.VolumeName   & "<BR>"
   s = s & "Available Space: " & FormatNumber(d.AvailableSpace/1024, 0)
   s = s & " Kbytes"
   ShowAvailableSpace = s
End Function

See Also

DriveLetter Property | DriveType Property | FileSystem Property | FreeSpace Property | IsReady Property | Path Property | RootFolder Property | SerialNumber Property | ShareName Property | TotalSize Property | VolumeName Property

Applies To: Drive Object


Column Property

Read-only property that returns the column number of the current character position in a TextStream file.

object.Column

The object is always the name of a TextStream object.

Remarks

After a newline character has been written, but before any other character is written, Column is equal to 1.

The following examples illustrates the use of the Column property:

[JScript]
function GetColumn()
{
   var fso, f, m;
   var ForReading = 1, ForWriting = 2;
   fso = new ActiveXObject("Scripting.FileSystemObject");
   f = fso.OpenTextFile("c:\\testfile.txt", ForWriting, true);
   f.Write("Hello World!");
   f.Close();
   f = fso.OpenTextFile("c:\\testfile.txt", ForReading);
   m = f.ReadLine();
   return(f.Column);
}
[VBScript]
Function GetColumn
   Const ForReading = 1, ForWriting = 2
   Dim fso, f, m
   Set fso = CreateObject("Scripting.FileSystemObject")
   Set f = fso.OpenTextFile("c:\testfile.txt", ForWriting, True)
   f.Write "Hello world!"
   f.Close
   Set f = fso.OpenTextFile("c:\testfile.txt", ForReading)
   m =   f.ReadLine
   GetColumn = f.Column
End Function

See Also

Line Property

Applies To: TextStream Object


CompareMode Property

Sets and returns the comparison mode for comparing string keys in a Dictionary object.

object.CompareMode[ = compare]

Arguments

object
Required. Always the name of a Dictionary object.
compare
Optional. If provided, compare is a value representing the comparison mode. Acceptable values are 0 (Binary), 1 (Text), 2 (Database). Values greater than 2 can be used to refer to comparisons using specific Locale IDs (LCID).

Remarks

An error occurs if you try to change the comparison mode of a Dictionary object that already contains data.

The following example illustrates the use of the CompareMode property:

[JScript]function TestCompareMode(key)
{
   // Create some variables.
   var a, d;
   var BinaryCompare = 0, TextCompare = 1;
   d = new ActiveXObject("Scripting.Dictionary");
   // Set Compare mode to Text.
   d.CompareMode = TextCompare;
   // Add some keys and items.
   d.Add("a", "Athens");
   d.Add("b", "Belgrade");
   d.Add("c", "Cairo");
   return(d.Item(key));
}
[VBScript
Dim d
Set d = CreateObject("Scripting.Dictionary")

d.CompareMode = vbTextCompare
d.Add "a", "Athens"   ' Add some keys and items.
d.Add "b", "Belgrade"
d.Add "c", "Cairo"
d.Add "B", "Baltimore"   ' Add method fails on this line because the
                         ' letter b already exists in the Dictionary.

See Also

Key Property

Applies To: Dictionary Object


DateLastAccessed Property

Returns the date and time that the specified file or folder was last accessed. Read-only.

object.DateLastAccessed

The object is always a File or Folder object.

Remarks

The following code illustrates the use of the DateLastAccessed property with a file:

[JScript]
function ShowFileAccessInfo(filespec)
{
   var fso, f, s;
   fso = new ActiveXObject("Scripting.FileSystemObject");
   f = fso.GetFile(filespec);
   s = filespec.toUpperCase() + "<br>";
   s += "Created: " + f.DateCreated + "<br>";
   s += "Last Accessed: " + f.DateLastAccessed + "<br>";
   s += "Last Modified: " + f.DateLastModified;
   return(s);
}
[VBScript]
Function ShowFileAccessInfo(filespec)
   Dim fso, f, s
   Set fso = CreateObject("Scripting.FileSystemObject")
   Set f = fso.GetFile(filespec)
   s = UCase(filespec) & "<BR>"
   s = s & "Created: " & f.DateCreated & "<BR>"
   s = s & "Last Accessed: " & f.DateLastAccessed & "<BR>"
   s = s & "Last Modified: " & f.DateLastModified
   ShowFileAccessInfo = s
End Function
Note This method depends on the underlying operating system for its behavior. If the operating system does not support providing time information, none will be returned.

See Also

Attributes Property | DateCreated Property | DateLastModified Property | Drive Property | Files Property | IsRootFolder Property | Name Property | ParentFolder Property | Path Property | ShortName Property | ShortPath Property | Size Property | SubFolders Property | Type Property

Applies To: File Object | Folder Object


DateLastModified Property

Returns the date and time that the specified file or folder was last modified. Read-only.

object.DateLastModified

The object is always a File or Folder object.

Remarks

The following code illustrates the use of the DateLastModified property with a file:

[JScript]
function ShowFileAccessInfo(filespec)
{
   var fso, f, s;
   fso = new ActiveXObject("Scripting.FileSystemObject");
   f = fso.GetFile(filespec);
   s = filespec.toUpperCase() + "<br>";
   s += "Created: " + f.DateCreated + "<br>";
   s += "Last Accessed: " + f.DateLastAccessed + "<br>";
   s += "Last Modified: " + f.DateLastModified;
   return(s);
}
[VBScript]
Function ShowFileAccessInfo(filespec)
   Dim fso, f, s
   Set fso = CreateObject("Scripting.FileSystemObject")
   Set f = fso.GetFile(filespec)
   s = UCase(filespec) & "<BR>"
   s = s & "Created: " & f.DateCreated & "<BR>"
   s = s & "Last Accessed: " & f.DateLastAccessed & "<BR>"
   s = s & "Last Modified: " & f.DateLastModified
   ShowFileAccessInfo = s
End Function

See Also

Attributes Property | DateCreated Property | DateLastAccessed Property | Drive Property | Files Property | IsRootFolder Property | Name Property | ParentFolder Property | Path Property | ShortName Property | ShortPath Property | Size Property | SubFolders Property | Type Property

Applies To: File Object | Folder Object


Drive Property

Returns the drive letter of the drive on which the specified file or folder resides. Read-only.

object.Drive

The object is always a File or Folder object.

Remarks

The following code illustrates the use of the Drive property:

[JScript]
function ShowFileAccessInfo(filespec)
{
   var fso, f, s;
   fso = new ActiveXObject("Scripting.FileSystemObject");
   f = fso.GetFile(filespec);
   s = f.Name + " on Drive " + f.Drive + "<br>";
   s += "Created: " + f.DateCreated + "<br>";
   s += "Last Accessed: " + f.DateLastAccessed + "<br>";
   s += "Last Modified: " + f.DateLastModified;
   return(s);
}
[VBScript]
Function ShowFileAccessInfo(filespec)
   Dim fso, f, s
   Set fso = CreateObject("Scripting.FileSystemObject")
   Set f = fso.GetFile(filespec)
   s = f.Name & " on Drive " & UCase(f.Drive) & "<BR>"
   s = s & "Created: " & f.DateCreated & "<BR>"
   s = s & "Last Accessed: " & f.DateLastAccessed & "<BR>"
   s = s & "Last Modified: " & f.DateLastModified
   ShowFileAccessInfo = s
End Function

See Also

Attributes Property | DateCreated Property | DateLastAccessed Property | DateLastModified Property | Files Property | IsRootFolder Property | Name Property | ParentFolder Property | Path Property | ShortName Property | ShortPath Property | Size Property | SubFolders Property | Type Property

Applies To: File Object | Folder Object


DriveLetter Property

Returns the drive letter of a physical local drive or a network share. Read-only.

object.DriveLetter

The object is always a Drive object.

Remarks

The DriveLetter property returns a zero-length string ("") if the specified drive is not associated with a drive letter, for example, a network share that has not been mapped to a drive letter.

The following code illustrates the use of the DriveLetter property:

[JScript]
function ShowDriveLetter(drvPath)
{
   var fso, d, s;
   fso = new ActiveXObject("Scripting.FileSystemObject");
   d = fso.GetDrive(fso.GetDriveName(drvPath));
   s = "Drive " + d.DriveLetter.toUpperCase( ) + ": - ";
   s += d.VolumeName + "<br>";
   s += "Available Space: " + d.AvailableSpace/1024 + " Kbytes";
   return(s);
}
[VBScript]
Function ShowDriveLetter(drvPath)
   Dim fso, d, s
   Set fso = CreateObject("Scripting.FileSystemObject")
   Set d = fso.GetDrive(fso.GetDriveName(drvPath))
   s = "Drive " & d.DriveLetter & ": - "
   s = s & d.VolumeName & "<BR>"
   s = s & "Free Space: " & FormatNumber(d.FreeSpace/1024, 0)
   s = s & " Kbytes"
   ShowDriveLetter = s
End Function

See Also

AvailableSpace Property | DriveType Property | FileSystem Property | FreeSpace Property | IsReady Property | Path Property | RootFolder Property | SerialNumber Property | ShareName Property | TotalSize Property | VolumeName Property

Applies To: Drive Object


Drives Property

Returns a Drives collection consisting of all Drive objects available on the local machine.

object.Drives

The object is always a FileSystemObject.

Remarks

Removable-media drives need not have media inserted for them to appear in the Drives collection.

[JScript]

You can iterate the members of the Drives collection using the Enumerator object and the for statement:

[JScript]
function ShowDriveList()
{
   var fso, s, n, e, x;
   fso = new ActiveXObject("Scripting.FileSystemObject");
   e = new Enumerator(fso.Drives);
   s = "";
   for (; !e.atEnd(); e.moveNext())
   {
      x = e.item();
      s = s + x.DriveLetter;
      s += " - ";
      if (x.DriveType == 3)
         n = x.ShareName;
      else if (x.IsReady)
         n = x.VolumeName;
      else
         n = "[Drive not ready]";
      s +=   n + "<br>";
   }
   return(s);
}

[VBScript]

You can iterate the members of the Drives collection using a For Each...Next construct as illustrated in the following code:

[VBScript]
Function ShowDriveList
   Dim fso, d, dc, s, n
   Set fso = CreateObject("Scripting.FileSystemObject")
   Set dc = fso.Drives
   For Each d in dc
      n = ""
      s = s & d.DriveLetter & " - "
      If d.DriveType = 3 Then
         n = d.ShareName
      ElseIf d.IsReady Then
         n = d.VolumeName
      End If
      s = s & n & "<BR>"
   Next
   ShowDriveList = s
End Function

See Also

Drives Collection | Files Property | SubFolders Property

Applies To: FileSystemObject Object


DriveType Property

Returns a value indicating the type of a specified drive.

object.DriveType

The object is always a Drive object.

Remarks

The following code illustrates the use of the DriveType property:

[JScript]
function ShowDriveType(drvpath)
{
   var fso, d, s, t;
   fso = new ActiveXObject("Scripting.FileSystemObject");
   d = fso.GetDrive(drvpath);
   switch (d.DriveType)
   {
      case 0: t = "Unknown"; break;
      case 1: t = "Removable"; break;
      case 2: t = "Fixed"; break;
      case 3: t = "Network"; break;
      case 4: t = "CD-ROM"; break;
      case 5: t = "RAM Disk"; break;
   }
   s = "Drive " + d.DriveLetter + ": - " + t;
   return(s);
}
[VBScript]
Function ShowDriveType(drvpath)
   Dim fso, d, t
   Set fso = CreateObject("Scripting.FileSystemObject")
   Set d = fso.GetDrive(drvpath)
   Select Case d.DriveType
      Case 0: t = "Unknown"
      Case 1: t = "Removable"
      Case 2: t = "Fixed"
      Case 3: t = "Network"
      Case 4: t = "CD-ROM"
      Case 5: t = "RAM Disk"
   End Select
   ShowDriveType = "Drive " & d.DriveLetter & ": - " & t
End Function

See Also

AvailableSpace Property | DriveLetter Property | FileSystem Property | FreeSpace Property | IsReady Property | Path Property | RootFolder Property | SerialNumber Property | ShareName Property | TotalSize Property | VolumeName Property

Applies To: Drive Object


FileSystem Property

Returns the type of file system in use for the specified drive.

object.FileSystem

The object is always a Drive object.

Remarks

Available return types include FAT, NTFS, and CDFS.

The following code illustrates the use of the FileSystem property:

[JScript]
function ShowFileSystemType(drvPath)
{
   var fso,d, s;
   fso = new ActiveXObject("Scripting.FileSystemObject");
   d = fso.GetDrive(drvPath);
   s = d.FileSystem;
   return(s);
}
[VBScript]
Function ShowFileSystemType(drvspec)
   Dim fso,d
   Set fso = CreateObject("Scripting.FileSystemObject")
   Set d = fso.GetDrive(drvspec)
   ShowFileSystemType = d.FileSystem
End Function

See Also

AvailableSpace Property | DriveLetter Property | DriveType Property | FreeSpace Property | IsReady Property | Path Property | RootFolder Property | SerialNumber Property | ShareName Property | TotalSize Property | VolumeName Property

Applies To: Drive Object


FreeSpace Property

Returns the amount of free space available to a user on the specified drive or network share. Read-only.

object.FreeSpace

The object is always a Drive object.

Remarks

The value returned by the FreeSpace property is typically the same as that returned by the AvailableSpace property. Differences may occur between the two for computer systems that support quotas.

The following code illustrates the use of the FreeSpace property:

[JScript]
function ShowFreeSpace(drvPath)
{
   var fso, d, s;
   fso = new ActiveXObject("Scripting.FileSystemObject");
   d = fso.GetDrive(fso.GetDriveName(drvPath));
   s = "Drive " + drvPath.toUpperCase( ) + " - ";
   s += d.VolumeName + "<br>";
   s += "Free Space: " + d.FreeSpace/1024 + " Kbytes";
   return(s);
}
[VBScript]
Function ShowFreeSpace(drvPath)
   Dim fso, d, s
   Set fso = CreateObject("Scripting.FileSystemObject")
   Set d = fso.GetDrive(fso.GetDriveName(drvPath))
   s = "Drive " & UCase(drvPath) & " - "
   s = s & d.VolumeName   & "<BR>"
   s = s & "Free Space: " & FormatNumber(d.FreeSpace/1024, 0)
   s = s & " Kbytes"
   ShowFreeSpace = s
End Function

See Also

AvailableSpace Property | DriveLetter Property | DriveType Property | FileSystem Property | IsReady Property | Path Property | RootFolder Property | SerialNumber Property | ShareName Property | TotalSize Property | VolumeName Property

Applies To: Drive Object


IsReady Property

Returns True if the specified drive is ready; False if it is not.

object.IsReady

The object is always a Drive object.

Remarks

For removable-media drives and CD-ROM drives, IsReady returns True only when the appropriate media is inserted and ready for access.

The following code illustrates the use of the IsReady property:

[JScript]
function ShowDriveInfo(drvpath)
{
   var fso, d, s, t;
   fso = new ActiveXObject("Scripting.FileSystemObject")
   d = fso.GetDrive(drvpath)
   switch (d.DriveType)
   {
      case 0: t = "Unknown"; break;
      case 1: t = "Removable"; break;
      case 2: t = "Fixed"; break;
      case 3: t = "Network"; break;
      case 4: t = "CD-ROM"; break;
      case 5: t = "RAM Disk"; break;
   }
   s = "Drive " + d.DriveLetter + ": - " + t;
   if (d.IsReady)
      s += "<br>" + "Drive is Ready.";
   else
      s += "<br>" + "Drive is not Ready.";
   return(s);
}
[VBScript]
Function ShowDriveInfo(drvpath)
   Dim fso, d, s, t
   Set fso = CreateObject("Scripting.FileSystemObject")
   Set d = fso.GetDrive(drvpath)
   Select Case d.DriveType
      Case 0: t = "Unknown"
      Case 1: t = "Removable"
      Case 2: t = "Fixed"
      Case 3: t = "Network"
      Case 4: t = "CD-ROM"
      Case 5: t = "RAM Disk"
   End Select
   s = "Drive " & d.DriveLetter & ": - " & t
   If d.IsReady Then
      s = s & "<BR>" & "Drive is Ready."
   Else
      s = s & "<BR>" & "Drive is not Ready."
   End If
   ShowDriveInfo = s
End Function

See Also

AvailableSpace Property | DriveLetter Property | DriveType Property | FileSystem Property | FreeSpace Property | Path Property | RootFolder Property | SerialNumber Property | ShareName Property | TotalSize Property | VolumeName Property

Applies To: Drive Object


IsRootFolder Property

Returns True if the specified folder is the root folder; False if it is not.

object.IsRootFolder

The object is always a Folder object.

Remarks

The following code illustrates the use of the IsRootFolder property:

[JScript]
function DisplayLevelDepth(pathspec)
{
   var fso, f, n, s = "";
   fso = new ActiveXObject("Scripting.FileSystemObject");
   f = fso.GetFolder(pathspec);
   n = 0;
   if (f.IsRootFolder)
      s = "The specified folder is the root folder."
   else
   {
      do
      {
         f = f.ParentFolder;
         n++;
      }
      while (!f.IsRootFolder)
      s = "The specified folder is nested " + n + " levels deep."
   }
   return(s);
}
[VBScript]
Function DisplayLevelDepth(pathspec)
   Dim fso, f, n
   Set fso = CreateObject("Scripting.FileSystemObject")
   Set f = fso.GetFolder(pathspec)
   If f.IsRootFolder Then
      DisplayLevelDepth = "The specified folder is the root folder."
   Else
      Do Until f.IsRootFolder
         Set f = f.ParentFolder
         n = n + 1
      Loop
      DisplayLevelDepth = "The specified folder is nested " & n & " levels deep."
   End If
End Function

See Also

Attributes Property | DateCreated Property | DateLastAccessed Property | DateLastModified Property | Drive Property | Files Property | Name Property | ParentFolder Property | Path Property | ShortName Property | ShortPath Property | Size Property | SubFolders Property | Type Property

Applies To: Folder Object


Line Property

Read-only property that returns the current line number in a TextStream file.

object.Line

The object is always the name of a TextStream object.

Remarks

After a file is initially opened and before anything is written, Line is equal to 1.

The following example illustrates the use of the Line property:

[JScript]
function GetLine()
{
   var fso, f, r
   var ForReading = 1, ForWriting = 2;
   fso = new ActiveXObject("Scripting.FileSystemObject")
   f = fso.OpenTextFile("c:\\textfile.txt", ForWriting, true)
   f.WriteLine("Hello world!");
   f.WriteLine("JScript is fun");
   f.Close();
   f = fso.OpenTextFile("c:\\textfile.txt", ForReading);
   r =   f.ReadAll();
   return(f.Line);
}
[VBScript]
Function GetLine
   Const ForReading = 1, ForWriting = 2
   Dim fso, f, ra
   Set fso = CreateObject("Scripting.FileSystemObject")
   Set f = fso.OpenTextFile("c:\testfile.txt", ForWriting, True)
   f.Write "Hello world!" & vbCrLf & "VB Script is fun!" & vbCrLf
   Set f = fso.OpenTextFile("c:\testfile.txt", ForReading)
   ra =   f.ReadAll
   GetLine = f.Line
End Function

See Also

Column Property

Applies To: TextStream Object


Name Property

Sets or returns the name of a specified file or folder. Read/write.

object.Name [= newname]

Arguments

object
Required. Always the name of a File or Folder object.
newname
Optional. If provided, newname is the new name of the specified object.

Remarks

The following code illustrates the use of the Name property:

[JScript]
function ShowFileAccessInfo(filespec)
{
   var fso, f, s;
   fso = new ActiveXObject("Scripting.FileSystemObject");
   f = fso.GetFile(filespec);
   s = f.Name + " on Drive " + f.Drive + "<br>";
   s += "Created: " + f.DateCreated + "<br>";
   s += "Last Accessed: " + f.DateLastAccessed + "<br>";
   s += "Last Modified: " + f.DateLastModified;
   return(s);
}
[VBScript]
Function ShowFileAccessInfo(filespec)
   Dim fso, f, s
   Set fso = CreateObject("Scripting.FileSystemObject")
   Set f = fso.GetFile(filespec)
   s = f.Name & " on Drive " & UCase(f.Drive) & "<BR>"
   s = s & "Created: " & f.DateCreated & "<BR>"
   s = s & "Last Accessed: " & f.DateLastAccessed & "<BR>"
   s = s & "Last Modified: " & f.DateLastModified
   ShowFileAccessInfo = s
End Function

See Also

Attributes Property | DateCreated Property | DateLastAccessed Property | DateLastModified Property | Drive Property | Files Property | IsRootFolder Property | ParentFolder Property | Path Property | ShortName Property | ShortPath Property | Size Property | SubFolders Property | Type Property

Applies To: File Object | Folder Object


ParentFolder Property

Returns the folder object for the parent of the specified file or folder. Read-only.

object.ParentFolder

The object is always a File or Folder object.

Remarks

The following code illustrates the use of the ParentFolder property with a file:

[JScript]
function ShowFileAccessInfo(filespec)
{
   var fso, f, s;
   fso = new ActiveXObject("Scripting.FileSystemObject");
   f = fso.GetFile(filespec);
   s = f.Name + " in " + f.ParentFolder + "<br>";
   s += "Created: " + f.DateCreated + "<br>";
   s += "Last Accessed: " + f.DateLastAccessed + "<br>";
   s += "Last Modified: " + f.DateLastModified;
   return(s);
}
[VBScript]
Function ShowFileAccessInfo(filespec)
   Dim fso, f, s
   Set fso = CreateObject("Scripting.FileSystemObject")
   Set f = fso.GetFile(filespec)
   s = UCase(f.Name) & " in " & UCase(f.ParentFolder) & "<BR>"
   s = s & "Created: " & f.DateCreated & "<BR>"
   s = s & "Last Accessed: " & f.DateLastAccessed & "<BR>"
   s = s & "Last Modified: " & f.DateLastModified
   ShowFileAccessInfo = s
End Function

See Also

Attributes Property | DateCreated Property | DateLastAccessed Property | DateLastModified Property | Drive Property | Files Property | IsRootFolder Property | Name Property | Path Property | ShortName Property | ShortPath Property | Size Property | SubFolders Property | Type Property

Applies To: File Object | Folder Object


Path Property

Returns the path for a specified file, folder, or drive.

object.Path

The object is always a File, Folder, or Drive object.

Remarks

For drive letters, the root drive is not included. For example, the path for the C drive is C:, not C:\.

The following code illustrates the use of the Path property with a File object:

[JScript]
function ShowFileAccessInfo(filespec)
{
   var fso, d, f, s;
   fso = new ActiveXObject("Scripting.FileSystemObject");
   f = fso.GetFile(filespec);
   s = f.Path.toUpperCase() + "<br>";
   s += "Created: " + f.DateCreated + "<br>";
   s += "Last Accessed: " + f.DateLastAccessed + "<br>";
   s += "Last Modified: " + f.DateLastModified
   return(s);
}
[VBScript]
Function ShowFileAccessInfo(filespec)
   Dim fso, d, f, s
   Set fso = CreateObject("Scripting.FileSystemObject")
   Set f = fso.GetFile(filespec)
   s = UCase(f.Path) & "<BR>"
   s = s & "Created: " & f.DateCreated & "<BR>"
   s = s & "Last Accessed: " & f.DateLastAccessed & "<BR>"
   s = s & "Last Modified: " & f.DateLastModified
   ShowFileAccessInfo = s
End Function

See Also

Attributes Property | AvailableSpace Property | DateCreated Property | DateLastAccessed Property | DateLastModified Property | Drive Property | DriveLetter Property | DriveType Property | Files Property | FileSystem Property | FreeSpace Property | IsReady Property | IsRootFolder Property | Name Property | ParentFolder Property | RootFolder Property | SerialNumber Property | ShareName Property | ShortName Property | ShortPath Property | Size Property | SubFolders Property | TotalSize Property | Type Property | VolumeName Property

Applies To: Drive Object | File Object | Folder Object


RootFolder Property

Returns a Folder object representing the root folder of a specified drive. Read-only.

object.RootFolder

The object is always a Drive object.

Remarks

All the files and folders contained on the drive can be accessed using the returned Folder object.

The following example illustrates the use of the RootFolder property:

[JScript]
function GetRootFolder(drv)
{
   var fso,d;
   fso = new ActiveXObject("Scripting.FileSystemObject");
   if (fso.DriveExists(drv))
      {
         d = fso.GetDrive(drv);
         return(d.RootFolder);
      }
   else
      return(false);
}
[VBScript]
Function ShowRootFolder(drvspec)
   Dim fso, f
   Set fso = CreateObject("Scripting.FileSystemObject")
   Set f = fso.GetDrive(drvspec)
   ShowRootFolder = f.RootFolder
End Function

See Also

AvailableSpace Property | DriveLetter Property | DriveType Property | FileSystem Property | FreeSpace Property | IsReady Property | Path Property | SerialNumber Property | ShareName Property | TotalSize Property | VolumeName Property

Applies To: Drive Object


SerialNumber Property

Returns the decimal serial number used to uniquely identify a disk volume.

object.SerialNumber

The object is always a Drive object.

Remarks

You can use the SerialNumber property to ensure that the correct disk is inserted in a drive with removable media.

The following code illustrates the use of the SerialNumber property:

[JScript]
function ShowDriveInfo(drvpath){
  var fso, d, s, t;
  fso = new ActiveXObject("Scripting.FileSystemObject");
  d = fso.GetDrive(fso.GetDriveName(fso.GetAbsolutePathName(drvpath)));
  switch (d.DriveType)
  {
    case 0: t = "Unknown"; break;
    case 1: t = "Removable"; break;
    case 2: t = "Fixed"; break;
    case 3: t = "Network"; break;
    case 4: t = "CD-ROM"; break;
    case 5: t = "RAM Disk"; break;
  }
  s = "Drive " + d.DriveLetter + ": - " + t;
  s += "<br>" + "SN: " + d.SerialNumber;
  return(s);
}
[VBScript]
Function ShowDriveInfo(drvpath)
   Dim fso, d, s, t
   Set fso = CreateObject("Scripting.FileSystemObject")
   Set d = fso.GetDrive(fso.GetDriveName(fso.GetAbsolutePathName(drvpath)))
   Select Case d.DriveType
      Case 0: t = "Unknown"
      Case 1: t = "Removable"
      Case 2: t = "Fixed"
      Case 3: t = "Network"
      Case 4: t = "CD-ROM"
      Case 5: t = "RAM Disk"
   End Select
   s = "Drive " & d.DriveLetter & ": - " & t
   s = s & "<BR>" & "SN: " & d.SerialNumber
   ShowDriveInfo = s
End Function


ShareName Property

Returns the network share name for a specified drive.

object.ShareName

The object is always a Drive object.

Remarks

If object is not a network drive, the ShareName property returns a zero-length string ("").

The following code illustrates the use of the ShareName property:

[JScript]
function ShowDriveInfo(drvpath)
{
   var fso, d, s;
   fso = new ActiveXObject("Scripting.FileSystemObject");
   d = fso.GetDrive(fso.GetDriveName(fso.GetAbsolutePathName(drvpath)));
   s = "Drive " + d.DriveLetter + ": - " + d.ShareName;
   return(s);
}
[VBScript]
Function ShowDriveInfo(drvpath)
   Dim fso, d
   Set fso = CreateObject("Scripting.FileSystemObject")
   Set d = fso.GetDrive(fso.GetDriveName(fso.GetAbsolutePathName(drvpath)))
   ShowDriveInfo = "Drive " & d.DriveLetter & ": - " & d.ShareName
End Function

See Also

AvailableSpace Property | DriveLetter Property | DriveType Property | FileSystem Property | FreeSpace Property | IsReady Property | Path Property | RootFolder Property | SerialNumber Property | TotalSize Property | VolumeName Property

Applies To: Drive Object


ShortName Property

Returns the short name used by programs that require the earlier 8.3 naming convention.

object.ShortName

The object is always a File or Folder object.

Remarks

The following code illustrates the use of the ShortName property with a File object:

[JScript]
function ShowShortName(filespec)
{
   var fso, f, s;
   fso = new ActiveXObject("Scripting.FileSystemObject");
   f = fso.GetFile(filespec);
   s = "The short name for " + "" + f.Name;
   s += "" + "<br>";
   s += "is: " + "" + f.ShortName + "";
   return(s);
}
[VBScript]
Function ShowShortName(filespec)
   Dim fso, f, s
   Set fso = CreateObject("Scripting.FileSystemObject")
   Set f = fso.GetFile(filespec)
   s = "The short name for "   & UCase(f.Name) & "<BR>"
   s = s & "is: " & f.ShortName
   ShowShortName = s
End Function

See Also

Attributes Property | DateCreated Property | DateLastAccessed Property | DateLastModified Property | Drive Property | Files Property | IsRootFolder Property | Name Property | ParentFolder Property | Path Property | ShortPath Property | Size Property | SubFolders Property | Type Property

Applies To: File Object | Folder Object


ShortPath Property

Returns the short path used by programs that require the earlier 8.3 file naming convention.

object.ShortPath

The object is always a File or Folder object.

Remarks

The following code illustrates the use of the ShortName property with a File object:

[JScript]
function ShowShortPath(filespec)
{
   var fso, f, s;
   fso = new ActiveXObject("Scripting.FileSystemObject");
   f = fso.GetFile(filespec);
   s = "The short path for " + "" + f.Name;
   s += "" + "<br>";
   s += "is: " + "" + f.ShortPath + "";
   return(s);
}
[VBScript]
Function ShowShortName(filespec)
   Dim fso, f, s
   Set fso = CreateObject("Scripting.FileSystemObject")
   Set f = fso.GetFile(filespec)
   s = "The short name for "   & UCase(f.Name) & "<BR>"
   s = s & "is: " & f.ShortName
   ShowShortName = s
End Function

See Also

Attributes Property | DateCreated Property | DateLastAccessed Property | DateLastModified Property | Drive Property | Files Property | IsRootFolder Property | Name Property | ParentFolder Property | Path Property | ShortName Property | Size Property | SubFolders Property | Type Property

Applies To: File Object | Folder Object


Size Property

For files, returns the size, in bytes, of the specified file. For folders, returns the size, in bytes, of all files and subfolders contained in the folder.

object.Size

The object is always a File or Folder object.

Remarks

The following code illustrates the use of the Size property with a Folder object:

[JScript]
function ShowFolderSize(filespec)
{
   var fso, f, s;
   fso = new ActiveXObject("Scripting.FileSystemObject");
   f = fso.GetFolder(filespec);
   s = f.Name + " uses " + f.size + " bytes.";
   return(s);
}
[VBScript]
 Function ShowFolderSize(filespec)
   Dim fso, f, s
   Set fso = CreateObject("Scripting.FileSystemObject")
   Set f = fso.GetFolder(filespec)
   s = UCase(f.Name) & " uses " & f.size & " bytes."
   ShowFolderSize = s
End Function

See Also

Attributes Property | DateCreated Property | DateLastAccessed Property | DateLastModified Property | Drive Property | Files Property | IsRootFolder Property | Name Property | ParentFolder Property | Path Property | ShortName Property | ShortPath Property | SubFolders Property | Type Property

Applies To: File Object | Folder Object


SubFolders Property

Returns a Folders collection consisting of all folders contained in a specified folder, including those with hidden and system file attributes set.

object.SubFolders

The object is always a Folder object.

Remarks

The following code illustrates the use of the SubFolders property:

[JScript]
function ShowFolderList(folderspec)
{
   var fso, f, fc, s;
   fso = new ActiveXObject("Scripting.FileSystemObject");
   f = fso.GetFolder(folderspec);
   fc = new Enumerator(f.SubFolders);
   s = "";
   for (;!fc.atEnd(); fc.moveNext())
      {
         s += fc.item();
         s += "<br>";
      }
      return(s);
}
[VBScript]
Function ShowFolderList(folderspec)
   Dim fso, f, f1, s, sf
   Set fso = CreateObject("Scripting.FileSystemObject")
   Set f = fso.GetFolder(folderspec)
   Set sf = f.SubFolders
   For Each f1 in sf
      s = s & f1.name
      s = s & "<BR>"
   Next
   ShowFolderList = s
End Function

See Also

Attributes Property | DateCreated Property | DateLastAccessed Property | DateLastModified Property | Drive Property | Files Property | IsRootFolder Property | Name Property | ParentFolder Property | Path Property | ShortName Property | ShortPath Property | Size Property | Type Property

Applies To: Folder Object


TotalSize Property

Returns the total space, in bytes, of a drive or network share.

object.TotalSize

The object is always a Drive object.

Remarks

The following code illustrates the use of the TotalSize property:

[JScript]
function SpaceReport(drvPath)
{
   var fso, d, s;
   fso = new ActiveXObject("Scripting.FileSystemObject");
   d = fso.GetDrive(fso.GetDriveName(drvPath));
   s = "Drive " + drvPath + " - ";
   s += d.VolumeName + "<br>";
   s += "Total Space: "+ d.TotalSize/1024 + " Kbytes <br>";
   s += "Free Space:   " + d.FreeSpace/1024 + " Kbytes";
   return(s);
}
[VBScript]
Function ShowSpaceInfo(drvpath)
   Dim fso, d, s
   Set fso = CreateObject("Scripting.FileSystemObject")
   Set d = fso.GetDrive(fso.GetDriveName(fso.GetAbsolutePathName(drvpath)))
   s = "Drive " & d.DriveLetter & ":"
   s = s & vbCrLf
   s = s & "Total Size: " & FormatNumber(d.TotalSize/1024, 0) & " Kbytes"
   s = s & vbCrLf
   s = s & "Available: " & FormatNumber(d.AvailableSpace/1024, 0) & " Kbytes"
   ShowSpaceInfo = s
End Function

See Also

AvailableSpace Property | DriveLetter Property | DriveType Property | FileSystem Property | FreeSpace Property | IsReady Property | Path Property | RootFolder Property | SerialNumber Property | ShareName Property | VolumeName Property

Applies To: Drive Object


Type Property

Returns information about the type of a file or folder. For example, for files ending in .TXT, "Text Document" is returned.

object.Type

The object is always a File or Folder object.

Remarks

The following code illustrates the use of the Type property to return a folder type. In this example, try providing the path of the Recycle Bin or other unique folder to the procedure.

[JScript]
function ShowFileType(filespec)
{
   var fso, f, s;
   fso = new ActiveXObject("Scripting.FileSystemObject");
   if (fso.FolderExists(filespec))
      f = fso.GetFolder(filespec);
   else if (fso.FileExists(filespec))
      f = fso.GetFile(filespec);
   else
      s = "File or Folder does not exist.";
   s = f.Name + " is a " + f.Type;
   return(s);
}
[VBScript]
Function ShowFolderType(filespec)
   Dim fso, f, s
   Set fso = CreateObject("Scripting.FileSystemObject")
   Set f = fso.GetFolder(filespec)
   s = UCase(f.Name) & " is a " & f.Type
   ShowFolderType = s
End Function

See Also

Attributes Property | DateCreated Property | DateLastAccessed Property | DateLastModified Property | Drive Property | Files Property | IsRootFolder Property | Name Property | ParentFolder Property | Path Property | ShortName Property | ShortPath Property | Size Property | SubFolders Property

Applies To: File Object | Folder Object


VolumeName Property

Sets or returns the volume name of the specified drive. Read/write.

object.VolumeName [= newname]

Arguments

object
Required. Always the name of a Drive object.
newname
Optional. If provided, newname is the new name of the specified object.

Remarks

The following code illustrates the use of the VolumeName property:

[JScript]
function SpaceReport(drvPath)
{
   var fso, d, s;
   fso = new ActiveXObject("Scripting.FileSystemObject");
   d = fso.GetDrive(fso.GetDriveName(drvPath));
   s = "Drive " + drvPath + " - ";
   s += d.VolumeName + "<br>";
   s += "Total Space: "+ d.TotalSize/1024 + " Kbytes <br>";
   s += "Free Space:   " + d.FreeSpace/1024 + " Kbytes";
   return(s);
}
[VBScript]
Function ShowVolumeInfo(drvpath)
   Dim fso, d, s
   Set fso = CreateObject("Scripting.FileSystemObject")
   Set d = fso.GetDrive(fso.GetDriveName(fso.GetAbsolutePathName(drvpath)))
   s = "Drive " & d.DriveLetter & ": - " & d.VolumeName
   ShowVolumeInfo = s
End Function

See Also

AvailableSpace Property | DriveLetter Property | DriveType Property | FileSystem Property | FreeSpace Property | IsReady Property | Path Property | RootFolder Property | SerialNumber Property | ShareName Property | TotalSize Property

Applies To: Drive Object


FileSystemObject Methods

In This Section

Add Method (Dictionary)
Adds a key and item pair to a Dictionary object.
Add Method (Folders)
Adds a new folder to a Folders collection.
BuildPath Method
Appends a name to an existing path.
Close Method
Closes an open TextStream file.
Copy Method
Copies a specified file or folder from one location to another.
CopyFile Method
Copies one or more files from one location to another.
CopyFolder Method
Recursively copies a folder from one location to another.
CreateFolder Method
Creates a folder.
CreateTextFile Method
Creates a specified file name and returns a TextStream object that can be used to read from or write to the file.
Delete Method
Deletes a specified file or folder.
DeleteFile Method
Deletes a specified file.
DeleteFolder Method
Deletes a specified folder and its contents.
DrivesExists Method
Returns true if the specified drive exists; false if it does not.
Exists Method
Returns true if a specified key exists in the Dictionary object, false if it does not.
FileExists Method
Returns true if a specified file exists; false if it does not.
FolderExists Method
Returns true if a specified folder exists; false if it does not.
GetAbsolutePathName Method
Returns a complete and unambiguous path from a provided path specification.
GetBaseName Method
Returns a string containing the base name of the last component, less any file extension, in a path.
GetDrive Method
Returns a Drive object corresponding to the drive in a specified path.
GetDriveName Method
Returns a string containing the name of the drive for a specified path.
GetExtensionName Method
Returns a string containing the extension name for the last component in a path.
GetFile Method
Returns a File object corresponding to the file in a specified path.
GetFileName Method
Returns the last component of specified path that is not part of the drive specification.
GetFileVersion Method
Returns the version number of a specified file.
GetFolder Method
Returns a Folder object corresponding to the folder in a specified path.
GetParentFolderName Method
Returns a string containing the name of the parent folder of the last component in a specified path.
GetSpecialFolder Method
Returns the special folder object specified.
GetTempName Method
Returns a randomly generated temporary file or folder name that is useful for performing operations that require a temporary file or folder.
Items Method
Returns an array containing all the items in a Dictionary object.
Keys Method
Returns an array containing all existing keys in a Dictionary object.
Move Method
Moves a specified file or folder from one location to another.
MoveFile Method
Moves one or more files from one location to another.
MoveFolder Method
Moves one or more folders from one location to another.
OpenAsTextStream Method
Opens a specified file and returns a TextStream object that can be used to read from, write to, or append to the file.
OpenTextFile Method
Opens a specified file and returns a TextStream object that can be used to read from, write to, or append to the file.
Read Method
Reads a specified number of characters from a TextStream file and returns the resulting string.
ReadAll Method
Reads an entire TextStream file and returns the resulting string.
ReadLine Method
Reads an entire line (up to, but not including, the newline character) from a TextStream file and returns the resulting string.
Remove Method
Removes a key, item pair from a Dictionary object.
RemoveAll Method
Removes all key, item pairs from a Dictionary object.
Skip Method
Skips a specified number of characters when reading a TextStream file.
SkipLine
Skips the next line when reading a TextStream file.
Write Method
Writes a specified string to a TextStream file.
WriteBlankLines Method
Writes a specified number of newline characters to a TextStream file.
WriteLine Method
Writes a specified string and newline character to a TextStream file.

Related Sections

Scripting Run-Time Reference
List of elements that make up Scripting Run-Time Reference.
FileSystemObject Basics
A guide to the fundamentals of the FileSystemObject.


Add Method (Folders)

Adds a new folder to a Folders collection.

object.Add (folderName)

Arguments

object
Required. Always the name of a Folders collection.
folderName
Required. The name of the new Folder being added.

Remarks

The following example illustrates the use of the Add method to create a new folder.

[JScript]
function AddNewFolder(path,folderName)
{
   var fso, f, fc, nf;
   fso = new ActiveXObject("Scripting.FileSystemObject");
   f = fso.GetFolder(path);
   fc = f.SubFolders;
   if (folderName != "" )
      nf = fc.Add(folderName);
   else
      nf = fc.Add("New Folder");
}
[VBScript]
Sub AddNewFolder(path, folderName)
   Dim fso, f, fc, nf
   Set fso = CreateObject("Scripting.FileSystemObject")
   Set f = fso.GetFolder(path)
   Set fc = f.SubFolders
   If folderName <> "" Then
      Set nf = fc.Add(folderName)
   Else
      Set nf = fc.Add("New Folder")
   End If
End Sub

An error occurs if the folderName already exists.

See Also

Add Method (Dictionary)
Applies To: Folders Collection


BuildPath Method

Appends a name to an existing path.

object.BuildPath(path, name)

Arguments

object
Required. Always the name of a FileSystemObject.
path
Required. Existing path to which name is appended. Path can be absolute or relative and need not specify an existing folder.
name
Required. Name being appended to the existing path.

Remarks

The BuildPath method inserts an additional path separator between the existing path and the name, only if necessary.

The following example illustrates use of the BuildPath method.

[JScript]
function GetBuildPath(path)
{
   var fso, newpath;
   fso = new ActiveXObject("Scripting.FileSystemObject");
   newpath = fso.BuildPath(path, "New   Folder");
   return(newpath);
}
[VBScript]
Function GetBuildPath(path)
   Dim fso, newpath
   Set fso = CreateObject("Scripting.FileSystemObject")
   newpath = fso.BuildPath(path, "Sub Folder")
   GetBuildPath = newpath
End Function

See Also

GetAbsolutePathName Method | GetBaseName Method | GetDriveName Method | GetExtensionName Method | GetFileName Method | GetParentFolderName Method | GetTempName Method
Applies To: FileSystemObject Object


Close Method

Closes an open TextStream file.

object.Close( );

The object is always the name of a TextStream object.

Remarks

The following example illustrates use of the Close method.

[JScript]
var fso;
fso = new ActiveXObject("Scripting.FileSystemObject");
a = fso.CreateTextFile("c:\\testfile.txt", true);
a.WriteLine("This is a test.");
a.Close();
[VBScript]
Sub CreateAFile
   Dim fso, MyFile
   Set fso = CreateObject("Scripting.FileSystemObject")
   Set MyFile = fso.CreateTextFile("c:\testfile.txt", True)
   MyFile.WriteLine("This is a test.")
   MyFile.Close
End Sub


Copy Method

Copies a specified file or folder from one location to another.

object.Copy( destination[, overwrite] );

Arguments

object
Required. Always the name of a File or Folder object.
destination
Required. Destination where the file or folder is to be copied. Wildcard characters are not allowed.
overwrite
Optional. Boolean value that is True (default) if existing files or folders are to be overwritten; False if they are not.

Remarks

The results of the Copy method on a File or Folder are identical to operations performed using FileSystemObject.CopyFile or FileSystemObject.CopyFolder where the file or folder referred to by object is passed as an argument. You should note, however, that the alternative methods are capable of copying multiple files or folders.

Example

The following example illustrates the use of the Copy method.

[JScript]
var fso, f;
fso = new ActiveXObject("Scripting.FileSystemObject");
f = fso.CreateTextFile("c:\\testfile.txt", true);
f.WriteLine("This is a test.");
f.Close();
f = fso.GetFile("c:\\testfile.txt");
f.Copy("c:\\windows\\desktop\\test2.txt");
[VBScript]
Dim fso, MyFile
Set fso = CreateObject("Scripting.FileSystemObject")
Set MyFile = fso.CreateTextFile("c:\testfile.txt", True)
MyFile.WriteLine("This is a test.")
MyFile.Close
Set MyFile = fso.GetFile("c:\testfile.txt")
MyFile.Copy ("c:\windows\desktop\test2.txt")

See Also

CopyFile Method | CopyFolder Method | Delete Method | Move Method | OpenAsTextStream Method
Applies To: File Object | Folder Object


CopyFile Method

Copies one or more files from one location to another.

object.CopyFile ( source, destination[, overwrite] )

Arguments

object
Required. The object is always the name of a FileSystemObject.
source
Required. Character string file specification, which can include wildcard characters, for one or more files to be copied.
destination
Required. Character string destination where the file or files from source are to be copied. Wildcard characters are not allowed.
overwrite
Optional. Boolean value that indicates if existing files are to be overwritten. If true, files are overwritten; if false, they are not. The default is true. Note that CopyFile will fail if destination has the read-only attribute set, regardless of the value of overwrite.

Remarks

Wildcard characters can only be used in the last path component of the source argument. For example, you can use:

[JScript]
fso = new ActiveXObject("Scripting.FileSystemObject");
fso.CopyFile ("c:\\mydocuments\\letters\\*.doc", "c:\\tempfolder\\")
[VBScript]
FileSystemObject.CopyFile "c:\mydocuments\letters\*.doc", "c:\tempfolder\"

But you cannot use:

[JScript]
fso = new ActiveXObject("Scripting.FileSystemObject");
fso.CopyFile ("c:\\mydocuments\\*\\R1???97.xls", "c:\\tempfolder")
[VBScript]
FileSystemObject.CopyFile "c:\mydocuments\*\R1???97.xls", "c:\tempfolder"

If source contains wildcard characters or destination ends with a path separator (\), it is assumed that destination is an existing folder in which to copy matching files. Otherwise, destination is assumed to be the name of a file to create. In either case, three things can happen when an individual file is copied.

  • If destination does not exist, source gets copied. This is the usual case.
  • If destination is an existing file, an error occurs if overwrite is false. Otherwise, an attempt is made to copy source over the existing file.
  • If destination is a directory, an error occurs.

An error also occurs if a source using wildcard characters doesn't match any files. The CopyFile method stops on the first error it encounters. No attempt is made to roll back or undo any changes made before an error occurs.

See Also

Copy Method | CopyFolder Method | CreateTextFile Method | DeleteFile Method | MoveFile Method
Applies To: FileSystemObject Object


CopyFolder Method

Recursively copies a folder from one location to another.

object.CopyFolder ( source, destination[, overwrite] );

Arguments

object
Required. Always the name of a FileSystemObject.
source
Required. Character string folder specification, which can include wildcard characters, for one or more folders to be copied.
destination
Required. Character string destination where the folder and subfolders from source are to be copied. Wildcard characters are not allowed.
overwrite
Optional. Boolean value that indicates if existing folders are to be overwritten. If true, files are overwritten; if false, they are not. The default is true.

Remarks

Wildcard characters can only be used in the last path component of the source argument. For example, you can use:

[JScript]
fso = new ActiveXObject("Scripting.FileSystemObject");
fso.CopyFolder ("c:\\mydocuments\\letters\\*", "c:\\tempfolder\\")
[VBScript]
FileSystemObject.CopyFolder "c:\mydocuments\letters\*", "c:\tempfolder\"

But you cannot use:

[JScript]
fso = new ActiveXObject("Scripting.FileSystemObject");
fso.CopyFolder ("c:\\mydocuments\\*\\*", "c:\\tempfolder\\")
[VBScript]
FileSystemObject.CopyFolder "c:\mydocuments\*\*", "c:\tempfolder\"

If source contains wildcard characters or destination ends with a path separator (\), it is assumed that destination is an existing folder in which to copy matching folders and subfolders. Otherwise, destination is assumed to be the name of a folder to create. In either case, four things can happen when an individual folder is copied.

  • If destination does not exist, the source folder and all its contents gets copied. This is the usual case.
  • If destination is an existing file, an error occurs.
  • If destination is a directory, an attempt is made to copy the folder and all its contents. If a file contained in source already exists in destination, an error occurs if overwrite is false. Otherwise, it will attempt to copy the file over the existing file.
  • If destination is a read-only directory, an error occurs if an attempt is made to copy an existing read-only file into that directory and overwrite is false.

An error also occurs if a source using wildcard characters doesn't match any folders.

The CopyFolder method stops on the first error it encounters. No attempt is made to roll back any changes made before an error occurs.

See Also

CopyFile Method | Copy Method | CreateFolder Method | DeleteFolder Method | MoveFolder Method
Applies To: FileSystemObject Object


CreateFolder Method

Creates a folder.

object.CreateFolder(foldername)

Arguments

object
Required. Always the name of a FileSystemObject.
foldername
Required. String expression that identifies the folder to create.

Remarks

An error occurs if the specified folder already exists.

The following code illustrates how to use the CreateFolder method to create a folder.

[JScript]
var fso = new ActiveXObject("Scripting.FileSystemObject");
var a = fso.CreateFolder("c:\\new folder");
[VBScript]
Function CreateFolderDemo
   Dim fso, f
   Set fso = CreateObject("Scripting.FileSystemObject")
   Set f = fso.CreateFolder("c:\New Folder")
   CreateFolderDemo = f.Path
End Function

See Also

CopyFolder Method | DeleteFolder Method | MoveFolder Method
Applies To: FileSystemObject Object


CreateTextFile Method

Creates a specified file name and returns a TextStream object that can be used to read from or write to the file.

object.CreateTextFile(filename[, overwrite[, unicode]])

Arguments

object
Required. Always the name of a FileSystemObject or Folder object.
filename
Required. String expression that identifies the file to create.
overwrite
Optional. Boolean value that indicates whether you can overwrite an existing file. The value is true if the file can be overwritten, false if it can't be overwritten. If omitted, existing files are not overwritten.
unicode
Optional. Boolean value that indicates whether the file is created as a Unicode or ASCII file. The value is true if the file is created as a Unicode file, false if it's created as an ASCII file. If omitted, an ASCII file is assumed.

Remarks

The following code illustrates how to use the CreateTextFile method to create and open a text file.

[JScript]
var fso = new ActiveXObject("Scripting.FileSystemObject");
var a = fso.CreateTextFile("c:\\testfile.txt", true);
a.WriteLine("This is a test.");
a.Close();
[VBScript]
Sub CreateAfile
   Dim fso, MyFile
   Set fso = CreateObject("Scripting.FileSystemObject")
   Set MyFile = fso.CreateTextFile("c:\testfile.txt", True)
   MyFile.WriteLine("This is a test.")
   MyFile.Close
End Sub

If the overwrite argument is false, or is not provided, for a filename that already exists, an error occurs.

See Also

CreateFolder Method | OpenAsTextStream Method | OpenTextFile Method
Applies To: FileSystemObject Object | Folder Object


DateCreated Property

Returns the date and time that the specified file or folder was created. Read-only.

object.DateCreated

The object is always a File or Folder object.

Remarks

The following code illustrates the use of the DateCreated property with a file:

[JScript]
function ShowFileInfo(filespec)
{
   var fso, f, s;
   fso = new ActiveXObject("Scripting.FileSystemObject");
   f = fso.GetFile(filespec);
   s = "Created: " + f.DateCreated;
   return(s);
}
[VBScript]
Function ShowFileInfo(filespec)
   Dim fso, f
   Set fso = CreateObject("Scripting.FileSystemObject")
   Set f = fso.GetFile(filespec)
   ShowFileInfo = "Created: " & f.DateCreated
End Function

See Also

Attributes Property | DateLastAccessed Property | DateLastModified Property | Drive Property | Files Property | IsRootFolder Property | Name Property | ParentFolder Property | Path Property | ShortName Property | ShortPath Property | Size Property | SubFolders Property | Type Property

Applies To: File Object | Folder Object


Delete Method

Deletes a specified file or folder.

object.Delete( force );

Arguments

object
Required. Always the name of a File or Folder object.
force
Optional. Boolean value that is True if files or folders with the read-only attribute set are to be deleted; False (default) if they are not.

Remarks

An error occurs if the specified file or folder does not exist.

The results of the Delete method on a File or Folder are identical to operations performed using FileSystemObject.DeleteFile or FileSystemObject.DeleteFolder.

The Delete method does not distinguish between folders that have contents and those that do not. The specified folder is deleted regardless of whether or not it has contents.

The following example illustrates the use of the Delete method.

[JScript]
var fso, f;
fso = new ActiveXObject("Scripting.FileSystemObject");
f = fso.CreateTextFile("c:\\testfile.txt", true);
f.WriteLine("This is a test.");
f.Close();
f = fso.GetFile("c:\\testfile.txt");
f.Delete();
[VBScript]
Dim fso, MyFile
Set fso = CreateObject("Scripting.FileSystemObject")
Set MyFile = fso.CreateTextFile("c:\testfile.txt", True)
MyFile.WriteLine("This is a test.")
MyFile.Close
Set MyFile = fso.GetFile("c:\testfile.txt")
MyFile.Delete

See Also

Copy Method | DeleteFile Method | DeleteFolder Method | Move Method | OpenAsTextStream Method
Applies To: File Object | Folder Object


DeleteFile Method

Deletes a specified file.

object.DeleteFile ( filespec[, force] );

Arguments

object
Required. Always the name of a FileSystemObject.
filespec
Required. The name of the file to delete. The filespec can contain wildcard characters in the last path component.
force
Optional. Boolean value that is true if files with the read-only attribute set are to be deleted; false (default) if they are not.

Remarks

An error occurs if no matching files are found. The DeleteFile method stops on the first error it encounters. No attempt is made to roll back or undo any changes that were made before an error occurred.

The following example illustrates the use of the DeleteFile method.

[JScript]
function DeleteFile(filespec)
{
   var fso;
   fso = new ActiveXObject("Scripting.FileSystemObject");
   fso.DeleteFile(filespec);
}
[VBScript]
Sub DeleteAFile(filespec)
   Dim fso
   Set fso = CreateObject("Scripting.FileSystemObject")
   fso.DeleteFile(filespec)
End Sub

See Also

CopyFile Method | CreateTextFile Method | Delete Method | DeleteFolder Method | MoveFile Method
Applies To: FileSystemObject Object


DeleteFolder Method

Deletes a specified folder and its contents.

object.DeleteFolder ( folderspec[, force] );

Arguments

object
Required. Always the name of a FileSystemObject.
folderspec
Required. The name of the folder to delete. The folderspec can contain wildcard characters in the last path component.
force
Optional. Boolean value that is true if folders with the read-only attribute set are to be deleted; false (default) if they are not.

Remarks

The DeleteFolder method does not distinguish between folders that have contents and those that do not. The specified folder is deleted regardless of whether or not it has contents.

An error occurs if no matching folders are found. The DeleteFolder method stops on the first error it encounters. No attempt is made to roll back or undo any changes that were made before an error occurred.

The following example illustrates the use of the DeleteFolder method.

[JScript]
function DeleteFolder(folderspec)
{
   var fso;
   fso = new ActiveXObject("Scripting.FileSystemObject");
   fso.DeleteFolder(folderspec);
}
[VBScript]
Sub DeleteAFolder(filespec)
   Dim fso
   Set fso = CreateObject("Scripting.FileSystemObject")
   fso.DeleteFolder(filespec)
End Sub

See Also

CopyFolder Method | CreateFolder Method | Delete Method | DeleteFile Method | MoveFolder Method
Applies To: FileSystemObject Object


DriveExists Method

Returns True if the specified drive exists; False if it does not.

object.DriveExists(drivespec)

Arguments

object
Required. Always the name of a FileSystemObject.
drivespec
Required. A drive letter or a complete path specification.

Remarks

For drives with removable media, the DriveExists method returns true even if there are no media present. Use the IsReady property of the Drive object to determine if a drive is ready.

The following example illustrates the use of the DriveExists method.

[JScript]
function ReportDriveStatus(drv)
{
   var fso, s = "";
   fso = new ActiveXObject("Scripting.FileSystemObject");
   if (fso.DriveExists(drv))
      s += "Drive " + drv + " exists.";
   else
      s += "Drive " + drv + " doesn't exist.";
   return(s);
}
[VBScript]
Function ReportDriveStatus(drv)
   Dim fso, msg
   Set fso = CreateObject("Scripting.FileSystemObject")
   If fso.DriveExists(drv) Then
      msg = ("Drive " & UCase(drv) & " exists.")
   Else
      msg = ("Drive " & UCase(drv) & " doesn't exist.")
   End If
   ReportDriveStatus = msg
End Function

See Also

Drive Object | Drives Collection | FileExists Method | FolderExists Method | GetDrive Method | GetDriveName Method | IsReady Property
Applies To: FileSystemObject Object


FileExists Method

Returns True if a specified file exists; False if it does not.

object.FileExists(filespec)

Arguments

object
Required. Always the name of a FileSystemObject.
filespec
Required. The name of the file whose existence is to be determined. A complete path specification (either absolute or relative) must be provided if the file isn't expected to exist in the current folder.

The following example illustrates the use of the FileExists method.

[JScript]
function ReportFileStatus(filespec)
{
   var fso, s = filespec;
   fso = new ActiveXObject("Scripting.FileSystemObject");
   if (fso.FileExists(filespec))
      s += " exists.";
   else
      s += " doesn't exist.";
   return(s);
}
[VBScript]
Function ReportFileStatus(filespec)
   Dim fso, msg
   Set fso = CreateObject("Scripting.FileSystemObject")
   If (fso.FileExists(filespec)) Then
      msg = filespec & " exists."
   Else
      msg = filespec & " doesn't exist."
   End If
   ReportFileStatus = msg
End Function

See Also

DriveExists Method | FolderExists Method | GetFile Method | GetFileName Method
Applies To: FileSystemObject Object


Files Property

Returns a Files collection consisting of all File objects contained in the specified folder, including those with hidden and system file attributes set.

object.Files

The object is always a Folder object.

Remarks

The following code illustrates the use of the Files property:

[JScript]
function ShowFolderFileList(folderspec)
{
   var fso, f, fc, s;
   fso = new ActiveXObject("Scripting.FileSystemObject");
   f = fso.GetFolder(folderspec);
   fc = new Enumerator(f.files);
   s = "";
   for (; !fc.atEnd(); fc.moveNext())
   {
      s += fc.item();
      s += "<br>";
   }
   return(s);
}
[VBScript]Function ShowFileList(folderspec)
   Dim fso, f, f1, fc, s
   Set fso = CreateObject("Scripting.FileSystemObject")
   Set f = fso.GetFolder(folderspec)
   Set fc = f.Files
   For Each f1 in fc
      s = s & f1.name
      s = s &   "<BR>"
   Next
   ShowFileList = s
End Function

See Also

Attributes Property | DateCreated Property | DateLastAccessed Property | DateLastModified Property | Drive Property | IsRootFolder Property | Name Property | ParentFolder Property | Path Property | ShortName Property | ShortPath Property | Size Property | SubFolders Property | Type Property

Applies To: Folder Object


FolderExists Method

Returns True if a specified folder exists; False if it does not.

object.FolderExists(folderspec)

Arguments

object
Required. Always the name of a FileSystemObject.
folderspec
Required. The name of the folder whose existence is to be determined. A complete path specification (either absolute or relative) must be provided if the folder isn't expected to exist in the current folder.

The following example illustrates the use of the FileExists method.

[JScript]
function ReportFolderStatus(fldr)
{
   var fso, s = fldr;
   fso = new ActiveXObject("Scripting.FileSystemObject");
   if (fso.FolderExists(fldr))
      s += " exists.";
   else
      s += " doesn't exist.";
   return(s);
}
[VBScript]
Function ReportFolderStatus(fldr)
   Dim fso, msg
   Set fso = CreateObject("Scripting.FileSystemObject")
   If (fso.FolderExists(fldr)) Then
      msg = fldr & " exists."
   Else
      msg = fldr & " doesn't exist."
   End If
   ReportFolderStatus = msg
End Function

See Also

DriveExists Method | FileExists Method | GetFolder Method | GetParentFolderName Method
Applies To: FileSystemObject Object


GetAbsolutePathName Method

Returns a complete and unambiguous path from a provided path specification.

object.GetAbsolutePathName(pathspec)

Arguments

object
Required. Always the name of a FileSystemObject.
pathspec
Required. Path specification to change to a complete and unambiguous path.

Remarks

A path is complete and unambiguous if it provides a complete reference from the root of the specified drive. A complete path can only end with a path separator character (\) if it specifies the root folder of a mapped drive.

Assuming the current directory is c:\mydocuments\reports, the following table illustrates the behavior of the GetAbsolutePathName method.

pathspec | Returned path
"c:" | "c:\mydocuments\reports"
"c:.." | "c:\mydocuments"
"c:\\" | "c:\"
"c:*.*\\may97" | "c:\mydocuments\reports\*.*\may97"
"region1" | "c:\mydocuments\reports\region1"
"c:\\..\\..\\mydocuments" | "c:\mydocuments"

The following example illustrates the use of the GetAbsolutePathName method.

function ShowAbsolutePath(path)
{
   var fso, s= "";
   fso = new ActiveXObject("Scripting.FileSystemObject");
   s += fso.GetAbsolutePathName(path);
   return(s);
}

See Also

GetBaseName Method | GetDrive Method | GetDriveName Method | GetExtensionName Method | GetFile Method | GetFileName Method | GetFileVersion Method | GetFolder Method | GetParentFolderName Method | GetSpecialFolder Method | GetTempName Method
Applies To: FileSystemObject Object


GetBaseName Method

Returns a string containing the base name of the last component, less any file extension, in a path.

object.GetBaseName(path)

Arguments

object
Required. Always the name of a FileSystemObject.
path
Required. The path specification for the component whose base name is to be returned.

Remarks

The GetBaseName method returns a zero-length string ("") if no component matches the path argument.

Note The GetBaseName method works only on the provided path string. It does not attempt to resolve the path, nor does it check for the existence of the specified path.

The following example illustrates the use of the GetBaseName method.

[JScript]
function ShowBaseName(filespec)
{
   var fso, s = "";
   fso = new ActiveXObject("Scripting.FileSystemObject");
   s += fso.GetBaseName(filespec);
   return(s);
}
[VBScript]
Function GetTheBase(filespec)
   Dim fso
   Set fso = CreateObject("Scripting.FileSystemObject")
   GetTheBase = fso.GetBaseName(filespec)
End Function

See Also

GetAbsolutePathName Method | GetDrive Method | GetDriveName Method | GetExtensionName Method | GetFile Method | GetFileName Method | GetFileVersion Method | GetFolder Method | GetParentFolderName Method | GetSpecialFolder Method | GetTempName Method
Applies To: FileSystemObject Object


GetDrive Method

Returns a Drive object corresponding to the drive in a specified path.

object.GetDrive ( drivespec );

Arguments

object
Required. Always the name of a FileSystemObject.
drivespec
Required. The drivespec argument can be a drive letter (c), a drive letter with a colon appended (c:), a drive letter with a colon and path separator appended (c:\), or any network share specification (\\computer2\share1).

Remarks

For network shares, a check is made to ensure that the share exists.

An error occurs if drivespec does not conform to one of the accepted forms or does not exist.

To call the GetDrive method on a normal path string, use the following sequence to get a string that is suitable for use as drivespec:

[JScript]
DriveSpec = GetDriveName(GetAbsolutePathName(Path))

[JScript]

The following example illustrates the use of the GetDrive method.

[JScript]
function ShowFreeSpace(drvPath)
{
   var fso, d, s ="";
   fso = new ActiveXObject("Scripting.FileSystemObject");
   d = fso.GetDrive(fso.GetDriveName(drvPath));
   s = "Drive " + drvPath.toUpperCase( ) + " - ";
   s += d.VolumeName + "<br>";
   s += "Free Space: " + d.FreeSpace/1024 + " Kbytes";
   return(s);
}
[VBScript]
DriveSpec = GetDriveName(GetAbsolutePathName(Path))

[VBScript]

The following example illustrates use of the GetDrive method:

[VBScript]
Function ShowFreeSpace(drvPath)
   Dim fso, d, s
   Set fso = CreateObject("Scripting.FileSystemObject")
   Set d = fso.GetDrive(fso.GetDriveName(drvPath))
   s = "Drive " & UCase(drvPath) & " - "
   s = s & d.VolumeName   & "<BR>"
   s = s & "Free Space: " & FormatNumber(d.FreeSpace/1024, 0)
   s = s & " Kbytes"
   ShowFreeSpace = s
End Function

See Also

GetAbsolutePathName Method | GetBaseName Method | GetDriveName Method | GetExtensionName Method | GetFile Method | GetFileName Method | GetFileVersion Method | GetFolder Method | GetParentFolderName Method | GetSpecialFolder Method | GetTempName Method
Applies To: FileSystemObject Object


GetDriveName Method

Returns a string containing the name of the drive for a specified path.

object.GetDriveName(path)

Arguments

object
Required. Always the name of a FileSystemObject.
path
Required. The path specification for the component whose drive name is to be returned.

Remarks

The GetDriveName method returns a zero-length string ("") if the drive can't be determined.

Note The GetDriveName method works only on the provided path string. It does not attempt to resolve the path, nor does it check for the existence of the specified path.

The following example illustrates the use of the GetDriveName method.

[JScript]
function GetDriveLetter(path)
{
   var fso, s ="";
   fso = new ActiveXObject("Scripting.FileSystemObject");
   s += fso.GetDrive(fso.GetDriveName(fso.GetAbsolutePathName(path)));
   return(s);
}
[VBScript]
Function GetAName(DriveSpec)
   Dim fso
   Set fso = CreateObject("Scripting.FileSystemObject")
   GetAName = fso.GetDriveName(Drivespec)
End Function

See Also

GetAbsolutePathName Method | GetBaseName Method | GetDrive Method | GetExtensionName Method | GetFile Method | GetFileName Method | GetFileVersion Method | GetFolder Method | GetParentFolderName Method | GetSpecialFolder Method | GetTempName Method
Applies To: FileSystemObject Object


GetExtensionName Method

Returns a string containing the extension name for the last component in a path.

object.GetExtensionName(path)

Arguments

object
Required. Always the name of a FileSystemObject.
path
Required. The path specification for the component whose extension name is to be returned.

Remarks

For network drives, the root directory (\) is considered to be a component.

The GetExtensionName method returns a zero-length string ("") if no component matches the path argument.

The following example illustrates the use of the GetExtensionName method.

[JScript]
function ShowExtensionName(filespec)
{
   var fso, s = "";
   fso = new ActiveXObject("Scripting.FileSystemObject");
   s += fso.GetExtensionName(filespec);
   return(s);
}
[VBScript]
Function GetAnExtension(DriveSpec)
   Dim fso
   Set fso = CreateObject("Scripting.FileSystemObject")
   GetAnExtension = fso.GetExtensionName(Drivespec)
End Function

See Also

GetAbsolutePathName Method | GetBaseName Method | GetDrive Method | GetDriveName Method | GetFile Method | GetFileName Method | GetFileVersion Method | GetFolder Method | GetParentFolderName Method | GetSpecialFolder Method | GetTempName Method
Applies To: FileSystemObject Object


GetFile Method

Returns a File object corresponding to the file in a specified path.

object.GetFile(filespec)

Arguments

object
Required. Always the name of a FileSystemObject.
filespec
Required. The filespec is the path (absolute or relative) to a specific file.

Remarks

An error occurs if the specified file does not exist.

The following example illustrates the use of the GetFile method.

[JScript]
function ShowFileAccessInfo(filespec)
{
   var fso, f, s;
   fso = new ActiveXObject("Scripting.FileSystemObject");
   f = fso.GetFile(filespec);
   s = f.Path.toUpperCase() + "<br>";
   s += "Created: " + f.DateCreated + "<br>";
   s += "Last Accessed: " + f.DateLastAccessed + "<br>";
   s += "Last Modified: " + f.DateLastModified
   return(s);
}
[VBScript]
Function ShowFileAccessInfo(filespec)
   Dim fso, f, s
   Set fso = CreateObject("Scripting.FileSystemObject")
   Set f = fso.GetFile(filespec)
   s = f.Path & "<br>"
   s = s & "Created: " & f.DateCreated & "<br>"
   s = s & "Last Accessed: " & f.DateLastAccessed & "<br>"
   s = s & "Last Modified: " & f.DateLastModified
   ShowFileAccessInfo = s
End Function

See Also

GetAbsolutePathName Method | GetBaseName Method | GetDrive Method | GetDriveName Method | GetExtensionName Method | GetFileName Method | GetFileVersion Method | GetFolder Method | GetParentFolderName Method | GetSpecialFolder Method | GetTempName Method
Applies To: FileSystemObject Object


GetFileName Method

Returns the last component of specified path that is not part of the drive specification.

object.GetFileName(pathspec)

Arguments

object
Required. Always the name of a FileSystemObject.
pathspec
Required. The path (absolute or relative) to a specific file.

Remarks

The GetFileName method returns a zero-length string ("") if pathspec does not end with the named component.

Note The GetFileName method works only on the provided path string. It does not attempt to resolve the path, nor does it check for the existence of the specified path.

The following example illustrates the use of the GetFileName method.

[JScript]
function ShowFileName(filespec)
{
   var fso, s = "";
   fso = new ActiveXObject("Scripting.FileSystemObject");
   s += fso.GetFileName(filespec);
   return(s);
}
[VBScript]
Function GetAName(DriveSpec)
   Dim fso
   Set fso = CreateObject("Scripting.FileSystemObject")
   GetAName = fso.GetFileName(DriveSpec)
End Function

See Also

GetAbsolutePathName Method | GetBaseName Method | GetDrive Method | GetDriveName Method | GetExtensionName Method | GetFile Method | GetFileVersion Method | GetFolder Method | GetParentFolderName Method | GetSpecialFolder Method | GetTempName Method
Applies To: FileSystemObject Object


GetFileVersion Method

Returns the version number of a specified file.

object.GetFileVersion(pathspec)

Arguments

object
Required. Always the name of a FileSystemObject.
pathspec
Required. The path (absolute or relative) to a specific file.

Remarks

The GetFileVersion method returns a zero-length string ("") if pathspec does not end with the named component.

Note The GetFileVersion method works only on the provided path string. It does not attempt to resolve the path, nor does it check for the existence of the specified path.

The following example illustrates the use of the GetFileVersion method.

[JScript]
function ShowFileName(filespec){
   var fso, s = "";
   fso = new ActiveXObject("Scripting.FileSystemObject");
   s += fso.GetFileVersion(filespec);
   return(s);
}
[VBScript]
Function GetVersion(DriveSpec)
   Dim fso, temp
   Set fso = CreateObject("Scripting.FileSystemObject")
   temp = fso.GetFileVersion(pathspec)
   If Len(temp) Then
      GetVersion = temp
   Else
      GetVersion = "No version information available."
   End If
End Function

See Also

GetAbsolutePathName Method | GetBaseName Method | GetDrive Method | GetDriveName Method | GetExtensionName Method | GetFile Method | GetFileName Method | GetFolder Method | GetParentFolderName Method | GetSpecialFolder Method | GetTempName Method
Applies To: FileSystemObject Object


GetFolder Method

Returns a Folder object corresponding to the folder in a specified path.

object.GetFolder(folderspec)

Arguments

object
Required. Always the name of a FileSystemObject.
folderspec
Required. The folderspec is the path (absolute or relative) to a specific folder.

Remarks

An error occurs if the specified folder does not exist.

The following example illustrates the use of the GetFolder method.

[JScript]
function ShowFolderList(folderspec)
{
   var fso, f, fc, s;
   fso = new ActiveXObject("Scripting.FileSystemObject");
   f = fso.GetFolder(folderspec);
   fc = new Enumerator(f.SubFolders);
   s = "";
   for (; !fc.atEnd(); fc.moveNext())
   {
      s += fc.item();
      s += "<br>";
   }
   return(s);
}
[VBScript]
Sub AddNewFolder(path, folderName)
   Dim fso, f, fc, nf
   Set fso = CreateObject("Scripting.FileSystemObject")
   Set f = fso.GetFolder(path)
   Set fc = f.SubFolders
   If folderName <> "" Then
      Set nf = fc.Add(folderName)
   Else
      Set nf = fc.Add("New Folder")
   End If
End Sub

See Also

GetAbsolutePathName Method | GetBaseName Method | GetDrive Method | GetDriveName Method | GetExtensionName Method | GetFile Method | GetFileName Method | GetFileVersion Method | GetParentFolderName Method | GetSpecialFolder Method | GetTempName Method
Applies To: FileSystemObject Object


GetParentFolderName Method

Returns a string containing the name of the parent folder of the last component in a specified path.

object.GetParentFolderName(path)

Arguments

object
Required. Always the name of a FileSystemObject.
path
Required. The path specification for the component whose parent folder name is to be returned.

Remarks

The GetParentFolderName method returns a zero-length string ("") if there is no parent folder for the component specified in the path argument.

Note The GetParentFolderName method works only on the provided path string. It does not attempt to resolve the path, nor does it check for the existence of the specified path.

The following example illustrates the use of the GetParentFolderName method.

[JScript]
function ShowParentFolderName(filespec)
{
   var fso, s = "";
   fso = new ActiveXObject("Scripting.FileSystemObject");
   s += fso.GetParentFolderName(filespec);
   return(s);
}
[VBScript]
Function GetTheParent(DriveSpec)
   Dim fso
   Set fso = CreateObject("Scripting.FileSystemObject")
   GetTheParent = fso.GetParentFolderName(Drivespec)
End Function

See Also

GetAbsolutePathName Method | GetBaseName Method | GetDrive Method | GetDriveName Method | GetExtensionName Method | GetFile Method | GetFileName Method | GetFileVersion Method | GetFolder Method | GetSpecialFolder Method | GetTempName Method
Applies To: FileSystemObject Object


GetSpecialFolder Method

Returns the special folder object specified.

object.GetSpecialFolder(folderspec)

Arguments

object
Required. Always the name of a FileSystemObject.
folderspec
Required. The name of the special folder to be returned. Can be any of the constants shown in the Settings section.

Settings

The folderspec argument can have any of the following values:

Constant | 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]
var fso, tempfile;
fso = new ActiveXObject("Scripting.FileSystemObject");

function CreateTempFile()
{
   var tfolder, tfile, tname, fname, TemporaryFolder = 2;
   tfolder = fso.GetSpecialFolder(TemporaryFolder);
   tname = fso.GetTempName();
   tfile = tfolder.CreateTextFile(tname);
   return(tfile);
}
tempfile = CreateTempFile();
tempfile.writeline("Hello World");
tempfile.close();
[VBScript]
Dim fso, tempfile
Set fso = CreateObject("Scripting.FileSystemObject")

Function CreateTempFile
   Dim tfolder, tname, tfile
   Const TemporaryFolder = 2
   Set tfolder = fso.GetSpecialFolder(TemporaryFolder)
   tname = fso.GetTempName
   Set tfile = tfolder.CreateTextFile(tname)
   Set CreateTempFile = tfile
End Function

Set tempfile = CreateTempFile
tempfile.WriteLine "Hello World"
tempfile.Close

See Also

GetAbsolutePathName Method | GetBaseName Method | GetDrive Method | GetDriveName Method | GetExtensionName Method | GetFile Method | GetFileName Method | GetFileVersion Method | GetFolder Method | GetParentFolderName Method | GetTempName Method
Applies To: FileSystemObject Object


GetTempName Method

Returns a randomly generated temporary file or folder name that is useful for performing operations that require a temporary file or folder.

object.GetTempName ( );

The optional object is always the name of a FileSystemObject.

Remarks

The GetTempName method does not create a file. It provides only a temporary file name that can be used with CreateTextFile to create a file.

The following example illustrates the use of the GetTempName method.

[JScript]
var fso, tempfile;
fso = new ActiveXObject("Scripting.FileSystemObject");

function CreateTempFile()
{
   var tfolder, tfile, tname, fname, TemporaryFolder = 2;
   tfolder = fso.GetSpecialFolder(TemporaryFolder);
   tname = fso.GetTempName();
   tfile = tfolder.CreateTextFile(tname);
   return(tfile);
}
tempfile = CreateTempFile();
tempfile.writeline("Hello World");
tempfile.close();
[VBScript]
Dim fso, tempfile
Set fso = CreateObject("Scripting.FileSystemObject")

Function CreateTempFile
   Dim tfolder, tname, tfile
   Const TemporaryFolder = 2
   Set tfolder = fso.GetSpecialFolder(TemporaryFolder)
   tname = fso.GetTempName
   Set tfile = tfolder.CreateTextFile(tname)
   Set CreateTempFile = tfile
End Function

Set tempfile = CreateTempFile
tempfile.WriteLine "Hello World"
tempfile.Close

See Also

GetAbsolutePathName Method | GetBaseName Method | GetDrive Method | GetDriveName Method | GetExtensionName Method | GetFile Method | GetFileName Method | GetFileVersion Method | GetFolder Method | GetParentFolderName Method | GetSpecialFolder Method
Applies To: FileSystemObject Object


Move Method

Moves a specified file or folder from one location to another.

object.Move( destination );

Arguments

object
Required. Always the name of a File or Folder object.
destination
Required. Destination where the file or folder is to be moved. Wildcard characters are not allowed.

Remarks

The results of the Move method on a File or Folder are identical to operations performed using FileSystemObject.MoveFile or FileSystemObject.MoveFolder. You should note, however, that the alternative methods are capable of moving multiple files or folders.

See Also

Copy Method | Delete Method | MoveFile Method | MoveFolder Method | OpenAsTextStream Method
Applies To: File Object | Folder Object


MoveFile Method

Moves one or more files from one location to another.

object.MoveFile ( source, destination );

Arguments

object
Required. Always the name of a FileSystemObject.
source
Required. The path to the file or files to be moved. The source argument string can contain wildcard characters in the last path component only.
destination
Required. The path where the file or files are to be moved. The destination argument can't contain wildcard characters.

Remarks

If source contains wildcards or destination ends with a path separator (\), it is assumed that destination specifies an existing folder in which to move the matching files. Otherwise, destination is assumed to be the name of a destination file to create. In either case, three things can happen when an individual file is moved:

  • If destination does not exist, the file gets moved. This is the usual case.
  • If destination is an existing file, an error occurs.
  • If destination is a directory, an error occurs.

An error also occurs if a wildcard character that is used in source doesn't match any files. The MoveFile method stops on the first error it encounters. No attempt is made to roll back any changes made before the error occurs.

Note This method allows moving files between volumes only if supported by the operating system.

The following example illustrates the use of the MoveFile method:

[JScript]
function MoveFile2Desktop(filespec)
{
   var fso;
   fso = new ActiveXObject("Scripting.FileSystemObject");
   fso.MoveFile(filespec, "c:\\windows\\desktop\\");
}
[VBScript]
Sub MoveAFile(Drivespec)
   Dim fso
   Set fso = CreateObject("Scripting.FileSystemObject")
   fso.MoveFile Drivespec, "c:\windows\desktop\"
End Sub

See Also

CopyFile Method | DeleteFile Method | GetFile Method | GetFileName Method | Move Method | MoveFolder Method | OpenTextFile Method
Applies To: FileSystemObject Object


MoveFolder Method

Moves one or more folders from one location to another.

object.MoveFolder ( source, destination );

Arguments

object
Required. Always the name of a FileSystemObject.
source
Required. The path to the folder or folders to be moved. The source argument string can contain wildcard characters in the last path component only.
destination
Required. The path where the folder or folders are to be moved. The destination argument can't contain wildcard characters.

Remarks

If source contains wildcards or destination ends with a path separator (\), it is assumed that destination specifies an existing folder in which to move the matching files. Otherwise, destination is assumed to be the name of a destination folder to create. In either case, three things can happen when an individual folder is moved:

  • If destination does not exist, the folder gets moved. This is the usual case.
  • If destination is an existing file, an error occurs.
  • If destination is a directory, an error occurs.

An error also occurs if a wildcard character that is used in source doesn't match any folders. The MoveFolder method stops on the first error it encounters. No attempt is made to roll back any changes made before the error occurs.

Important This method allows moving folders between volumes only if supported by the operating system.

The following example illustrates the use of the MoveFolder method:

[JScript]
function MoveFldr2Desktop(fldrspec)
{
   var fso;
   fso = new ActiveXObject("Scripting.FileSystemObject");
   fso.MoveFolder(fldrspec, "c:\\windows\\desktop\\");
}
[VBScript]
Sub MoveAFolder(Drivespec)
   Dim fso
   Set fso = CreateObject("Scripting.FileSystemObject")
   fso.MoveFolder Drivespec, "c:\windows\desktop\"
End Sub

See Also

CopyFile Method | DeleteFile Method | GetFile Method | GetFileName Method | Move Method | MoveFile Method | OpenTextFile Method
Applies To: FileSystemObject Object


OpenAsTextStream Method

Opens a specified file and returns a TextStream object that can be used to read from, write to, or append to the file.

object.OpenAsTextStream([iomode, [format]])

Arguments

object
Required. Always the name of a File object.
iomode
Optional. Indicates input/output mode. Can be one of three constants: ForReading, ForWriting, or ForAppending.
format
Optional. One of three Tristate values used to indicate the format of the opened file. If omitted, the file is opened as ASCII.

Settings

The iomode argument can have any of the following settings:

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

Remarks

The OpenAsTextStream method provides the same functionality as the OpenTextFile method of the FileSystemObject. In addition, the OpenAsTextStream method can be used to write to a file.

The following code illustrates the use of the OpenAsTextStream method:

[JScript]
function TextStreamTest( )
{
   var fso, f, ts, s;
   var ForReading = 1, ForWriting = 2, ForAppending = 8;
   var TristateUseDefault = -2, TristateTrue = -1, TristateFalse = 0;
   fso = new ActiveXObject("Scripting.FileSystemObject");
   fso.CreateTextFile( "test1.txt" );           // Create a file.
   f = fso.GetFile("test1.txt");
   ts = f.OpenAsTextStream(ForWriting, TristateUseDefault);
   ts.Write( "Hello World" );
   ts.Close( );
   ts = f.OpenAsTextStream(ForReading, TristateUseDefault);
   s = ts.ReadLine( );
   ts.Close( );
   return(s);
}
[VBScript]
Function TextStreamTest
   Const ForReading = 1, ForWriting = 2, ForAppending = 8
   Const TristateUseDefault = -2, TristateTrue = -1, TristateFalse = 0
   Dim fso, f, ts
   Set fso = CreateObject("Scripting.FileSystemObject")
   fso.CreateTextFile "test1.txt"   ' Create a file.
   Set f = fso.GetFile("test1.txt")
   Set ts = f.OpenAsTextStream(ForWriting, TristateUseDefault)
   ts.Write "Hello World"
   ts.Close
   Set ts = f.OpenAsTextStream(ForReading, TristateUseDefault)
   TextStreamTest = ts.ReadLine
   ts.Close
End Function

See Also

Copy Method | CreateTextFile Method | Delete Method | Move Method | OpenTextFile Method
Applies To: File Object


OpenTextFile Method

Opens a specified file and returns a TextStream object that can be used to read from, write to, or append to the file.

object.OpenTextFile(filename[, iomode[, create[, format]]])

Arguments

object
Required. Object is always the name of a FileSystemObject.
filename
Required. String expression that identifies the file to open.
iomode
Optional. Can be one of three constants: ForReading, ForWriting, or ForAppending.
create
Optional. Boolean value that indicates whether a new file can be created if the specified filename doesn't exist. The value is True if a new file is created, False if it isn't created. If omitted, a new file isn't created.
format
Optional. One of three Tristate values used to indicate the format of the opened file. If omitted, the file is opened as ASCII.

Settings

The iomode argument can have any of the following settings:

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

Value | Description
TristateTrue | Open the file as Unicode.
TristateFalse | Open the file as ASCII.
TristateUseDefault | Open the file using the system default.

Remarks

The following code illustrates the use of the OpenTextFile method to open a file for appending text:

[JScript]
var fs, a, ForAppending;
ForAppending = 8;
fs = new ActiveXObject("Scripting.FileSystemObject");
a = fs.OpenTextFile("c:\\testfile.txt", ForAppending, false);
...
a.Close();
[VBScript]
Sub OpenTextFileTest
   Const ForReading = 1, ForWriting = 2, ForAppending = 8
   Dim fso, f
   Set fso = CreateObject("Scripting.FileSystemObject")
   Set f = fso.OpenTextFile("c:\testfile.txt", ForWriting, True)
   f.Write "Hello world!"
   f.Close
End Sub

See Also

CreateTextFile Method | OpenAsTextStream Method
Applies To: FileSystemObject Object


Read Method

Reads a specified number of characters from a TextStream file and returns the resulting string.

object.Read(characters)

Arguments

object
Required. Always the name of a TextStream object.
characters
Required. Number of characters you want to read from the file.

The following example illustrates how to use the Read method to read a six character header from a file and return the resulting string:

[JScript]
function GetHeader()
{
   var fso, f;
   var ForReading = 1, ForWriting = 2;
   fso = new ActiveXObject("Scripting.FileSystemObject");
   f = fso.OpenTextFile("c:\\testfile.txt", ForWriting, true);
   f.Write("Header");
   f.Write("1234567890987654321");
   f.Close();
   f = fso.OpenTextFile("c:\\testfile.txt", ForReading);
   return(f.Read(6));
}
[VBScript]
Function ReadTextFileTest
   Const ForReading = 1, ForWriting = 2, ForAppending = 8
   Dim fso, f, Msg
   Set fso = CreateObject("Scripting.FileSystemObject")
   Set f = fso.OpenTextFile("c:\testfile.txt", ForWriting, True)
   f.Write "Hello world!"
   Set f = fso.OpenTextFile("c:\testfile.txt", ForReading)
   ReadTextFileTest = f.Read(5)
End Function

See Also

ReadAll Method | ReadLine Method | Skip Method | SkipLine Method
Applies To: TextStream Object


ReadAll Method

Reads an entire TextStream file and returns the resulting string.

object.ReadAll( );

The object is always the name of a TextStream object.

Remarks

For large files, using the ReadAll method wastes memory resources. Other techniques should be used to input a file, such as reading a file line by line.

The following example illustrates the use of the ReadAll method:

[JScript]
function GetEverything()
{
   var fso, f;
   var ForReading = 1, ForWriting = 2;
   fso = new ActiveXObject("Scripting.FileSystemObject");
   f = fso.OpenTextFile("c:\\testfile.txt", ForWriting, true);
   f.Write("Header");
   f.Write("1234567890987654321");
   f.Close();
   f = fso.OpenTextFile("c:\\testfile.txt", ForReading);
   return(f.ReadAll());
}
[VBScript]
Function ReadAllTextFile
   Const ForReading = 1, ForWriting = 2
   Dim fso, f
   Set fso = CreateObject("Scripting.FileSystemObject")
   Set f = fso.OpenTextFile("c:\testfile.txt", ForWriting, True)
   f.Write "Hello world!"
   Set f = fso.OpenTextFile("c:\testfile.txt", ForReading)
   ReadAllTextFile =   f.ReadAll
End Function

See Also

Read Method | ReadLine Method | Skip Method | SkipLine Method
Applies To: TextStream Object


ReadLine Method

Reads an entire line (up to, but not including, the newline character) from a TextStream file and returns the resulting string.

object.ReadLine( )

The object argument is always the name of a TextStream object.

Remarks

The following example illustrates the use of the Line property:

[JScript]
function GetLine()
{
   var fso, f, r;
   var ForReading = 1, ForWriting = 2;
   fso = new ActiveXObject("Scripting.FileSystemObject");
   f = fso.OpenTextFile("c:\\testfile.txt", ForWriting, true);
   f.WriteLine("Hello world!");
   f.WriteLine("JScript is fun");
   f.Close();
   f = fso.OpenTextFile("c:\\testfile.txt", ForReading);
   r =  f.ReadLine();
   return(r);
}
[VBScript]
Function ReadLineTextFile
   Const ForReading = 1, ForWriting = 2
   Dim fso, MyFile
   Set fso = CreateObject("Scripting.FileSystemObject")
   Set MyFile = fso.OpenTextFile("c:\testfile.txt", ForWriting, True)
   MyFile.WriteLine "Hello world!"
   MyFile.WriteLine "The quick brown fox"
   MyFile.Close
   Set MyFile = fso.OpenTextFile("c:\testfile.txt", ForReading)
   ReadLineTextFile = MyFile.ReadLine    ' Returns "Hello world!"
End Function

See Also

Read Method | ReadAll Method | Skip Method | SkipLine Method
Applies To: TextStream Object


Skip Method

Skips a specified number of characters when reading a TextStream file.

object.Skip(characters)

Arguments

object
Required. Always the name of a TextStream object.
characters
Required. Number of characters to skip when reading a file.

Remarks

Skipped characters are discarded.

The following example illustrates the use of the Skip method:

[JScript]
function SkipDemo()
{
   var fso, f, r;
   var ForReading = 1, ForWriting = 2;
   fso = new ActiveXObject("Scripting.FileSystemObject")
   f = fso.OpenTextFile("c:\\testfile.txt", ForWriting, true);
   f.WriteLine("Hello world!");
   f.WriteLine("JScript is fun");
   f.Close();
   f = fso.OpenTextFile("c:\\testfile.txt", ForReading);
   f.Skip(6);
   r = f.ReadLine();
   return(r);
}
[VBScript]
Function SkipTextFile
   Const ForReading = 1, ForWriting = 2
   Dim fso, f
   Set fso = CreateObject("Scripting.FileSystemObject")
   Set f = fso.OpenTextFile("c:\testfile.txt", ForWriting, True)
   f.Write "Hello world!"
   Set f = fso.OpenTextFile("c:\testfile.txt", ForReading)
   f.Skip(6)
   SkipTextFile =   f.ReadLine
End Function

See Also

Close Method | Read Method | ReadAll Method | ReadLine Method | SkipLine Method | Write Method | WriteLine Method | WriteBlankLines Method
Applies To: TextStream Object


SkipLine Method

Skips the next line when reading a TextStream file.

object.SkipLine( )

The object is always the name of a TextStream object.

Remarks

The following examples illustrates the use of the SkipLine method:

[JScript]
function SkipLineDemo()
{
   var fso, f, r
   var ForReading = 1, ForWriting = 2;
   fso = new ActiveXObject("Scripting.FileSystemObject")
   f = fso.OpenTextFile("c:\\testfile.txt", ForWriting, true)
   f.WriteLine("Hello world!");
   f.WriteLine("JScript is fun");
   f.Close();
   f = fso.OpenTextFile("c:\\testfile.txt", ForReading);
   f.SkipLine();
   r = f.ReadLine();
   return(r);
}
[VBScript]
Function SkipLineInFile
   Const ForReading = 1, ForWriting = 2
   Dim fso, f
   Set fso = CreateObject("Scripting.FileSystemObject")
   Set f = fso.OpenTextFile("c:\testfile.txt", ForWriting, True)
   f.Write "Hello world!" & vbCrLf & "VB Script is fun!"
   Set f = fso.OpenTextFile("c:\testfile.txt", ForReading)
   f.SkipLine
   SkipLineInFile = f.ReadLine
End Function

See Also

Read Method | ReadAll Method | ReadLine Method | Skip Method
Applies To: TextStream Object


Write Method

Writes a specified string to a TextStream file.

object.Write(string)

Arguments

object
Required. Always the name of a TextStream object.
string
Required. The text you want to write to the file.

Remarks

Specified strings are written to the file with no intervening spaces or characters between each string. Use the WriteLine method to write a newline character or a string that ends with a newline character.

The following example illustrates the use of the Write method:

[JScript]
function WriteDemo()
{
   var fso, f, r
   var ForReading = 1, ForWriting = 2;
   fso = new ActiveXObject("Scripting.FileSystemObject")
   f = fso.OpenTextFile("c:\\testfile.txt", ForWriting, true)
   f.Write("Hello world!");
   f.Close();
   f = fso.OpenTextFile("c:\\testfile.txt", ForReading);
   r = f.ReadLine();
   return(r);
}
[VBScript]
Function WriteToFile
   Const ForReading = 1, ForWriting = 2
   Dim fso, f
   Set fso = CreateObject("Scripting.FileSystemObject")
   Set f = fso.OpenTextFile("c:\testfile.txt", ForWriting, True)
   f.Write "Hello world!"
   Set f = fso.OpenTextFile("c:\testfile.txt", ForReading)
   WriteToFile =   f.ReadLine
End Function

See Also

WriteBlankLines Method | WriteLine Method
Applies To: TextStream Object


WriteBlankLines Method

Writes a specified number of newline characters to a TextStream file.

object.WriteBlankLines(lines)

Arguments

object
Required. Always the name of a TextStream object.
lines
Required. Number of newline characters you want to write to the file.

Remarks

The following example illustrates the use of the WriteBlankLines method:

[JScript]
function WriteBlanksDemo()
{
   var fso, f, r;
   var ForReading = 1, ForWriting = 2;
   fso = new ActiveXObject("Scripting.FileSystemObject");
   f = fso.OpenTextFile("c:\\testfile.txt", ForWriting, true);
   f.Write("Hello world!");
   f.WriteBlankLines(2);
   f.Write("JScript is fun!");
   f.Close();
   f = fso.OpenTextFile("c:\\testfile.txt", ForReading);
   r = f.ReadAll();
   return(r);
}
[VBScript]
Function WriteBlankLinesToFile
   Const ForReading = 1, ForWriting = 2
   Dim fso, f
   Set fso = CreateObject("Scripting.FileSystemObject")
   Set f = fso.OpenTextFile("c:\testfile.txt", ForWriting, True)
   f.WriteBlankLines 2
   f.WriteLine "Hello World!"
   Set f = fso.OpenTextFile("c:\testfile.txt", ForReading)
   WriteBlankLinesToFile = f.ReadAll
End Function

See Also

Write Method | WriteLine Method
Applies To: TextStream Object


WriteLine Method

Writes a specified string and newline character to a TextStream file.

object.WriteLine([string])

Arguments

object
Required. Always the name of a TextStream object.
string
Optional. The text you want to write to the file. If omitted, a newline character is written to the file.

Remarks

The following example illustrates use of the WriteLine method:

[JScript]
var fso, f;
fso = new ActiveXObject("Scripting.FileSystemObject");
f = fso.CreateTextFile("c:\\testfile.txt", true);
f.WriteLine("This is a test.");
f.Close();
[VBScript]
Function WriteLineToFile
   Const ForReading = 1, ForWriting = 2
   Dim fso, f
   Set fso = CreateObject("Scripting.FileSystemObject")
   Set f = fso.OpenTextFile("c:\testfile.txt", ForWriting, True)
   f.WriteLine "Hello world!"
   f.WriteLine "VBScript is fun!"
   Set f = fso.OpenTextFile("c:\testfile.txt", ForReading)
   WriteLineToFile = f.ReadAll
End Function

See Also

Write Method | WriteBlankLines Method
Applies To: TextStream Object


FileSystemObject Objects

In This Section

Dictionary Object
Object that stores data key, item pairs.
Drive Object
Provides access to the properties of a particular disk drive or network share.
File Object
Provides access to all the properties of a file.
FileSystemObject Object
Provides access to a computer's file system.
Folder Object
Provides access to all the properties of a folder.
TextStream Object
Facilitates sequential access to file.

Related Sections

Scripting Run-Time Reference
List of elements that make up Scripting Run-Time Reference.
FileSystemObject Basics
A guide to the fundamentals of the FileSystemObject.
FileSystemObject Collections
List of collections you can use with the FileSystemObject object model.


Drive Object

Provides access to the properties of a particular disk drive or network share.

Remarks

The following code illustrates the use of the Drive object to access drive properties:

[JScript]
function ShowFreeSpace(drvPath)
{
   var fso, d, s;
   fso = new ActiveXObject("Scripting.FileSystemObject");
   d = fso.GetDrive(fso.GetDriveName(drvPath));
   s = "Drive " + drvPath + " - " ;
   s += d.VolumeName + "<br>";
   s += "Free Space: " + d.FreeSpace/1024 + " Kbytes";
   return(s);
}
[VBScript]
Function ShowFreeSpace(drvPath)
   Dim fso, d, s
   Set fso = CreateObject("Scripting.FileSystemObject")
   Set d = fso.GetDrive(fso.GetDriveName(drvPath))
   s = "Drive " & UCase(drvPath) & " - "
   s = s & d.VolumeName   & "<BR>"
   s = s & "Free Space: " & FormatNumber(d.FreeSpace/1024, 0)
   s = s & " Kbytes"
   ShowFreeSpace = s
End Function

Methods

The Drive object has no methods.

Properties

AvailableSpace Property | DriveLetter Property | DriveType Property | FileSystem Property | FreeSpace Property | IsReady Property | Path Property | RootFolder Property | SerialNumber Property | ShareName Property | TotalSize Property | VolumeName Property

See Also

Drives Collection | File Object | Files Collection | Folder Object | Folders Collection | GetDrive Method


File Object

Provides access to all the properties of a file.

Remarks

The following code illustrates how to obtain a File object and how to view one of its properties.

[JScript]
function ShowFileInfo(filespec)
{
   var fso, f, s;
   fso = new ActiveXObject("Scripting.FileSystemObject");
   f = fso.GetFile(filespec);
   s = f.DateCreated;
   return(s);
}
[VBScript]
Function ShowDateCreated(filespec)
   Dim fso, f
   Set fso = CreateObject("Scripting.FileSystemObject")
   Set f = fso.GetFile(filespec)
   ShowDateCreated = f.DateCreated
End Function

Methods

Copy Method | Delete Method | Move Method | OpenAsTextStream Method

Properties

Attributes Property | DateCreated Property | DateLastAccessed Property | DateLastModified Property | Drive Property | Name Property | ParentFolder Property | Path Property | ShortName Property | ShortPath Property | Size Property | Type Property

See Also

Drive Object | Drives Collection | Files Collection | Folder Object | Folders Collection


FileSystemObject Object

Provides access to a computer's file system.

Remarks

[JScript]

The following code illustrates how the FileSystemObject is used to return a TextStream object that can be read from or written to:

[JScript]
var fso = new ActiveXObject("Scripting.FileSystemObject");
var a = fso.CreateTextFile("c:\\testfile.txt", true);
a.WriteLine("This is a test.");
a.Close();

[JScript]

In the example code, the ActiveXObject object is assigned to the FileSystemObject (fso). The CreateTextFile method then creates the file as a TextStream object (a), and the WriteLine method writes a line of text to the created text file. The Close method flushes the buffer and closes the file.

[VBScript]

The following code illustrates how the FileSystemObject is used to return a TextStream object that can be read from or written to:

[VBScript]
Dim fso, MyFile
Set fso = CreateObject("Scripting.FileSystemObject")
Set MyFile = fso.CreateTextFile("c:\testfile.txt", True)
MyFile.WriteLine("This is a test.")
MyFile.Close

[VBScript]

In the preceding code, the CreateObject function returns the FileSystemObject (fso). The CreateTextFile method then creates the file as a TextStream object (a) and the WriteLine method writes a line of text to the created text file. The Close method flushes the buffer and closes the file.

Methods

BuildPath Method | CopyFile Method | CopyFolder Method | CreateFolder Method | CreateTextFile Method | DeleteFile Method | DeleteFolder Method | DriveExists Method | FileExists Method | FolderExists Method | GetAbsolutePathName Method | GetBaseName Method | GetDrive Method | GetDriveName Method | GetExtensionName Method | GetFile Method | GetFileName Method | GetFolder Method | GetParentFolderName Method | GetSpecialFolder Method | GetTempName Method | MoveFile Method | MoveFolder Method | OpenTextFile Method

Properties

Drives Property

See Also

Dictionary Object | Drive Object | Drives Collection | File Object | Files Collection | Folder Object | Folders Collection | TextStream Object


Folder Object

Provides access to all the properties of a folder.

Remarks

The following code illustrates how to obtain a Folder object and how to return one of its properties:

[JScript]
function ShowFolderInfo(folderspec)
{
   var fso, folder, s;
   fso = new ActiveXObject("Scripting.FileSystemObject");
   folder = fso.GetFolder(folderspec);
   s = folder.DateCreated;
   return(s);
}
[VBScript]
Function ShowDateCreated(folderspec)
   Dim fso, f
   Set fso = CreateObject("Scripting.FileSystemObject")
   Set f = fso.GetFolder(folderspec)
   ShowDateCreated = f.DateCreated
End Function

Methods

Copy Method | Delete Method | Move Method | OpenAsTextStream Method

Properties

Attributes Property | DateCreated Property | DateLastAccessed Property | DateLastModified Property | Drive Property | Files Property | IsRootFolder Property | Name Property | ParentFolder Property | Path Property | ShortName Property | ShortPath Property | Size Property | SubFolders Property | Type Property

See Also

Drive Object | Drives Collection | File Object | Files Collection | Folders Collection


TextStream Object

Facilitates sequential access to file.

TextStream.{property  | method( )}

The property and method arguments can be any of the properties and methods associated with the TextStream object. Note that in actual usage, TextStream is replaced by a variable placeholder representing the TextStream object returned from the FileSystemObject.

Remarks

In the following code, a is the TextStream object returned by the CreateTextFile method on the FileSystemObject:

[JScript]
var fso = new ActiveXObject("Scripting.FileSystemObject");
var a = fso.CreateTextFile("c:\\testfile.txt", true);
a.WriteLine("This is a test.");
a.Close();
[VBScript]
Dim fso, MyFile
Set fso = CreateObject("Scripting.FileSystemObject")
Set MyFile= fso.CreateTextFile("c:\testfile.txt", True)
MyFile.WriteLine("This is a test.")
MyFile.Close

WriteLine and Close are two methods of the TextStream object.

Methods

Close Method | Read Method | ReadAll Method | ReadLine Method | Skip Method | SkipLine Method | Write Method | WriteBlankLines Method | WriteLine Method

Properties

AtEndOfLine Property | AtEndOfStream Property | Column Property | Line Property

See Also

Dictionary Object | FileSystemObject Object


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

Read-only collection of all available drives.

Remarks

Removable-media drives need not have media inserted for them to appear in the Drives collection.

[JScript]

The following example illustrates how to get the Drives collection using the Drives property and iterate the collection using the Enumerator object:

[JScript]
function ShowDriveList()
{
   var fso, s, n, e, x;
   fso = new ActiveXObject("Scripting.FileSystemObject");
   e = new Enumerator(fso.Drives);
   s = "";
   for (; !e.atEnd(); e.moveNext())
   {
      x = e.item();
      s = s + x.DriveLetter;
      s += " - ";
      if (x.DriveType == 3)
         n = x.ShareName;
      else if (x.IsReady)
         n = x.VolumeName;
      else
         n = "[Drive not ready]";
      s +=   n + "<br>";
   }
   return(s);
}

[VBScript]

The following code illustrates how to get the Drives collection and iterate the collection using the For Each...Next statement:

[VBScript]
Function ShowDriveList
   Dim fso, d, dc, s, n
   Set fso = CreateObject("Scripting.FileSystemObject")
   Set dc = fso.Drives
   For Each d in dc
      n = ""
      s = s & d.DriveLetter & " - "
      If d.DriveType = Remote Then
         n = d.ShareName
      ElseIf d.IsReady Then
         n = d.VolumeName
      End If
      s = s & n & "<BR>"
   Next
   ShowDriveList = s
End Function

Methods

The Drives collection has no methods.

Properties

Count Property | Item Property

See Also

Drive Object | Drives Property | File Object | Files Collection | Folder Object | Folders Collection


Files Collection

Collection of all File objects within a folder.

Remarks

[JScript]

The following example illustrates how to get a Files collection and iterate the collection using the Enumerator object and the for statement:

[JScript]
function ShowFolderFileList(folderspec)
{
   var fso, f, f1, fc, s;
   fso = new ActiveXObject("Scripting.FileSystemObject");
   f = fso.GetFolder(folderspec);
   fc = new Enumerator(f.files);
   s = "";
   for (; !fc.atEnd(); fc.moveNext())
   {
      s += fc.item();
      s += "<br>";
   }
   return(s);
}

[VBScript]

The following code illustrates how to get a Files collection and iterate the collection using the For Each...Next statement:

[VBScript]
Function ShowFolderList(folderspec)
   Dim fso, f, f1, fc, s
   Set fso = CreateObject("Scripting.FileSystemObject")
   Set f = fso.GetFolder(folderspec)
   Set fc = f.Files
   For Each f1 in fc
      s = s & f1.name
      s = s & "<BR>"
   Next
   ShowFolderList = s
End Function

Methods

The Files collection has no methods.

Properties

Count Property | Item Property

See Also

Drive Object | Drives Collection | File Object | Folder Object | Folders Collection


Folders Collection

Collection of all Folder objects contained within a Folder object.

Remarks

[JScript]

The following example illustrates how to get a Folders collection and how to iterate the collection using the Enumerator object and the for statement:

[JScript]
function ShowFolderList(folderspec)
{
   var fso, f, fc, s;
   fso = new ActiveXObject("Scripting.FileSystemObject");
   f = fso.GetFolder(folderspec);
   fc = new Enumerator(f.SubFolders);
   s = "";
   for (; !fc.atEnd(); fc.moveNext())
   {
      s += fc.item();
      s += "<br>";
   }
   return(s);
}

[VBScript]

The following code illustrates how to get a Folders collection and how to iterate the collection using the For Each...Next statement:

[VBScript]
Function ShowFolderList(folderspec)
   Dim fso, f, f1, fc, s
   Set fso = CreateObject("Scripting.FileSystemObject")
   Set f = fso.GetFolder(folderspec)
   Set fc = f.SubFolders
   For Each f1 in fc
      s = s & f1.name
      s = s &   "<BR>"
   Next
   ShowFolderList = s
End Function

Methods

Add Method (Folders)

Properties

Count Property | Item Property

See Also

Drive Object | Drives Collection | File Object | Files Collection | Folder Object | SubFolders Property


Script Encoder Overview

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.

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

Using Script Encoder | Script Encoder Syntax | Script Encoding Sample


Using Script Encoder

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.

For Visual Basic® Scripting Edition (VBScript), the following example illustrates how the encoding marker is used to expose a plain-text copyright message:

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

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

<SCRIPT LANGUAGE="VBScript.Encode">

For JScript, the new designator looks like this:

<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

Script Encoder Overview | Script Encoder Syntax | Script Encoding Sample


Script Encoder Syntax

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:

screnc test.html encode.html

To encode input file test.htm and overwrite the input file with the encoded output file, use:

screnc /f test.htm

To encode all .ASP files in the current directory and place the encoded output files in c:\temp, use:

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:

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:

screnc /s /f *.sct

See Also

Script Encoder Overview | Using Script Encoder | Script Encoding Sample


Script Encoding Sample

Here is a short example of a Web page that includes some JScript code that needs protecting:

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

Script Encoder Overview | Using Script Encoder | Script Encoder Syntax


Windows Script Host

Windows Script Host

In This Section

Getting Started

WSH Basics

Running Your Scripts

Basic Windows Script Host Tasks

Security and Windows Script Host

Reference


Getting Started

In This Section

What's New in WSH
Description of the new features in WSH 5.6.
Document Conventions
Description of the syntax and conventions used in WSH 5.6 help documentation.

Related Sections

WSH Reference
List of elements that make up WSH Reference.
WSH Basics
Learn the basics of WSH.


What's New In WSH 5.6

Several areas of functionality have been addressed in this latest version of the Windows Script Host (version 5.6).

  • Argument handling has been improved — Handling and documenting command line arguments is simpler. The process of integrating your scripts with other command line scripts has been simplified, and it is easier to create scripts that can supply the user with help information. Refer to the following table for information on the WSH language features that connect you to this new functionality.
    To Learn About | See
    Grouping your script's switches together. | <runtime> Element
    Defining your script's named switches. | <named> Element
    Defining your script's unnamed switches. | <unnamed> Element
    Making your script self-documenting. <example> Element

    <description> Element
    Sharing the environment of the current process (IOW, WSH) with a 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
  • You can run scripts remotely — You can load scripts onto several remote computer systems and start them all running simultaneously. While a remote script is running, you can check its progress. After it has finished, you can ensure that it ran correctly or determine the cause of its premature termination. There is a new dispatch object used to create remote WSH objects — the Controller object. In addition, there is a new object that represents an instance of a running script — the Remote WSH object.
    To Learn About | See
    Creating a remote script object — the remote WSH interface. | WshController Object
    Creating a remote script object — using remote WSH interface. | CreateScript Method
    Creating a remote script object — getting a handle. | WshRemote Object
    Starting a remote script process. | Execute Method
    Determining whether a remote script is currently running. | Status Property (WshRemote)
    Determining why a remote script terminated. | Description Property (WshRemoteError)
    Identifying which statement in your remote script caused it to terminate. | Line Property (WshRemoteError)
    Accessing error information after a remote script terminates. | WshRemoteError Object
    Identifying the character in the line of code that contained the error. | Character Property
    Identifying the error number representing a script error. | Number Property
    Identifying the source of the script error. | Source Property
    Identifying the line of source code that caused an error. | SourceText Property
    Handling remote object events. Start Event

    End Event

    Error Event
  • When you start new processes, you can treat them as objects — You determine the status of spawned processes and access their standard I/O streams.
    To Learn About | See
    Spawning a process. | Exec Method
    Accessing the object that represents running processes. | WshScriptExec Object
    Accessing process status information. | Status Property (WshScriptExec)
    Accessing the standard I/O streams. | StdOut Property (WshScriptExec)
    StdIn Property (WshScriptExec)
    StdErr Property (WshScriptExec)
  • You can access the current working directory — You can determine/modify the active process's current working directory.
    To Learn About | See
    Accessing the active directory information. | CurrentDirectory Property
  • Security issues unique to scripts have been addressed — A new security model makes distributing and running scripts safer.
    To Learn About | See
    Script signing and verification. | Security and Windows Script Host


Upgrading Windows Script Host

If you are currently using Windows 2000 or Windows ME, you have version 2.0 of WSH installed on your computer system. If you are running Windows 95, 98, or Windows NT 4.0, you have version 1.0. To upgrade to WSH 5.6, visit the Microsoft Windows Script Technologies Web site at (http://msdn.microsoft.com/scripting/).

Note The latest version of WSH is 5.6 due to a file versioning issue that was easiest to resolve by skipping some version numbers.


Document Conventions

Throughout the Windows Script Host 5.6 Help documentation, different fonts, weights, and colors are used to draw your attention to text of interest.

Examples of Text Styles

Type of Information | Sample
Code snippets appear in Courier blue
WScript.Echo "Hello from VBScript"
Featured elements in code snippets appear bolded in Courier blue
WScript.Echo "Hello from VBScript"
Keywords appear bolded | in the Script tab within the Properties dialog…
Links appear underlined | WshNetwork Object
Pop-up links appear italicized, and underlined | <?job error="flag" debug="flag" ?>


WSH Version Information

The following table lists the version of Windows Script Host implemented by Microsoft host applications.

Host Application | 1.0 | 2.0 | 5.6
Microsoft Windows 98 | x |  |
Microsoft Windows NT 4 Option Pack | x |  |
Microsoft Windows 2000 |  | X |

The following table lists Windows Script Host language elements and the version in which they were introduced.

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 | x |  |
AtEndOfLine Property |  | X |
AtEndOfStream Property |  | X |
Character Property |  |  | x
Close Method |  | X |
Column Property |  | X |
ComputerName Property | x |  |
ConnectObject Method |  | x |
Count Method | x |  |
CreateObject Method | x |  |
CreateScript Method |  |  | x
CreateShortcut Method | x |  |
Description Property | x |  |
Description Property (WshRemote) |  |  | 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 |  |  | x
Execute Method |  |  | x
Exists Method |  |  | x
ExitCode Property |  |  | x
ExpandEnvironmentStrings Method | x |  |
FullName Property | x |  |
GetObject Method | x |  |
GetResource Method |  | x |
HotKey Property | x |  |
IconLocation Property | x |  |
Item Property | x |  |
Item Property (WshNamed) |  |  | x
Item Property (WshUnnamed) |  |  | x
<job> Element |  | x | x
Length Property | x |  |
Line Property |  | x |
Line Property (WshRemote) |  |  | x
LogEvent Method |  | x |
MapNetworkDrive Method | x |  |
Name Property | x |  |
<named> Element |  |  | x
Number Property |  |  | x
<object> Element |  | x |
<package> Element |  | x |
Path Property | x |  |
Popup Method | x |  |
ProcessID Property |  |  | x
Quit Method | x |  |
Read Method |  | x |
ReadAll Method |  | x |
ReadLine Method |  | x |
<reference> Element |  | x |
RegDelete Method | x |  |
RegRead Method | x |  |
RegWrite Method | x |  |
Remove Method | x |  |
RemoveNetworkDrive Method | x |  |
RemovePrinterConnection Method | x |  |
<resource> Element |  |  |
Run Method | x |  |
<runtime> Element |  |  | x
Save Method | x |  |
<script> Element |  | x |
ScriptFullName Property | x |  |
ScriptName Property | x |  |
SendKeys Method |  | x |
SetDefaultPrinter Method | x |  |
ShowUsage Method |  |  | x
Skip Method |  | x |
SkipLine Method |  | x |
Sleep Method |  | x |
Source Property |  |  | x
SourceText Property |  |  | x
SpecialFolders Property | x |  |
Status Property (WshRemote) |  |  | x
Status Property (WshScriptExec) |  |  | x
StdErr Property |  | x |
StdErr Property (WshScriptExec) |  |  | x
StdIn Property |  | x |
StdIn Property (WshScriptExec) |  |  | x
StdOut Property |  | x |
StdOut Property (WshScriptExec) |  |  | x
TargetPath Property | x |  |
Terminate Method (WshScriptExec) |  |  | x
<usage> Element |  |  | x
UserDomain Property | x |  |
UserName Property | x |  |
Version Property | x |  |
WindowStyle Property | x |  |
WorkingDirectory Property | x |  |
Write Method |  | x |
WriteBlankLines Method |  | x |
WriteLine Method |  | 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

Microsoft® Windows® Script Host (WSH) is a language-independent scripting host for Windows Script compatible scripting engines. It brings simple, powerful, and flexible scripting to the Windows 32-bit platform, allowing you to run scripts from both the Windows desktop and the command prompt.

Windows Script Host is ideal for non-interactive scripting needs, such as logon scripting, administrative scripting, and machine automation.

In the Section

What Is WSH?
General overview of Windows Script Host
Hosting Environments and Script Engines
About the WSH Host environment and the script engines you can use
Creating Scripts that Can Be Used with WSH
How to create a WSH-compatible script
Windows Script Host Object Model
A roadmap to the architecture


What Is WSH?

Windows Script Host (WSH) is a Windows administration tool.

WSH creates an environment for hosting scripts. That is, when a script arrives at your computer, WSH plays the part of the host — it makes objects and services available for the script and provides a set of guidelines within which the script is executed. Among other things, Windows Script Host manages security and invokes the appropriate script engine.

WSH is language-independent for WSH-compliant scripting engines. It brings simple, powerful, and flexible scripting to the Windows platform, allowing you to run scripts from both the Windows desktop and the command prompt.

Windows Script Host is ideal for noninteractive scripting needs, such as logon scripting, administrative scripting, and machine automation.

WSH Objects and Services

Windows Script Host provides several objects for direct manipulation of script execution, as well as helper functions for other actions. Using these objects and services, you can accomplish tasks such as the following:

  • Print messages to the screen
  • Run basic functions such as CreateObject and GetObject
  • Map network drives
  • Connect to printers
  • Retrieve and modify environment variables
  • Modify registry keys

Where Is WSH?

Windows Script Host is built into Microsoft Windows 98, 2000, and Millennium Editions. If you are running Windows 95, you can download Windows Script Host 5.6 from the Microsoft Windows Script Technologies Web site (http://msdn.microsoft.com/scripting).

Note You can also go to the 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

Windows Script Host Object Model | CreateObject | GetObject


Scripts and Automating Windows

Computers are wonderful tools that perform repetitive tasks. But what if you need to perform a series of repetitive tasks? The answer lies in scripting.

What Is a Script?

A script is a program written in a scripting language, such as JScript and VBScript. Alternative script languages include Rexx, Python, and Perl. When compared to programming languages such as C++ and Visual Basic, scripting languages are better suited to creating short applications that provide quick solutions to small problems.

Automating Windows

In many cases, scripts are used to automate manual tasks, much like a macro. Scripts are well suited for:

  • Manipulating the Windows environment
  • Running other programs
  • Automating logon procedures
  • Sending key sequences to an application

For example, if you have several similar tasks, you can write one generalized script that can handle all of them.

You can write scripts that start an action in response to an event. You can write scripts that keep a running tally of events and trigger some action only when certain criteria are met.

Scripts are also useful for nonrepetitive tasks as well. If a task requires you to do many things in sequence, you can turn that sequence of tasks into just one task by scripting it.

See Also

Types of Script Files


Types of Script Files

Stand-alone scripts come in several varieties, and each has its own extension. The following table is a list of some common types.

Extension | 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

Windows Script Host Object Model


Hosting Environments and Script Engines

Scripts are often embedded in Web pages, either in an HTML page (on the client side) or in an ASP page (on the server side). In the case of a script embedded in an HTML page, the engine component that interprets and runs the script code is loaded by the Web browser, such as Internet Explorer. In the case of a script embedded in an ASP page, the engine that interprets and runs the script code is built into Internet Information Services (IIS).

Windows Script Host executes scripts that exist outside an HTML or ASP page and that stand on their own as text files.

Available Script Engines

Generally, you write scripts in either Microsoft JScript or VBScript, the two script engines that ship with Microsoft Windows 98, 2000 and Millennium Editions. You can use other script engines, such as Perl, REXX, and Python, with Windows Script Host.

Note For more information, see Microsoft Developer Network (MSDN) (http://msdn.microsoft.com/workshop/languages/clinic/vbsvjs.asp).

A stand-alone script written in JScript has the .js extension; a stand-alone script written in VBScript has the .vbs extension. These extensions are registered with Windows. When you run one of these types of files, Windows starts Windows Script Host, which invokes the associated script engine to interpret and run the file.

Note If you need to run another engine, that engine must be registered properly.


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

To simplify your script writing, you can divide a script into more than one part. With this approach, you would create a .wsf file and use it as the starting point of execution. The other parts could be .js or .vbs files. You would reference these files from the .wsf file.

This approach makes your code more robust because it isolates pieces of it, allowing you to debug one piece at a time. It also makes your code reusable because it allows you to create functions that can be called again and again.


Windows Script Host Object Model

The Windows Script Host object model consists of 14 objects. The root object is the WScript object.

The illustration that follows represents the Windows Script Host Object Model hierarchy. Click an object in the diagram to see its associated Help topic.

WshScriptExec ObjectWshSpecialFolders CollectionWshEnvironment CollectionWshUrlShortCut ObjectWshShortCut ObjectWshShell ObjectWshNetwork ObjectWshRemoteError ObjectWshRemote ObjectWshController ObjectWshUnnamed CollectionWshNamed CollectionWshArguments CollectionWScript Object

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

There are three ways to run your scripts.

  • In the Windows environment, double-click the icon of the script (you run script files the same way you run regular executable files).
  • In the Windows environment, click the Start button, and then click Run. In the Open field of the Run dialog box, type the full path of the script, and click OK.
  • From the command line, type the name of the script.

See Also

Running Scripts with WScript.exe | Running Scripts with CScript.exe | What to Include to Run a Script | Drag and Drop Support


Using Windows Script Files (.wsf)

A Windows script (*.wsf) file is a text document containing Extensible Markup Language (XML) code. It incorporates several features that offer you increased scripting flexibility. Because Windows script files are not engine-specific, they can contain script from any Windows Script compatible scripting engine. They act as a container.

With .wsf files, you can take advantage of the following features as you create your scripts:

.wsf files support | 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.

<job id="IncludeExample">
   <script language="JScript" src="FSO.JS"/>
   <script language="VBScript">
      ' Get the free space for drive C.
      s = GetFreeSpace("c:")
      WScript.Echo s
   <sScript>
</job>

The fso.js file contains the following:

function GetFreeSpace(drvPath) {
   var fs, d, s;
   fs = new ActiveXObject("Scripting.FileSystemObject");
   d = fs.GetDrive(fs.GetDriveName(drvPath));
   s = "Drive " + drvPath + " - " ;
   s += d.VolumeName;
   s += " Free Space: " + d.FreeSpace/1024 + " Kbytes";
   return s;
}

Multiple-Engine Support

Since one scripting language may not have all the functionality you need, Windows Script Host allows you to combine multiple languages in a single .wsf file. The following example shows a .wsf file that includes both VBScript and PerlScript code:

<job id="PERLandVBS">
   <script language="PerlScript">
      sub PerlHello {
         my $str = @_[0];
         $WScript->Echo($str);
      }
   </script>

   <script language="VBScript">
      WScript.Echo "Hello from VBScript"
      PerlHello "Hello from PERLScript"
   </script>
</job>

Type Library Support

In the following example, "MyComponent" was developed with Microsoft Visual Basic 5.0. "MyComponent" defines the constant MyError with the following statement.

Public Const MyError = "You are not using MyComponent correctly"

The type library is contained in mycomponent.lib, which is installed in C:\MyComponent.

<job id="IncludeExample">
   <reference progid="MyComponent.MyClass">
   <script language="VBScript">
      Dim MyVar
      Set MyVar = CreateObject("MyComponent.MyClass")
      Currentreturn = MyVar.MyMethod
      If Currentreturn = False then
         WScript.Echo MyError
      End If
   </script>
</job>

Tools Support

Since the .wsf file is in XML format, you can use any editor that supports XML to edit .wsf files. This includes text editors, such as Notepad.

Multiple Jobs in One File

Instead of keeping all your scripts in separate files, you can incorporate them all into one .wsf file and break them into several different jobs. You can then run each job separately using syntax similar to the following example, where "MyFirstJob" is the name of the job contained in the MyScripts.wsf file.

CScript //Job:MyFirstJob MyScripts.wsf


WSH Drag and Drop Support

You can drag files onto a WSH script. The file names are translated into arguments on the command line. These file names can be displayed in a list, which you can use to manipulate files with any scripting object.

To display a script's argument list

  1. Create a file and give it a name with a script extension (for example, DragDrop.vbs).
  2. Add code to the script file, for example:
    Set objArgs = WScript.Arguments
For I = 0 to objArgs.Count - 1
   WScript.Echo objArgs(I)
Next
  3. Save the file to your hard disk.
  4. Drag and drop any file or files onto your saved file. In the example, the file names are echoed back to the screen.

The number of files you can drag onto a script is limited by the your system's maximum command-line length. If the total number of characters in all file names being dragged exceeds this limit, the drag and drop operation fails.


Setting and Customizing Script Properties (.wsh)

You can record specific settings for each of your individual scripts by means of a Windows Script Host control (.wsh) file. The .wsh file is a text document in which you can customize execution of one or more of your scripts. It is created automatically when you set the properties for a supported script file.

If you create multiple .wsh files for a single script, you can tailor the way the script runs to the needs of specific groups or even individuals within an organization. For example, you could create a single logon script that is invoked by two different .wsh files that contain different settings and parameters.

When you double-click a .wsh file or run it from the command line, CScript.exe or WScript.exe reads the .wsh file to determine the specific settings that should be used to execute the script. CScript/WScript executes the original script, passing in the properties that are defined within the .wsh file.

To create a .wsh file for a given script

  1. 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:

[ScriptFile]
Path=C:\WINNT\Samples\WSH\showprop.vbs
[Options]
Timeout=0
DisplayLogo=1
BatchMode=0

The path information in the [ScriptFile] section identifies the script file that is associated with the .wsh file. The keys in the [Options] section correspond to settings in the Script tab within the Properties dialog box.

Note You must have the original script file present when executing the .wsh file. If the .wsh file fails to run the script, check the Path= information in the .wsh file to ensure that it points to the script you are attempting to run.


Running Scripts from the Command Prompt

Windows Script Host enables you to run scripts from the command prompt. CScript.exe provides command-line switches for setting script properties.

To run scripts using CScript.exe

  • Type a command at the command prompt using the following syntax:
    cscript [host options...] [script name] [script options and parameters]

Host Options enable or disable various Windows Script Host features. Host options are preceded by two slashes (//).Script name is the name of the script file with extension and necessary path information, for example, d:\admin\vbscripts\chart.vbs. Script options and parameters are passed to the script. Script parameters are preceded by a single slash (/).

Each parameter is optional; however, you cannot specify script options without specifying a script name. If you do not specify parameters, CScript displays the CScript syntax and the valid host parameters.

CScript Example

Several sample scripts, which are installed along with Windows Script Host, are also available for download at (http://msdn.microsoft.com/scripting).

Suppose, for the purposes of this example, that you have copied the Chart.vbs sample script to the following folder on your computer:

c:\sample scripts\chart.vbs

You can run the script with and without a logo as follows.

To run a script with or without a logo

  1. Start the MS-DOS command prompt.
  2. Enter the following commands at the command prompt (modify accordingly if your sample scripts are located in a different folder):
cscript //logo c:\"sample scripts"\chart.vbs
cscript //nologo c:\"sample scripts"\chart.VBScript

See Also

Running Scripts from Windows | What to Include to Run a Script | WScript.exe and CScript.exe Options


Running Scripts from Windows

Windows Script Host enables you to run scripts from Windows. WScript.exe provides a Windows-based dialog box for setting script properties. Using WScript.exe, you can run scripts under Windows in the following ways. Whether you use WScript or CScript, you still run the scripts in the same manner. The difference is only in the output — WScript generates windowed output, while CScript sends its output to the command window in which it was started.

On initial installation, the default host is WScript. To change it to CScript, type the following at the command line:

cscript //h:cscript

Or, to change it from Cscript to Wscript:

wscript //h:cscript

To run a script using the default engine:

  1. Double click the script in Windows Explorer or on the desktop.
  2. Click Start, select Run, and enter the script name.
    Note On 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

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

For the most part, options listed in the following table are applicable to both WScript.exe and CScript.exe. Exceptions are noted.

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

The information that you type when you run a script by typing its name depends on which version of Windows you are running and on the method you use to run the script.

WSH Executable File | Windows Version | 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

Running Scripts with WScript.exe | Running Scripts with CScript.exe | Drag and Drop Support


Setting up Remote WSH

Remote WSH, which is a new technology included in WSH 5.6, provides the ability to run a script on a remote machine or machines. With Remote WSH, the script is physically copied from the local machine to the remote machine before executing. In order to enable Remote WSH functionality, you must first set up the remote machine with the proper security settings. The steps below perform the tasks that enable Remote WSH.

Note Both the remote and local machines must be running Windows NT 4 SP3 or greater in order to use Remote WSH.

To enable a machine to run remote scripts

  1. Install WSH V5.6 on the machine. If you are using Windows 2001 or have installed Internet Explorer 6 or greater, WSH 5.6 has already been installed.
    Note WSH 5.6 is available for download 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 Poledit.exe on the server.
    Note An administrator who wants to enable Remote WSH must either acquire the Windows 2000 resource kit, or use http://msdn.microsoft.com/scripting to acquire the necessary windowsscript.adm file that contains the WSH settings. The windowsscript.adm file must be copied to the server that sets the gapplicabel group's policies. Although it is not necessary to copy the file to the server's \WINNT\INF directory, this is nonetheless where the default adm files are located.
    Note For more information on Poledit.exe, see the Poledit.exe's online help system.
  4. WSH should now be enabled on the machine. To test it, see Running Scripts Remotely.

See Also

Security and Windows Script Host | Running Scripts Remotely


Basic Windows Script Host Tasks

This section contains several commonly used Windows Scripting Host 5.6 scripts, which demonstrate basic functions.

Note The scripts presented 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)


Accessing Networks

With WSH you can easily access a network programmatically. The following tasks demonstrate some of these capabilities.

In this Section

Accessing Network Connections

Controlling Networked Printers

See Also

WSH Samples


Accessing Network Connections

The Network object enables you to access information about your network. The following scripts demonstrate how to map a network drive. In the first step, the script creates a Network Object. Next, the MapNetworkDrive method, one of the Network object's methods, performs the mapping operation. The MapNetworkDrive method takes five arguments:

  • The local drive assignment (I:, for example)
  • The Universal Naming Convention (UNC) path to the mapped remote drive
  • An optional Boolean indicating whether the drive will be persistently connected
  • An optional user name if you want to use different credentials
  • An optional password for use with the alternate user name
// JScript.
var net;
net = new ActiveXObject("WScript.Network");
net.MapNetworkDrive("I:", "\\\\computer2\\public","True","jdoe","jdoepassword");

' VBScript.
Dim net
Set net = CreateObject("WScript.Network")
net.MapNetworkDrive "I:", "\\computer2\public","True","jdoe","jdoepassword"

See Also

Accessing Networks


Controlling Networked Printers

The Network object enables you to access printing devices on your network. The following scripts demonstrate the use of the Network object to control a network printer device.

Connecting to a Remote Printer

The following scripts demonstrate how to connect to a network shared printing device. In the first step, the script creates a Network Object. Next, the AddWindowsPrinterConnection method, one of the Network object's methods, performs the connection operation. The AddWindowsPrinterConnection method takes two parameters: the name you wish to call the printer and the Universal Naming Convention (UNC) path to the printing device.

// JScript.
var net;
net = new ActiveXObject("WScript.Network");
net.AddWindowsPrinterConnection("\\\\ServerName\\PrinterName");

' VBScript.
Dim net
Set net = CreateObject("WScript.Network")
net.AddWindowsPrinterConnection "\\ServerName\PrinterName"

Setting Default Printer

The following script demonstrates how to set the desired default printing device. In the first step, the script creates a Network Object. Next, the SetDefaultPrinter method, one of the Network object's methods, performs the operation. The SetDefaultPrinter method takes a single parameter, the name of the printer, which is either the local printer name or a remote printer name using the Universal Naming Convention (UNC) path to the printing device.

// JScript.
var net;
net = new ActiveXObject("WScript.Network");
net.SetDefaultPrinter("\\\\ServerName\\PrinterName");

' VBScript.
Dim net
Set net = CreateObject("WScript.Network")
net.SetDefaultPrinter "\\ServerName\PrinterName"

See Also

Accessing Networks | AddWindowsPrinterConnection Method | SetDefaultPrinter Method | RemovePrinterConnection Method


Creating an Automated Login Script

With WSH you can create automated login scripts. The following example assumes that a company has two file servers (named "server1" and "server2"), and two print servers (named "printer1" and "printer2"). To balance usage of the servers, everyone whose login name starts with A - K goes to the first file and print server, and everyone whose login name starts with L - Z goes to the second one.

Note In Windows 9x, include a delay so user logon takes affect.
// JScript.
var oNet, sUser, cInitial, startTime;
oNet = new ActiveXObject("WScript.Network");
// Get the user name. On Windows 98 and Windows ME, the use may not be logged
// on when the script starts running; keep checking every 1/2 a
// second until they are logged on
sUser = oNet.UserName;
startTime = new Date();
while (sUser == "")
{
   var curTime = new Date();
   if (curTime – startTime > 30000) WScript.Quit();
   WScript.Sleep(500);
   sUser = oNet.UserName;
}
// Add a share for the "h" drive and the printer, based on the
// first letter of the user's name
cInitial = sUser.charAt(0).toUpperCase();
if (cInitial < "L")
{
   oNet.MapNetworkDrive("h:", "\\\\server1\\users\\" + sUser);
   oNet.AddWindowsPrinterConnection("\\\\printer1\\hp", "HP LaserJet 4");
}
else
{
   oNet.MapNetworkDrive("h:", "\\\\server2\\users\\" + sUser);
   oNet.AddWindowsPrinterConnection("\\\\printer2\\hp", "HP LaserJet 4");
}

' VBScript.

Option Explicit
Dim oNet, sUser, cInitial, startTime
' Helper object
Set oNet = CreateObject("WScript.Network")
' Get the user name. On Windows 9x, the use may not be logged
' on when the script starts running; keep checking every 1/2 a
' second until they are logged on.
sUser = oNet.UserName
startTime = Now
Do While sUser = ""
   If DateDiff("s", startTime, Now) > 30 Then Wscript.Quit
   Wscript.Sleep 500
   sUser = oNet.UserName
Loop
' Add a share for the "h" drive and the printer, based on the
' first letter of the user's name
cInitial = UCase(Left(sUser, 1))
If (cInitial < "L") Then
   oNet.MapNetworkDrive "h:", "\\server1\users\" & sUser
   oNet.AddWindowsPrinterConnection "\\printer1\hp", "HP LaserJet 4"
Else
   oNet.MapNetworkDrive "h:", "\\server2\users\" & sUser
   oNet.AddWindowsPrinterConnection "\\printer2\hp", "HP LaserJet 4"
End If

See Also

WSH Samples


Driving Applications

With WSH you can start applications. The following scripts demonstrate some of these capabilities.

Creating a Local Server Application

Some applications, such as Microsoft Word, expose objects which can be accessed programmatically. The following script uses Word's spell checker.

// JScript.
var Word, Doc, Uncorrected, Corrected;
var wdDialogToolsSpellingAndGrammar = 828;
var wdDoNotSaveChanges = 0;
Uncorrected = "Helllo world!";
Word = new ActiveXObject("Word.Application");
Doc = Word.Documents.Add();
Word.Selection.Text = Uncorrected;
Word.Dialogs(wdDialogToolsSpellingAndGrammar).Show();
if (Word.Selection.Text.length != 1)
   Corrected = Word.Selection.Text;
else
   Corrected = Uncorrected;
Doc.Close(wdDoNotSaveChanges);
Word.Quit();

' VBScript.

Dim Word, Doc, Uncorrected, Corrected
Const wdDialogToolsSpellingAndGrammar = 828
Const wdDoNotSaveChanges = 0

Uncorrected = "Helllo world!"
Set Word = CreateObject("Word.Application")
Set Doc = Word.Documents.Add
Word.Selection.Text = Uncorrected
Word.Dialogs(wdDialogToolsSpellingAndGrammar).Show

If Len(Word.Selection.Text) <> 1 Then
Corrected = Word.Selection.Text
Else
   Corrected = Uncorrected
End If

Doc.Close wdDoNotSaveChanges
Word.Quit

Spawning Programs with Shell.Exec Command

The Shell.Exec command provides additional capability beyond the Shell.Run method. These abilities include:

  • Improved environment variable passing
  • Ability to access the standard streams of the executable

The following VBScript sample demonstrates how to use standard streams and the Shell.Exec command to search a disk for a file name that matches a regular expression.

First, here's a small script that dumps to StdOut the full path of every file in the current directory and below:

' VBScript.
'  MYDIR.VBS
Option Explicit
Dim FSO
Set FSO = CreateObject("Scripting.FileSystemObject")
DoDir FSO.GetFolder(".")
Sub DoDir(Folder)
   On Error Resume Next
   Dim File, SubFolder
   For Each File In Folder.Files
      WScript.StdOut.WriteLine File.Path
   Next
   For Each SubFolder in Folder.SubFolders
      DoDir SubFolder
   Next
End Sub

Next, this script searches StdIn for a pattern and dumps all lines that match that pattern to StdOut.

' MyGrep.VBS
Option Explicit
Dim RE, Line
If WScript.Arguments.Count = 0 Then WScript.Quit
Set RE = New RegExp
RE.IgnoreCase = True
RE.Pattern = WScript.Arguments(0)
While Not WScript.StdIn.AtEndOfStream
   Line = WScript.StdIn.ReadLine
   If RE.Test(Line) Then WScript.StdOut.WriteLine Line
WEnd

Together these two scripts do what we want — one lists all files in a directory tree and one finds lines that match a regular expression. Now we write a third program which does two things: it uses the operating system to pipe one program into the other, and it then pipes the result of that to its own StdOut:

// MyWhere.JS
if (WScript.Arguments.Count() == 0)
   WScript.Quit();
var Pattern = WScript.Arguments(0);
var Shell = new ActiveXObject("WScript.Shell");
var Pipe = Shell.Exec("%comspec% /c \"cscript //nologo mydir.vbs | cscript //nologo mygrep.vbs " + Pattern + "\"");
while(!Pipe.StdOut.AtEndOfStream)
   WScript.StdOut.WriteLine(Pipe.StdOut.ReadLine());

See Also

WSH Samples | Exec Method | Run Method


Executing File Management Operations

With WSH you can easily create, copy, move, and delete files and folders programmatically. The following tasks demonstrate these capabilities.

In this Section

Copying Files and Folders

Mapping to a Special Folders

See Also

WSH Samples


Copying Files and Folders

File system manipulation, such as copying files and folders, requires the use of the File System Object (FSO). The following scripts demonstrate the use of the FSO to copy both files and folders.

Copying Files

The following scripts demonstrate how to copy a file from one local folder to another. In the first step, the script creates a File System Object. The CopyFile method, a file system object method, performs the file copy operation. The CopyFile method takes two parameters, the source file and the destination.

// JScript.
var FSO = WScript.CreateObject("Scripting.FileSystemObject");
FSO.CopyFile("c:\\COMPlusLog.txt", "c:\\x\\");

' VBScript.
Dim FSO
Set FSO = CreateObject("Scripting.FileSystemObject")
FSO.CopyFile "c:\COMPlusLog.txt", "c:\x\"

Copying Folders

The following script demonstrates how to copy the contents of one local folder to another folder on the local machine.

Note The destination folder must already 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.

// JScript.
var FSO = WScript.CreateObject("Scripting.FileSystemObject");
FSO.CopyFolder("c:\\x", "c:\\y");

' VBScript.
Dim FSO
Set FSO = CreateObject("Scripting.FileSystemObject")
FSO.CopyFolder "c:\x", "c:\y"

See Also

Executing File Management Operations | FileSystemObject | CopyFile Method | CopyFolder Method | CreateFolder Method | MoveFolder Method


Mapping to a Special Folder

Mapping special folders, such as the My Documents desktop folder, requires the use of the Shell object. The following scripts demonstrate the use of the Shell object to create a shortcut to a folder on the desktop.

// JScript.
var Shell, DesktopPath, URL;
Shell = new ActiveXObject("WScript.Shell");
DesktopPath = Shell.SpecialFolders("Desktop");
URL = Shell.CreateShortcut(DesktopPath + "\\MSDN Scripting.url");
URL.TargetPath = "HTTP://MSDN.Microsoft.com/scripting/";
URL.Save();

' VBScript.
Dim Shell, DesktopPath, URL
Set Shell = CreateObject("WScript.Shell")
DesktopPath = Shell.SpecialFolders("Desktop")
Set URL = Shell.CreateShortcut(DesktopPath & "\MSDN Scripting.URL")
URL.TargetPath = "HTTP://MSDN.Microsoft.com/scripting/"
URL.Save

See Also

Executing File Management Operations


Managing Shortcuts

With WSH you can easily create, delete, move, and copy shortcuts programmatically. The following tasks demonstrate some of these capabilities.

In this Section

Copying a Shortcut

Creating a Shortcut

Deleting a Shortcut

Moving a Shortcut

See Also

WSH Samples


Copying a Shortcut

Copying shortcuts requires the use of the File System Object (FSO). The following scripts demonstrate the use of the File System Object to copy shortcuts.

// JScript.
Shell = new ActiveXObject("WScript.Shell");
FSO = new ActiveXObject("Scripting.FileSystemObject");
DesktopPath = Shell.SpecialFolders("Desktop") + "\\MSDN Scripting url";
MyDocumentsPath = Shell.SpecialFolders("MyDocuments") + "\\"
FSO.CopyFile(DesktopPath, MyDocumentsPath);

' VBScript.
Set Shell = CreateObject("WScript.Shell")
Set FSO = CreateObject("Scripting.FileSystemObject")
DesktopPath = Shell.SpecialFolders("Desktop") + "\MSDN Scripting.url"
MyDocumentsPath = Shell.SpecialFolders("MyDocuments") + "\\"
FSO.CopyFile DesktopPath, MyDocumentsPath

See Also

Managing Shortcuts


Creating a Shortcut

Creating shortcuts requires the use of the File Shell object. The following scripts demonstrate the use of the File Shell object to create shortcuts.

// JScript.
Shell = new ActiveXObject("WScript.Shell");
DesktopPath = Shell.SpecialFolders("Desktop");
link = Shell.CreateShortcut(DesktopPath + "\\test.lnk");
link.Arguments = "1 2 3";
link.Description = "test shortcut";
link.HotKey = "CTRL+ALT+SHIFT+X";
link.IconLocation = "foo.exe,1";
link.TargetPath = "c:\\blah\\foo.exe";
link.WindowStyle = 3;
link.WorkingDirectory = "c:\\blah";
link.Save();

' VBScript.
Set Shell = CreateObject("WScript.Shell")
DesktopPath = Shell.SpecialFolders("Desktop")
Set link = Shell.CreateShortcut(DesktopPath & "\test.lnk")
link.Arguments = "1 2 3"
link.Description = "test shortcut"
link.HotKey = "CTRL+ALT+SHIFT+X"
link.IconLocation = "foo.exe,1"
link.TargetPath = "c:\blah\foo.exe"
link.WindowStyle = 3
link.WorkingDirectory = "c:\blah"
link.Save

See Also

Managing Shortcuts


Deleting a Shortcut

Deleting shortcuts requires the use of the File System Object (FSO). The following scripts demonstrate the use of the File System Object to delete shortcuts.

// JScript.
Shell = new ActiveXObject("WScript.Shell");
FSO = new ActiveXObject("Scripting.FileSystemObject");
DesktopPath = Shell.SpecialFolders("Desktop");
FSO.DeleteFile(DesktopPath + "\\test.lnk")

' VBScript.
Set Shell = CreateObject("WScript.Shell")
Set FSO = CreateObject("Scripting.FileSystemObject")
DesktopPath = Shell.SpecialFolders("Desktop")
FSO.DeleteFile DesktopPath & "\test.lnk"

See Also

Managing Shortcuts


Moving a Shortcut

Moving shortcuts requires the use of the File System Object (FSO). The following scripts demonstrate the use of the File System Object to move shortcuts.

// JScript.

Shell = new ActiveXObject("WScript.Shell");
FSO = new ActiveXObject("Scripting.FileSystemObject");
DesktopPath = Shell.SpecialFolders("Desktop") + "\\test.lnk";
MyDocumentsPath = Shell.SpecialFolders("MyDocuments") + "\\test.lnk";
FSO.MoveFile(DesktopPath, MyDocumentsPath);
' VBScript.

Set Shell = CreateObject("WScript.Shell")
Set FSO = CreateObject("Scripting.FileSystemObject")
DesktopPath = Shell.SpecialFolders("Desktop") & "\test.lnk"
MyDocumentsPath = Shell.SpecialFolders("MyDocuments") & "\test.lnk"
FSO.MoveFile DesktopPath, MyDocumentsPath

See Also

Managing Shortcuts


Manipulating the System Registry

With WSH you can manage the system registry. The following scripts demonstrate some of these capabilities.

// JScript.
Sh = new ActiveXObject("WScript.Shell");
key =  "HKEY_CURRENT_USER\\"
Sh.RegWrite( key + "WSHTest\\", "testkeydefault");
Sh.RegWrite( key + "WSHTest\\string1", "testkeystring1");
Sh.RegWrite( key + "WSHTest\\string2", "testkeystring2", "REG_SZ");
Sh.RegWrite( key + "WSHTest\\string3", "testkeystring3", "REG_EXPAND_SZ");
Sh.RegWrite( key + "WSHTest\\int", 123, "REG_DWORD");
WScript.Echo( Sh.RegRead(key + "WSHTest\\"));
WScript.Echo ( Sh.RegRead(key + "WSHTest\\string1"));
WScript.Echo ( Sh.RegRead(key + "WSHTest\\string2"));
WScript.Echo ( Sh.RegRead(key + "WSHTest\\string3"));
WScript.Echo ( Sh.RegRead(key + "WSHTest\\int"));
Sh.RegDelete(key + "WSHTest\\");

' VBScript.
Set Sh = CreateObject("WScript.Shell")
key =  "HKEY_CURRENT_USER\"
Sh.RegWrite key & "WSHTest\", "testkeydefault"
Sh.RegWrite key & "WSHTest\string1", "testkeystring1"
Sh.RegWrite key & "WSHTest\string2", "testkeystring2", "REG_SZ"
Sh.RegWrite key & "WSHTest\string3", "testkeystring3", "REG_EXPAND_SZ"
Sh.RegWrite key & "WSHTest\int", 123, "REG_DWORD"
WScript.Echo Sh.RegRead(key & "WSHTest\")
WScript.Echo Sh.RegRead(key & "WSHTest\string1")
WScript.Echo Sh.RegRead(key & "WSHTest\string2")
WScript.Echo Sh.RegRead(key & "WSHTest\string3")
WScript.Echo Sh.RegRead(key & "WSHTest\int")
Sh.RegDelete key & "WSHTest\"

See Also

WSH Samples


Running Scripts Remotely

WSH 5.6 can run scripts that reside on remote systems. The following scripts demonstrate this capability. These scripts make the assumption that the files are located on a local machine directory called "c:\wsh5.6"; change the local path and the remote machine name as necessary.

After initially running RemoteTest.WSF on the local machine, there may be a small pause as DCOM verifies your identity. After you see the "Done" message, a file named "c:\beenhere.txt" on the remote machine indicates the time that you executed the command (from the remote computer's clock).

// JScript.
RemoteTest.WSF
-------------------------------
<package>
<job>
<script language="JScript">
var oController = new ActiveXObject("WSHController");
var oProcess = oController.CreateScript("c:\\wsh5.6\\beenhere.wsf", "remmachine");
oProcess.Execute();
while (oProcess.Status != 2) WScript.Sleep(100);
WScript.Echo("Done");
</script>
</job>
</package>
-------------------------------
BeenHere.WSF
-------------------------------
<package>
<job>
<script language="JScript">
var fso = new ActiveXObject("Scripting.FileSystemObject");
var fout = fso.CreateTextFile("c:\\beenhere.txt", true);
fout.WriteLine(new Date);
fout.Close();
</script>
</job>
</package>
-------------------------------

' VBScript.
RemoteTest.WSF
-------------------------------
<package>
<job>
<script language="VBScript">
set oController = CreateObject("WSHController")
set oProcess = oController.CreateScript("c:\wsh5.6\beenhere.wsf", "remmachine")
oProcess.Execute
While oProcess.Status <> 2
   WScript.Sleep 100
WEnd
WScript.Echo "Done"
</script>
</job>
</package>
-------------------------------

BeenHere.WSF
-------------------------------
<package>
<job>
<script language="VBScript">
set fso = CreateObject("Scripting.FileSystemObject")
set fout = fso.CreateTextFile("c:\beenhere.txt", true)
fout.WriteLine Now
fout.Close
</script>
</job>
</package>

See Also

WSH Samples | Setting up Remote WSH | WshRemote Object


Signing a Script

The following scripts demonstrate the creation of a signature, which is used in a verification process. The script uses the Signer Object and the SignFile method to create a digital signature.

// JScript.
<job>
<runtime>
   <named name="file" helpstring="the file to sign" required="true" type="string"/>
   <named name="cert" helpstring="the name of the signing certificate" required="true" type="string"/>
   <named name="store" helpstring="the name of the certificate store" required="false" type="string"/>
</runtime>
<script language="JScript">
   var Signer, File, Cert, Store;
   if (!(WScript.Arguments.Named.Exists("cert") && WScript.Arguments.Named.Exists("file")))
   {
      WScript.Arguments.ShowUsage();
      WScript.Quit();
   }
   Signer = new ActiveXObject("Scripting.Signer");
   File  = WScript.Arguments.Named("file");
   Cert  = WScript.Arguments.Named("cert");
   Store = WScript.Arguments.Named("store");
    Signer.SignFile(File, Cert, Store);
</script>
</job>

'VBScript
<job>
<runtime>
   <named name="file" helpstring="the file to sign" required="true" type="string"/>
   <named name="cert" helpstring="the name of the signing certificate" required="true" type="string"/>
   <named name="store" helpstring="the name of the certificate store" required="false" type="string"/>
</runtime>
<script language="VBScript">
   Dim Signer, File, Cert, Store
   If Not (WScript.Arguments.Named.Exists("cert")) And WScript.Arguments.Named.Exists("file")) Then
      WScript.Arguments.ShowUsage
      WScript.Quit
   End If
   Set Signer = CreateObject("Scripting.Signer")
   File  = WScript.Arguments.Named("file")
   Cert  = WScript.Arguments.Named("cert")
   Store = WScript.Arguments.Named("store")
    Signer.SignFile File, Cert, Store
</script>
</job>

See Also

WSH Samples | Verifying a Script | Signing a Script


WSH and Windows Management Instrumentation (WMI)

With WSH you can easily use Windows Management Instrumentation (WMI). The following scripts demonstrate using WSH and WMI to retrieve a user's logon time via ADSI.

Note For more information on WMI, see the WMI SDK at (http://msdn.microsoft.com).
// JScript.
LoginProfiles = GetObject("winmgmts:").InstancesOf ("Win32_NetworkLoginProfile");
for(e = new Enumerator(LoginProfiles) ; !e.atEnd() ; e.moveNext())
{
   Profile = e.item();
   WScript.Echo(Profile.Name);
   WScript.Echo(Profile.LastLogon);
}

' VBScript.
Set LoginProfiles = GetObject("winmgmts:").InstancesOf ("Win32_NetworkLoginProfile")
   for each Profile in LoginProfiles
      WScript.Echo Profile.Name
      WScript.Echo Profile.LastLogon
   next

See Also

Basic Windows Script Host Tasks


WSH Walkthrough

The following walkthrough describes how a typical Network Administrator or other IT professional might use WSH 5.6 to create procedures that accomplish useful tasks.

Note The walkthrough is presented in VBScript. The process for creating these scripts is nearly the same for developers using VBScript or JScript.

During the course of this walkthrough, you will perform the following activities:

  • Create a script that creates a common share on several remote machines and populate it with files.
  • Create a script that creates a common Printing Device connection on several remote machines and establish it as the default printing device.

To complete the walkthrough, all remote machines must be properly configured to enable Remote WSH. For more information on enabling these security settings, see Setting up Remote WSH.

Note The following code is from the sample included in this documentation. To view the entire sample, see WSH Network Administrator Sample Script.

Create Variables and Constants

To create the necessary variables and constants

  1. In your text-scripting editor, enter the variables.
    Dim 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.
    Const FolderName = "C:\Public"
Const AdminServer = "\\AdminMachine"
Const ShareName = "Pubs"
Const PrinterShare = "\\CorpPrinters\PrinterShare"

Connecting to a printer and setting it as default

To connect the machine to a common printing device

  • In your text-scripting editor, enter the code that creates a printing device. This code uses the Network variable and PrinterShare constant initialized in the previous step.
    Set Network = CreateObject("Wscript.Network")
Network.AddWindowsPrinterConnection PrinterShare

To set the machines default printing device

  • In your text-scripting editor, enter the code that sets the default printing device. This code uses the Network variable and PrinterShare constant initialized in the first step.
    Network.SetDefaultPrinter PrinterShare

Creating a common share, copying files to it, and sharing it

To create a common share on the machine

  • In your text-scripting editor, enter the code that creates a File System Object (FSO) and creates a folder. The script verifies the existence of the folder. If the folder does not exist, the script creates it. This code uses the FSO variable and the FolderName constant initialized in the first step.
    Set FSO = CreateObject("Scripting.FileSystemObject")
If Not FSO.FolderExists(FolderName) Then
   FSO.CreateFolder(FolderName)
End If

To copy files to the newly created folder

  • In your text-scripting editor, enter the code that creates a File System Object (FSO) and copies files from your local machine to the remote machine. This code uses the FSO variable and the FolderName constant initialized in the first step.
    Call FSO.CopyFile(AdminServer & "\Public\Images\*.*", FolderName)

To establish the newly created folder as a share with WMI

  • In your text-scripting editor, enter the code that creates a share using Windows Management Instrumentation (WMI). The share is established on the folder generated above. The script first connects to WMI. Next, it sets the security impersonation level and the Windows NT privilege that lets you set Discretionary Access Control Lists (DACLs) and Security Access Control Lists (SACLs). Next, it creates a new security descriptor and sets up a couple of Access Control Entries (ACEs) for the new share. Finally, it creates a new share with the new security descriptor. This code uses the Services, SecDescClass, SecDesc, Trustee, ACE, Share, and InParam variables, and the FolderName, AdminShare, and ShareName constants initialized in the first step.
    Note WMI is a powerful, sophisticated technology based on Web Based Enterprise Management (WBEM). WMI is primarily used for accessing and instrumenting management information in an enterprise environment. For more information on WMI, see Microsoft Windows Management Instrumentation: Background and Overview at (http://msdn.microsoft.com/library/default.asp?URL=/library/backgrnd/html/wmixwdm.htm).
    Set Services = GetObject("WINMGMTS:{impersonationLevel=impersonate,(Security)}!" & AdminServer & "\ROOT\CIMV2")
Set SecDescClass = Services.Get("Win32_SecurityDescriptor")
Set SecDesc = SecDescClass.SpawnInstance_()
Set Trustee = Services.Get("Win32_Trustee").SpawnInstance_
Trustee.Domain = Null
Trustee.Name = "EVERYONE"
Trustee.Properties_.Item("SID") = Array(1, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0)
Set ACE = Services.Get("Win32_Ace").SpawnInstance_
ACE.Properties_.Item("AccessMask") = 2032127
ACE.Properties_.Item("AceFlags") = 3
ACE.Properties_.Item("AceType") = 0
ACE.Properties_.Item("Trustee") = Trustee
SecDesc.Properties_.Item("DACL") = Array(ACE)
Set Share = Services.Get("Win32_Share")
Set InParam = Share.Methods_("Create").InParameters.SpawnInstance_()
InParam.Properties_.Item("Access") = SecDesc
InParam.Properties_.Item("Description") = "Public Share"
InParam.Properties_.Item("Name") = ShareName
InParam.Properties_.Item("Path") = FolderName
InParam.Properties_.Item("Type") = 0
Share.ExecMethod_("Create", InParam)

Running the Completed Script

The sample included in this documentation contains a complete, executable script with all of the functionality above. See WSH Network Administrator Sample Script.

Before running the script, ensure that all remote machines have been properly configured to run remote scripts. This is accomplished with Poledit.exe on the server. For more information, see Setting up Remote WSH.

When running remote WSH, the script is copied to the remote machines. Once the remote machine's security settings have been verified and the script is successfully copied, a return indicates success or failure. If successful, the script is then executed on the remote machines. For more information on running a remote WSH script, see Running Scripts Remotely.

See Also

Setting up Remote WSH | Accessing Networks | Running Scripts Remotely


WSH Network Administrator Sample Script

This WSH network sample demonstrates how a typical network administrator may use a script on several remote machines on the network. The sample script performs useful administrative tasks including:

  • Connecting the machines to a network printing device
  • Setting the newly connected printing device as the default printer
  • Creating a common public folder on the machines
  • Copying files to the newly created folder
  • Establishing the newly created folder as a share using Windows Management Instrumentation (WMI).
    Note WMI is a powerful, sophisticated technology based on Web Based Enterprise Management (WBEM). WMI is primarily used for accessing and instrumenting management information in an enterprise environment. For more information on WMI, see Microsoft Windows Management Instrumentation: Background and Overview at (http://msdn.microsoft.com/library/default.asp?URL=/library/backgrnd/html/wmixwdm.htm).

The Administrator must establish the necessary security settings on the remote machines. For more information, see Setting up Remote WSH. Next the administrator must copy and paste the sample into the scripting editor and change the constants to reflect the corresponding network paths and machine names. Finally the administrator can run the script.

To run this sample

  1. 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:
    var oController = new ActiveXObject"WSHController"
var oProcess = oController.CreateScript "c:\MyLocalDir\\AdminScript.vbs", "remmachine"
oProcess.Execute()
while (oProcess.Status != 2)
     WScript.Sleep(100)
WScript.Echo"Done"

AdminScript.vbs Sample

' Remote WSH Admin Sample  AdminScript.vbs
'
' 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

WSH Walkthrough | Accessing Networks | Setting up Remote WSH | Running Scripts Remotely


Security and Windows Script Host

Windows Script Host, which is a flexible tool for automating Windows, can be dangerous in the hands of someone who is bent on wreaking havoc.

To prevent abuse of Windows Script Host without stifling its power, Windows Script Host 5.6 employs a new security model.

Script users can now verify the authenticity of a script before running it. Script developers can sign their scripts to prevent unauthorized modifications. Administrators can enforce strict policies that determine which users have privileges to run scripts locally or remotely.

In this Section

CryptoAPI Tools

Signing a Script

Signature Verification Policy

Verifying a Script

Software Restriction Policies


CryptoAPI Tools

The CryptoAPI Tools are used to create and verify digital signatures in *.exe, *.cab, *.dll, *.ocx, and script (*js, *.vbs, and *.wsf) files.

CryptoAPI Tools are used to digitally sign files to be used with Microsoft® Authenticode®, and to view and manage certificates, certificate revocation lists (CRLs), and certificate trust lists (CTLs). For more information on CrptoAPI Tools, see the CryptoAPI Start Page at (http://msdn.microsoft.com/library/psdk/crypto/portalapi_3351.htm?RLD=290).

See Also

Security and Windows Script Host | Signing a Script | Verifying a Script | Signature Verification Policy


Signing a Script

Signing a script writes a digital signature block of comments in a script. The signature, which contains encoded information about the identity of the author, also encapsulates encoded information about the script itself. Consequently, any attempt to change the script invalidates the signature.

Script signing is programmatically accomplished with the Scripting.Signer object's SignFile method.

<job>
<runtime>
   <named name="file" helpstring="the file to sign" required="true" type="string"/>
   <named name="cert" helpstring="the name of the signing certificate" required="true" type="string"/>
   <named name="store" helpstring="the name of the certificate store" required="false" type="string"/>
</runtime>
<script language="JScript">
   var Signer, File, Cert, Store;
   if (!(WScript.Arguments.Named.Exists("cert") && WScript.Arguments.Named.Exists("file")))
   {
      WScript.Arguments.ShowUsage();
      WScript.Quit();
   }
   Signer = new ActiveXObject("Scripting.Signer");
   File  = WScript.Arguments.Named("file");
   Cert  = WScript.Arguments.Named("cert");
   if (WScript.Arguments.Named.Exists("store"))
   {
      Store = WScript.Arguments.Named("store");
   }
   else
   {
      Store = "";
   }
    Signer.SignFile(File, Cert, Store);
</script>
</job>
Note In order to sign a script, you must have a valid certificate. Ask your Administrator about your certification policy or contact a commercial certification authority.

See Also

Security and Windows Script Host | Verifying a Script | Signature Verification Policy | WinTrust | Signing a Script


Software Restriction Policies

Software Restriction Policies are trust policies, which are regulations set by an administrator to restrict scripts that are not fully trusted from performing unauthorized actions within the operating system.

The following three criteria are used by Software Restriction Policies in determining a trust level:

  • Any signature information in the script
  • The path from which the script is running
  • File content

Software Restriction Policies define the following default containers:

  • Domain Administrator
  • Machine Administrator
  • Machine User
  • Guest User
  • Denied

Additionally, you can define your own custom container and set your own policies.

See Also

Security and Windows Script Host


Signature Verification Policy

In WSH, administrators have the choice to turn signature verification either on or off. If an administrator turns signature verification on, then the machine will only run scripts signed by trusted authorities. With signature verification turned on, there are two possible scenarios:

  • If the trust can't be determined, then the user is prompted to confirm that the script should run.
  • If the trust can't be determined, then the script does not run.

If an administrator turns signature verification off, the machine permits users to run any script.

In Windows 2000, the signature verification policy is set through the Local Security Policy editor. For more information on the Local Security Policy Editor and WSH settings, see the online Windows help system.

The signature verification policy registry key is located in the following hive:

\HKEY_CURRENT_USER\SOFTWARE\Microsoft\Windows Script Host\Settings\TrustPolicy

The key is set to one of the following REG_DWORD values:

  • 0 Run all scripts
  • 1 Prompt user if script is untrusted
  • 2 Run only trusted scripts

See Also

Security and Windows Script Host | Signing a Script | Verifying a Script | WinTrust


Verifying a Script

Verifying a script determines whether the script that you are about to run is from a trusted source. It also allows you to confirm the integrity of the script. WSH verifies scripts before it attempts to run them, but you may have your own reason to verify a script.

Script verification is accomplished programmatically with the Signer object's VerifyFile method.

The VerifyFile method:

  • Verifies the validity of the signature.
  • Verifies that the signature belongs to a person who is trusted in your Trusted Publishers List.
  • Verifies that the script has not been changed since it was signed.
Note Although 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

Security and Windows Script Host | Signing a Script | Signature Verification Policy | WinTrust


Reference

In this Section

XML Elements
List of WSH XML Elements.
Objects
List of WSH Objects.
Properties
List of WSH Properties.
Methods
List of WSH Methods.
Events
List of WSH Events
Error Messages
List of WSH Error Messages.

Related Sections

WSH Basics
Learn the basics of WSH.


XML Elements

In this Section

<?job?> Element
XML processing instruction that specifies attributes for error handling.
<?XML?> Element
Indicates that a file should be parsed as XML.
<description> Element
Marks the descriptive text that appears when the user runs ShowUsage() or runs the script with the /? command line switch.
<example> Element
Makes your script self documenting.
<job> Element
Marks the beginning and the end of a job within a Windows Script file (*.wsf).
<named> Element
Marks a particular named argument to the script.
<object> Element
XML element that is used in Windows Script component files and that defines objects that can be referenced by script.
<package> Element
Encloses multiple job definitions in a Windows Script Host control (.wsf) file.
<reference> Element
XML element that includes a reference to an external type library.
<resource> Element
XML element that isolates textual or numeric data that should not be hard-coded into a script.
<runtime> Element
Groups together the set of run-time arguments for a script.
<script> Element
XML element that contains script to define the behavior of a Windows Script component.

Related Sections

WSH Reference
List of elements that make up WSH Reference.
WSH Basics
Learn the basics of WSH.


<?job ?> Element

Windows Script Host

<?job?> Element

Specifies attributes for error handling.

<?job error="flag" debug="flag" ?>

Arguments

error
A Boolean value. False is the default value for all attributes. Set to true to allow error messages for syntax or run-time errors in the Windows Script (.wsf) file.
Debug
A Boolean value. False is the default value for all attributes. Set to true to enable debugging. If debugging is not enabled, you will be unable to launch the script debugger for a Windows Script file.

Remarks

Although most Windows Script files normally run silently during production, you might find it useful to be notified of errors in the Windows Script (.wsf) file as you are developing it.

Example

The following example incorporates two jobs into one .wsf file that uses two different scripting languages.

<package>
   <job id="DoneInVBS">
      <?job debug="true"?>
      <script language="VBScript">
         WScript.Echo "This is VBScript"
      </script>
   </job>

   <job id="DoneInJS">
      <?job debug="true"?>
      <script language="JScript">
         WScript.Echo("This is JScript");
      </script>
   </job>
</package>

See Also

<runtime> Element | <named> Element | <description> Element | <example> Element | <object> Element | <package> Element | <resource> Element | <?XML?> Element


<?XML ?> Element

Windows Script Host

<?XML?> Element

Indicates that a file should be parsed as XML.

<?XML version="version" [standalone="DTDflag"] ?>

Arguments

version
A string in the form n.n specifying the XML level of the file. Use the value 1.0.
DTDflag
Optional. Boolean value indicating whether the XML file includes a reference to an external Document Type Definition (DTD). Script component XML files do not include such a reference, so the value for this attribute is always "yes."

Remarks

This declaration must be the first element in the file and cannot be preceded by any blank lines.

The existence of this declaration puts the script component compiler into strict XML mode, where element types and attribute names are case-sensitive, attribute values are enclosed in single or double quotation marks, and all elements are parsed. If the declaration is not included, the compiler allows syntax that is less strict.

You should include this declaration and follow XML conventions if your script component file will be edited in an editor that supports XML.

Example

The following example demonstrates the use of the <?XML?> Element:

<?XML version="1.0" standalone="yes" ?>

See Also

<runtime> Element | <named> Element | <description> Element | <example> Element | <object> Element | <package> Element | <resource> Element | <?job?> Element


<description> Element

Marks the descriptive text that is displayed when the ShowUsage method is executed or when the script is run with the /? command line switch.

<description>
    This section describes the script
</description>

Remarks

Your description can be more than one line long.

Do not include quotes in your description if you do not want them to appear in the usage. All text between the description tags appears in the usage listing. This includes, among others, tabs, new lines, and special characters.

The <description> element is similar to the <example> element, except it appears at the start of the usage, whereas the <example> element appears at the end.

Example

The following script demonstrates the use of the <description> Element:

<runtime>
    <description>
        This script reboots a server
    </description>
    <!--...etc...-->
</runtime>

See Also

ShowUsage Method | <runtime> Element | <named> Element | <unnamed> Element | <example> Element


<example> Element

Provides an example of usage for the job.

<example>
   Example text
</example>

Remarks

The <example> element is enclosed within the <runtime> element.

Example

The following script demonstrates the use of the <example> Element:

<job>
    <runtime>
        <description>This script reboots a server</description>
        <named
            name = "Server"
            helpstring = "Server to run the script on"
            type = "string"
            required = "true"
        />
        <example>Example: reboot.wsf /Server:scripting</example>
    </runtime>
</job>

Everything between <example> and </example> tags gets picked up, including new lines and extra white space. Calling the ShowUsage method from this script results in the following output:

This script reboots a server

Usage: reboot.wsf /server:value

Options:

server : Server to run the script on

Example:

reboot.wsf /server:scripting

See Also

ShowUsage Method


<job> Element

Marks the beginning and the end of a job within a Windows Script file (*.wsf).

<job [id=JobID]>
    job code
</job>

Arguments

JobID
Optional. Uniquely identifies the job within the scope of the Windows Script file.

Remarks

Each jobID within a Windows Script file must be unique.

Each script within a set of job tags is executed in sequence, from top to bottom.

A job contains one or more script blocks. A script block is any script code between a set of <script> tags. A script block can contain several scripts, and each script can be in a different scripting language.

To run a specific job or to run multiple jobs, use the //Job switch. If you specify more than one job, the jobs are executed in sequential order. (This is shown in the example below.). If you do not specify a job, only the first job is run. If you have two or more jobs in your Windows Script file, they must be enclosed in a <package> tag.

Example

The following script example is a Windows Script file called myScript.wsf. This file contains two separate jobs, each written in a different scripting language. The first job, written in VBScript, is given the identifier DoneInVBS. The second job, written in JScript, is given the identifier DoneInJS.

<package>
    <job id="DoneInVBS">
    <?job debug="true"?>
        <script language="VBScript">
           WScript.Echo "This is VBScript"
        </script>
    </job>
    <job id="DoneInJS">
    <?job debug="true"?>
        <script language="JScript">
           WScript.Echo("This is JScript");
        </script>
    </job>
</package>

To run the second job in the Windows Script file, myScript.wsf, type the following at the command prompt.

cscript myScript.wsf //job:DoneInJS

To run both jobs in myScript.wsf, type the following at the command prompt.

cscript myScript.wsf //job:DoneInVBS //job:DoneInJS

See Also

ShowUsage Method | <runtime> Element | <named> Element | <unnamed> Element | <description> Element | <example> Element


<named> Element

Describes a named argument for the script.

<named
   name = namedname
   helpstring = helpstring
   type = "string|boolean|simple"
   required = boolean
/>

Arguments

name
String that represents the name of the argument you are describing. Defines the argument at the command line and in the script.
helpstring
String that represents the help description for the argument. The WSH runtime provides the help description using the ShowUsage method or the /? argument.
type
Optional. Describes the type of argument, which defines how the argument will be parsed from the command line. The default value is simple.
required
Optional. A Boolean value that indicates whether an argument is required or not. Affects the display of the usage only.

Remarks

The <named> element is contained by (enclosed within) a set of runtime tags.

An argument with the name server would provide a /server argument at the command line as well as an argument named server in the WSHNamed arguments collection.

If the type is string, the argument is a string. The argument is passed to the script as /named:stringvalue.

If the type is Boolean, the argument is Boolean. The argument is passed to the script as /named+ to turn it on, or /named- to turn it off.

If the type is simple, the argument takes no additional value and is passed as just the name, /named.

Example

The following script demonstrates the use of the <named> Element:

<job>
<runtime>
  <named
    name="server"
    helpstring="Server to access"
    type="string"
    required="true"
  />
  <named
    name="user"
    helpstring="User account to use on server. Default is current account."
    type="string"
    required="false"
  />
  <named
    name="enable"
    helpstring="If true (+), enables the action. A minus(-) disables."
    type="boolean"
    required="true"
  />
  <named
    name="verbose"
    helpstring="If specified, output will be verbose."
    type="boolean"
    required="false"
  />
</runtime>
<script language="JScript">
  WScript.Arguments.ShowUsage();
</script>
</job>

This will produce the following output when usage is shown:

Usage: example.wsf /server:value [/user:value] /enable[+|-] [/verbose]

Options:

server    : 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.

See also

ShowUsage Method | <runtime> Element | <unnamed> Element | <description> Element | <example> Element


<object> Element

Defines objects in Windows Script (.wsf) files that can be referenced by a script.

<object id="objID" [classid="clsid:GUID" | progid="progID"] />

Arguments

objID
Required. A name that references the object in your script. Object ID values must begin with a letter and can include letters, digits, and underscores (_). The object ID must be unique throughout the scope of the Windows Script file.
GUID
Optional. The class ID (GUID) of the object.
progID
Optional. Program ID of the object, which can be specified as an alternative to the class ID.

Remarks

The <object> element provides a way to expose objects globally for use in scripting within the Windows Script file without using functions such as CreateObject(). Using an <object> element makes the object available with global scope and enables scripting tools to provide statement completion for the object's members.

You must specify either a classid or a progid.

Example

<job>
<obect id="fso" progid="Scripting.FileSystemObject"/>
<script language="Jscript">

var a = fso.CreateTextFile("c:\\testfile.txt", true);
a.WriteLine("This is a test.");
a.Close();

</script>
</job>

See Also

<runtime> Element | <named> Element | <description> Element | <example> Element | <package> Element


<package> Element

Encloses multiple job definitions in a Windows Script (.wsf) file.

<package>
   code for one or more jobs
</package>

Remarks

The <package> element is optional when a .wsf file contains only one job.

Example

The following example incorporates two jobs into one .wsf file that uses two different scripting languages:

<package>
   <job id="DoneInVBS">
   <?job debug="true"?>
      <script language="VBScript">
         WScript.Echo "This is VBScript"
      </script>
   </job>

   <job id="DoneInJS">
   <?job debug="true"?>
      <script language="JScript">
         WScript.Echo("This is JScript");
      </script>
   </job>
</package>

See Also

<runtime> Element | <named> Element | <description> Element | <example> Element | <object> Element


<reference> Element

Includes a reference to an external type library.

<reference [object="progID"|guid="typelibGUID"] [version="version"] />

Arguments

progID
Program ID from which the type library can be derived. It can include either a version number (for example, ADO.Recordset.2.0), the explicit program ID of a type library, or the program ID of the executable (such as a .DLL) that incorporates the type library. If you use the object attribute, you do not need to specify a version attribute because the version can be inferred from the program ID. If the object attribute is specified, you cannot also specify a GUID attribute.
typelibGUID
The GUID of the type library to reference. If the GUID attribute is specified, you cannot also specify an object attribute.
version
Optional. Version number of the type library to use. It must be in the form <major version>[.<minor version>]. If a version is not specified, the default version is 1.0. If the object attribute is used to specify the type library and the version is not specified, the version is derived from the registry key for the specified program ID. If none can be found, the default is 1.0.

Remarks

Referencing a type library in your Windows Script (.wsf) file enables you to use constants defined in the type library in your scripts. The <reference> element looks up and makes available the type library associated with a specific program ID or type library name. Type library information can be available in .tlb, .olb, or .dll files.

See Also

<runtime> Element | <named> Element | <description> Element | <example> Element | <object> Element | <package> Element


<resource> Element

Isolates textual or numeric data that should not be hard-coded into a script.

<resource id="resourceID">
   text or number
</resource>

Arguments

resourceID
Unique identifier for the resource within the script.

Remarks

The <resource> element allows you to isolate strings or numbers in your Windows Script (.wsf) file that you want to reference in your scripts. For example, resource elements are typically used to maintain strings that may be localized into other languages.

To get the value of a resource, call the getResource method, passing it the ID of the resource you want to use.

Everything within the elements gets used including white space (tabs, new lines, etc.).

Example

The following code defines a resource (errNonNumeric) and returns its value if the variable upperBound is not numeric.

<resource id="errNonNumeric">
   Non-numeric value passed
</resource>

<script language="VBScript">
   <![CDATA[
      Function getRandomNumber(upperBound)
         If IsNumeric(upperBound) Then
            getRandomNumber = CInt(upperBound * Rnd + 1)
         Else
            getRandomNumber=getResource("errNonNumeric")
         End If
      End Function
   ]]>
</script>

See Also

<runtime> Element | <named> Element | <description> Element | <example> Element | <object> Element | <package> Element | getResource Method


<runtime> Element

Groups together the set of run-time arguments for a script.

<runtime>
    <named attributes etc. />
    <unnamed attributes etc. />
    <example>Example Text</example>
    …
</runtime>

Remarks

The ShowUsage method uses the information enclosed by the <runtime> element to display the runtime parameters for a script.

Since the <runtime> element is enclosed within a set of job tags, the defined run-time arguments apply to that job only.

Note With version 5.6, the 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.

Example

The following script demonstrates the use of the <runtime> Element:

<job>
    <runtime>
        <named
            name="server"
            helpstring="The server to run the script on"
            type="string"
            required="true"
        />
    </runtime>
<script language="JScript">
  if (!WScript.Arguments.Named.Exists("server"))
  {
    WScript.Arguments.ShowUsage();
  }
// ... some script here
</script>
</job>

See Also

ShowUsage Method | <named> Element | <unnamed> Element | <description> Element | <example> Element


<script> Element

Contains script that defines the behavior of a Windows Script (.wsf) file.

<script language="language" [src="strFile"]>
     script here
</script>

Arguments

language
The name of the scripting language, such as VBScript or JScript, used in the script block.
strFile
The name of the script file to include into the script block.

Remarks

If XML validation is not enabled, the XML parser ignores all lines inside the <script> element. However, if XML validation is enabled by including the <?XML?> element at the top of the Windows Script (.wsf) file, the XML parser can misinterpret greater than (>), less than (<), and other symbols used in script as XML delimiters.

If you are creating a file that conforms closely to XML syntax, you must ensure that characters in your script element are not treated as XML-reserved characters. To do this, enclose the actual script in a <![CDATA[ ... ]]> section. This applies to all data blocks - <example>, <description>, and <resource>. All may need CDATA markers if <?XML?> is specified and if they include XML-reserved characters.

Note Do not include a CDATA section unless you also include the <?XML?> declaration.

Example

The following example incorporates two jobs into one .wsf file, using two different scripting languages:

<package>
   <job id="DoneInVBS">
   <?job debug="true"?>
      <script language="VBScript">
         WScript.Echo "This is VBScript"
      </script>
   </job>

   <job id="DoneInJS">
   <?job debug="true"?>
      <script language="JScript">
         WScript.Echo("This is JScript");
      </script>
   </job>
</package>

See Also

<runtime> Element | <named> Element | <description> Element | <example> Element | <object> Element | <package> Element | <resource> Element | <?XML?> Element


<unnamed> Element

Describes an unnamed argument for the script.

<unnamed
   name       = unnamedname
   helpstring = helpstring
   many       = boolean
   required   = boolean or integer
/>

Arguments

name
The string that is used in the usage to represent this argument. This value is not used elsewhere.
helpstring
String that represents the help description for the argument. The WSH runtime provides the help description using the ShowUsage method or the /? argument.
many
Optional. Boolean value. If true, then this argument may be repeated more times than specified by the required attribute. Otherwise, the required attribute represents the exact number of the argument that is required. See the example below for more details.
required
Optional. An integer value indicating how many times this argument should appear in the command line.

Remarks

The <unnamed> element is contained by (enclosed within) a set of runtime tags.

An argument with the name server would provide a /server argument at the command line and an argument named server in the WSHNamed arguments collection.

Note The name attribute of the unnamed element is just for display purposes.

When setting the "required" attribute, a Boolean value will be converted to an integer; "true" becomes 1 and "false" becomes 0.

Example

Here are a couple of examples of how the various attributes affect the usage with unnamed elements. First, a simple case:

<runtime>
<unnamed
  name="filename"
  helpstring="The file to process"
  many="false"
  required="true"
</>
</runtime>

This would produce the following:

Usage: example.wsf filename

Options:

filename : The file to process

Change it to:

<runtime>
<unnamed
  name="filename"
  helpstring="The files to process"
  many="false"
  required="3"
</ >
</runtime>

and the output changes to:

Usage: example.wsf filename1 filename2 filename3

Options:

filename : The files to process

The many switch will display ellipses to indicate you can enter more files than indicated. If the example changes to:

<runtime>
<unnamed
  name="filename"
  helpstring="The file(s) to process"
  many="true"
  required="1"
</>
</runtime>

then the output changes to:

Usage: example.wsf filename1 [filename2...]

Options:

filename: The file to process.

See also

ShowUsage Method | <runtime> Element | <named> Element | <description> Element | <example> Element


<usage> Element

Allows user to override default usage display.

<usage>
    This section describes the script
</usage>

Remarks

The <usage> element is similar to the <example> and <description> elements — it contains text that the developer can include in the usage. The difference is that if a <usage> element exists, everything else in the <runtime> element is ignored, and only the text in the <usage> element is displayed. This is so you can completely override the usage display.

Note The <usage> Element should always be enclosed by a <runtime> Element.

Example

The following script demonstrates the use of the <usage> Element:

<job>
<runtime>
<named name="arg1" helpstring="the first arg"/>
<usage>
Your usage text goes here.
</usage>
</runtime>
<script language="vbscript">
WScript.Arguments.ShowUsage
</script>
</job>

This produces the following:

Your usage text goes here.

See Also

<runtime> Element | <named> Element | <description> Element | <example> Element | <package> Element | <resource> Element | <?XML?> Element


Objects

In this Section

WScript Object
Provides access to most of the objects, methods, and properties in the WSH object model.
WshArguments Object
Gives you access to the entire collection of command-line parameters — in the order in which they were originally entered.
WshController Object
Exposes the method CreateScript() that creates a remote script process.
WshEnvironment Object
Gives you access to the collection of Microsoft Windows system environment variables.
WshNamed Object
Provides access to the named command-line script arguments within the WshArguments object.
WshNetwork Object
Gives you access to the shared resources on the network to which your computer is connected.
WshRemote Object
Provides access to the remote script process.
WshRemoteError Object
Exposes the error information available when a remote script (a WshRemote object) terminates as a result of a script error.
WshScriptExec Object
Provides status and error information about a script run with Exec, along with access to the stdIn, stdOut, and stdErr channels.
WshShell Object
Gives you access to the native Windows shell functionality.
WshShortcut Object
Allows you to create a shortcut programmatically.
WshSpecialFolders Object
Allows you to access the Windows Special Folders.
WshUnnamed Object
Provides access to the unnamed command-line script arguments within the WshArguments object.
WshUrlShortcut Object
Allows you to create a shortcut to an Internet resource, programmatically.

Related Sections

WSH Reference
List of elements that make up WSH Reference.
WSH Basics
Learn the basics of WSH.


Scripting.Signer Object

The Scripting.Signer object enables an author to sign a script with a digital signature and a recipient to verify the signature's authenticity and trustworthiness.

Remarks

The Scripting.Signer object requires a valid certificate.

Example

The following JScript code shows the Scripting.Signer object digitally signing a script.

<job>
<runtime>
   <named name="file" helpstring="the file to sign" required="true" type="string"/>
   <named name="cert" helpstring="the name of the signing certificate" required="true" type="string"/>
   <named name="store" helpstring="the name of the certificate store" required="false" type="string"/>
</runtime>
<script language="JScript">
   var Signer, File, Cert, Store = "my";
   if (!(WScript.Arguments.Named.Exists("cert") && WScript.Arguments.Named.Exists("file")))
   {
      WScript.Arguments.ShowUsage();
      WScript.Quit();
   }
   Signer = new ActiveXObject("Scripting.Signer");
   File  = WScript.Arguments.Named("file");
   Cert  = WScript.Arguments.Named("cert");
   if (WScript.Arguments.Named.Exists("store"))
   {
      Store = WScript.Arguments.Named("store");
   }

    Signer.SignFile(File, Cert, Store);
</script>
</job>

See Also

Signing a Script | Sign Method | SignFile Method | Verify Method | VerifyFile Method


Scripting.Signer Object Methods

Methods

Sign Method

SignFile Method

Verify Method

VerifyFile Method


WScript Object

Provides access to root object for the Windows Script Host object model.

Remarks

The WScript object is the root object of the Windows Script Host object model hierarchy. It never needs to be instantiated before invoking its properties and methods, and it is always available from any script file. The WScript object provides access to information such as:

  • command-line arguments,
  • the name of the script file,
  • the host file name,
  • and host version information.

The WScript object allows you to:

  • create objects,
  • connect to objects,
  • disconnect from objects,
  • sync events,
  • stop a script's execution programmatically,
  • output information to the default output device (either a Windows dialog box or the command console).

The WScript object can be used to set the mode in which the script runs (either interactive or batch).

Example

Since the WScript object is the root object for the Windows Script Host object model, many properties and methods apply to the object. For examples of specific syntax, visit the properties and methods links.

Properties

Arguments Property | FullName Property (WScript Object) | Interactive Property | Name Property | Path Property | ScriptFullName Property | ScriptName Property | StdErr Property | StdIn Property | StdOut Property | Version Property

Methods

CreateObject Method | ConnectObject Method | DisconnectObject Method | Echo Method | GetObject Method | Quit Method | Sleep Method

See Also

Running Your Scripts | WshShell Object | WshNetwork Object


WScript Object Properties and Methods

Properties

Arguments Property

FullName Property

Name Property

Path Property

ScriptFullName Property

ScriptName Property

StdErr Property

StdIn Property

StdOut Property

Version Property

Methods

CreateObject Method

ConnectObject Method

DisconnectObject Method

Echo Method

GetObject Method

Quit Method

Sleep Method


WshArguments Object

Arguments PropertyWScript Object

Provides access to the entire collection of command-line parameters — in the order in which they were originally entered.

Remarks

The WshArguments object is a collection returned by the WScript object's Arguments property (WScript.Arguments). Two of the WshArguments object's properties are filtered collections of arguments — one contains the named arguments (querying this property returns a WshNamed object), the other contains the unnamed arguments (querying this property returns a WshUnnamed object). There are three ways to access sets of command-line arguments.

  • You can access the entire set of arguments (those with and without names) with the WshArguments object.
  • You can access the arguments that have names with the WshNamed object.
  • You can access the arguments that have no names with the WshUnnamed object.

Example

The following code displays the command-line parameters in the WshArguments object.

[VBScript]
Set objArgs = WScript.Arguments
For I = 0 to objArgs.Count - 1
   WScript.Echo objArgs(I)
Next
[JScript]
objArgs = WScript.Arguments;
for (i = 0; i < objArgs.length; i++)
{
   WScript.Echo(objArgs(i));
}

Properties

Item Property | Length Property (WshArguments object) | Count Property | Named Property | Unnamed Property

Methods

Count Method | ShowUsage Method

See Also

Arguments Property | WshNamed Object | WshUnnamed Object


WshArguments Object Properties and Methods

Properties

Item Property

Length Property

Methods

Count Method


WshController Object

'WScript Object

Provides access to the CreateScript() method (for creating a remote script process).

Example

The following example uses a controller object to create a WshRemote object.

[VBScript]
Dim Controller, RemoteScript
Set Controller = WScript.CreateObject("WSHController")
Set RemoteScript = Controller.CreateScript("remote1.js")
RemoteScript.Execute

Do While RemoteScript.Status <> 2
    WScript.Sleep 100
Loop
[JScript]
var Controller = WScript.CreateObject("WSHController");
var RemoteScript = Controller.CreateScript("test.js", "remoteserver");
RemoteScript.Execute();

while (RemoteScript.Status != 2) {
    WScript.Sleep(100);
}

Methods

CreateScript Method

See Also

CreateObject Method


WshController Object Methods

Methods

CreateScript Method


WshEnvironment Object

Environment PropertyWshShell Object

Provides access to the collection of Windows environment variables.

Remarks

The WshEnvironment object is a collection of environment variables that is returned by the WshShell object's Environment property. This collection contains the entire set of environment variables (those with names and those without). To retrieve individual environment variables (and their values) from this collection, use the environment variable name as the index.

Example

The following code displays an environment variable.

[VBScript]
Set WshShell = WScript.CreateObject("WScript.Shell")
Set WshSysEnv = WshShell.Environment("SYSTEM")
WScript.Echo WshSysEnv("NUMBER_OF_PROCESSORS")
[JScript]
var WshShell = WScript.CreateObject("WScript.Shell");
var WshSysEnv = WshShell.Environment("SYSTEM");
WScript.Echo(WshSysEnv("NUMBER_OF_PROCESSORS"));

Properties

Item Property | Length Property (WshEnvironment object)

Methods

Count Method | Remove Method

See Also

Environment Property


WshEnvironment Object Properties and Methods

Properties

Item Property

Length Property

Methods

Count Method

Remove Method


WshNamed Object

Named PropertyWshArguments Object

Provides access to the named arguments from the command line.

Remarks

The Named property of the WshArguments object returns the WshNamed object, which is a collection of arguments that have names. This collection uses the argument name as the index to retrieve individual argument values. There are three ways to access sets of command-line arguments.

  • You can access the entire set of arguments (those with and without names) with the WshArguments object.
  • You can access the arguments that have names with the WshNamed object.
  • You can access the arguments that have no names with the WshUnnamed object.

Example

The following code displays the number of named and unnamed command-line arguments.

<package>
<job id="JS">
<script language="JScript">

var argsNamed = WScript.Arguments.Named;
var argsUnnamed = WScript.Arguments.Unnamed;

WScript.Echo("There are " + argsNamed.length + " named arguments.");
WScript.Echo("There are " + argsUnnamed.length + " unnamed arguments.");

</script>
</job>

<job id="VBS">
<script language="VBScript">

Dim argsNamed, argsUnnamed
Set argsNamed = WScript.Arguments.Named
Set argsUnnamed = WScript.Arguments.Unnamed

WScript.Echo "There are " & argsNamed.Count & " named arguments."
WScript.Echo "There are " & argsUnnamed.Count & " unnamed arguments."

</script>
</job>
</package>

Properties

Item Property | Length Property

Methods

Count Method | Exists Method

See Also

WshArguments Object | WshUnnamed Object


WshNamed Object Properties and Methods

Properties

Item Property

Length Property

Methods

Count Method

Exists Method


WshNetwork Object

WScript Object

Provides access to the shared resources on the network to which your computer is connected.

Remarks

You create a WshNetwork object when you want to connect to network shares and network printers, disconnect from network shares and network printers, map or remove network shares, or access information about a user on the network.

Example

The following example demonstrates displaying the domain name, computer name, and user name for the current computer system using the WshNetwork object.

<package>
   <job id="vbs">
      <script language="VBScript">
         Set WshNetwork = WScript.CreateObject("WScript.Network")
         WScript.Echo "Domain = " & WshNetwork.UserDomain
         WScript.Echo "Computer Name = " & WshNetwork.ComputerName
         WScript.Echo "User Name = " & WshNetwork.UserName
      </script>
   </job>

   <job id="js">
      <script language="JScript">
         var WshNetwork = WScript.CreateObject("WScript.Network");
         WScript.Echo("Domain = " + WshNetwork.UserDomain);
         WScript.Echo("Computer Name = " + WshNetwork.ComputerName);
         WScript.Echo("User Name = " + WshNetwork.UserName);
      </script>
   </job>
</package>

Properties

ComputerName Property | UserDomain Property | UserName Property

Methods

AddWindowsPrinterConnection Method | AddPrinterConnection Method | EnumNetworkDrives Method | EnumPrinterConnection Method | MapNetworkDrive Method | RemoveNetworkDrive Method | RemovePrinterConnection Method | SetDefaultPrinter Method

See Also

Running Your Scripts | WScript Object


WshNetwork Object Properties and Methods

Properties

ComputerName Property

UserDomain Property

UserName Property

Methods

AddPrinterConnection Method

EnumNetworkDrives Method

EnumPrinterConnection Method

MapNetworkDrive Method

RemoveNetworkDrive Method

RemovePrinterConnection Method

SetDefaultPrinter Method


WshRemote Object

WshController Object

Provides access to the remote script process.

Remarks

The WshRemote object allows you to remotely administer computer systems on a computer network. It represents an instance of a WSH script, i.e., a script file with one of the following extensions: .wsh, .wsf, .js, .vbs, .jse, .vbe, and so on. An instance of a running script is a process. You can run the process either on the local machine or on a remote machine. If you do not provide a network path, it will run locally. When a WSHRemote object is created (by using the CreateScript() method), the script is copied to the target computer system. Once there, the script does not begin executing immediately; it begins executing only when the WSHRemote method Execute is invoked. Through the WshRemote object interface, your script can manipulate other programs or scripts. Additionally, external applications can also manipulate remote scripts. The WshRemote object works asynchronously over DCOM.

Example

The following example demonstrates how the WshRemote object is used to start a remote script.

[VBScript]
Dim Controller, RemoteScript
Set Controller = WScript.CreateObject("WSHController")
Set RemoteScript = Controller.CreateScript("test.js", "remoteserver")
RemoteScript.Execute

Do While RemoteScript.Status <> 2
    WScript.Sleep 100
Loop
[JScript]
var Controller = WScript.CreateObject("WSHController");
var RemoteScript = Controller.CreateScript("test.js", "remoteserver");
RemoteScript.Execute();

while (RemoteScript.Status != 2) {
    WScript.Sleep(100);
}

Properties

Status Property | Error Property

Methods

Execute Method | Terminate Method

Events

Start Event | End Event | Error Event

See Also

WshController Object


WshRemote Object Properties, Methods, and Events

Properties

Status Property

Error Property

Methods

Execute Method

Terminate Method

Events

Start Event

End Event

Error Event


WshRemoteError Object

Error PropertyWshRemote Object

Provides access to the error information available when a remote script (a WshRemote object) terminates as a result of a script error.

Remarks

The WshRemoteError object is returned by the Error property of the WshRemote object.

Example

The following example demonstrates how the WshRemoteError object is used to show where the error occurred in the script along with a description of the error.

[VBScript]
Dim Controller, RemoteScript
Set Controller = WScript.CreateObject("WSHController")
Set RemoteScript = Controller.CreateScript("test.js", "remoteserver")
WScript.ConnectObject RemoteScript, "remote_"
RemoteScript.Execute

Do While RemoteScript.Status <> 2
    WScript.Sleep 100
Loop

WScript.DisconnectObject RemoteScript

Sub remote_Error
    Dim theError
    Set theError = RemoteScript.Error
    WScript.Echo "Error " & theError.Number & " - Line: " & theError.Line & ", Char: " & theError.Character & vbCrLf & "Description: " & theError.Description
    WScript.Quit -1
End Sub
[JScript]
var Controller = WScript.CreateObject("WSHController");
var RemoteScript = Controller.CreateScript("test.js", "remoteserver");
WScript.ConnectObject(RemoteScript, "remote_");
RemoteScript.Execute();

while (RemoteScript.Status != 2) {
    WScript.Sleep(100);
}

WScript.DisconnectObject(RemoteScript);

function remote_Error()
{
    var theError = RemoteScript.Error;
    WScript.Echo("Error " + theError.Number + " - Line: " + theError.Line + ", Char: " + theError.Character + "\nDescription: " + theError.Description);
    WScript.Quit(-1);
}

Properties

Description Property | Line Property | Character Property | SourceText Property | Source Property | Number Property

See Also

WshRemote Object


WshRemoteError Object Properties

Properties

Description Property

Line Property

Character Property

SourceText Property

Source Property

Number Property


WshScriptExec Object

Exec MethodWshShell Object

Provides status information about a script run with Exec along with access to the StdIn, StdOut, and StdErr streams.

Remarks

The WshScriptExec object is returned by the Exec method of the WshShell object. The Exec method returns the WshScriptExec object either once the script or program has finished executing, or before the script or program begins executing.

Example

The following code runs calc.exe and echoes the final status to the screen.

[VBScript]
Dim WshShell, oExec
Set WshShell = CreateObject("WScript.Shell")

Set oExec = WshShell.Exec("calc")

Do While oExec.Status = 0
     WScript.Sleep 100
Loop

WScript.Echo oExec.Status
[JScript]
var WshShell = new ActiveXObject("WScript.Shell");
var oExec = WshShell.Exec("calc");

while (oExec.Status == 0)
{
     WScript.Sleep(100);
}

WScript.Echo(oExec.Status);

Properties

Status Property | StdOut Property | StdIn Property | StdErr Property

Methods

Terminate Method

See Also

WScript Object | Exec Method


WshScriptExec Object Properties and Methods

Properties

ExitCode Property

ProcessID Property

Status Property

StdOut Property

StdIn Property

StdErr Property

Methods

Terminate Method


WshShell Object

WScript Object

Provides access to the native Windows shell.

Remarks

You create a WshShell object whenever you want to run a program locally, manipulate the contents of the registry, create a shortcut, or access a system folder. The WshShell object provides the Environment collection. This collection allows you to handle environmental variables (such as WINDIR, PATH, or PROMPT).

Example

The following example demonstrates the creation of a shortcut to the script being run and a URL shortcut to www.microsoft.com:

<package>
   <job id="vbs">
      <script language="VBScript">
         set WshShell = WScript.CreateObject("WScript.Shell")
         strDesktop = WshShell.SpecialFolders("Desktop")
         set oShellLink = WshShell.CreateShortcut(strDesktop & "\Shortcut Script.lnk")
         oShellLink.TargetPath = WScript.ScriptFullName
         oShellLink.WindowStyle = 1
         oShellLink.Hotkey = "CTRL+SHIFT+F"
         oShellLink.IconLocation = "notepad.exe, 0"
         oShellLink.Description = "Shortcut Script"
         oShellLink.WorkingDirectory = strDesktop
         oShellLink.Save
      </script>
   </job>

   <job id="js">
      <script language="JScript">
         var WshShell = WScript.CreateObject("WScript.Shell");
         strDesktop = WshShell.SpecialFolders("Desktop");
         var oShellLink = WshShell.CreateShortcut(strDesktop + "\\Shortcut Script.lnk");
         oShellLink.TargetPath = WScript.ScriptFullName;
         oShellLink.WindowStyle = 1;
         oShellLink.Hotkey = "CTRL+SHIFT+F";
         oShellLink.IconLocation = "notepad.exe, 0";
         oShellLink.Description = "Shortcut Script";
         oShellLink.WorkingDirectory = strDesktop;
         oShellLink.Save();
      </script>
   </job>
</package>

Properties

CurrentDirectory Property | Environment Property | SpecialFolders Property

Methods

AppActivate Method | CreateShortcut Method | ExpandEnvironmentStrings Method | LogEvent Method | Popup Method | RegDelete Method | RegRead Method | RegWrite Method | Run Method | SendKeys Method | Exec Method

See Also

Running Your Scripts


WshShellObject Properties and Methods

Properties

CurrentDirectory Property

Environment Property

SpecialFolders Property

Methods

AppActivate Method

CreateShortcut Method

ExpandEnvironmentStrings Method

LogEvent Method

Popup Method

RegDelete Method

RegRead Method

RegWrite Method

Run Method

SendKeys Method


WshShortcut Object

WshShell Object

Allows you to create a shortcut programmatically.

Example

The following example demonstrates the creation of a shortcut to the script being run:

<package>
   <job id="vbs">
      <script language="VBScript">
         set WshShell = WScript.CreateObject("WScript.Shell")
         strDesktop = WshShell.SpecialFolders("Desktop")
         set oShellLink = WshShell.CreateShortcut(strDesktop & "\Shortcut Script.lnk")
         oShellLink.TargetPath = WScript.ScriptFullName
         oShellLink.WindowStyle = 1
         oShellLink.Hotkey = "CTRL+SHIFT+F"
         oShellLink.IconLocation = "notepad.exe, 0"
         oShellLink.Description = "Shortcut Script"
         oShellLink.WorkingDirectory = strDesktop
         oShellLink.Save
      </script>
   </job>

   <job id="js">
      <script language="JScript">
         var WshShell = WScript.CreateObject("WScript.Shell");
         strDesktop = WshShell.SpecialFolders("Desktop");
         var oShellLink = WshShell.CreateShortcut(strDesktop + "\\Shortcut Script.lnk");
         oShellLink.TargetPath = WScript.ScriptFullName;
         oShellLink.WindowStyle = 1;
         oShellLink.Hotkey = "CTRL+SHIFT+F";
         oShellLink.IconLocation = "notepad.exe, 0";
         oShellLink.Description = "Shortcut Script";
         oShellLink.WorkingDirectory = strDesktop;
         oShellLink.Save();
      </script>
   </job>
</package>

Properties

Arguments Property | Description Property | FullName Property (WshShortcut Object) | Hotkey Property | IconLocation Property | TargetPath Property | WindowStyle Property | WorkingDirectory Property

Methods

Save Method

See Also

Running Your Scripts | CreateShortcut Method


WshShortcut Object Properties and Methods

Properties

Arguments Property

Description Property

FullName Property

Hotkey Property

IconLocation Property

TargetPath Property

WindowStyle Property

WorkingDirectory Property

Methods

Save Method


WshSpecialFolders Object

SpecialFolders PropertyWshShell Object

Provides access to the collection of Windows special folders.

Remarks

The WshShell object's SpecialFolders property returns the WshSpecialFolders object, which is a collection of special folders. This collection contains references to Windows special folders (for example, the Desktop folder, Start Menu folder, and Personal Documents folder). This collection retrieves paths to special folders using the special folder name as the index. A special folder's path depends on the user environment. The information stored in a special folder is unique to the user logged onto the computer system. If several different users have accounts on the same computer system, several different sets of special folders are stored on the hard disk.

The following special folders are available:

  • AllUsersDesktop
  • AllUsersStartMenu
  • AllUsersPrograms
  • AllUsersStartup
  • Desktop
  • Favorites
  • Fonts
  • MyDocuments
  • NetHood
  • PrintHood
  • Programs
  • Recent
  • SendTo
  • StartMenu
  • Startup
  • Templates

Example

The following script demonstrates the use of the WshSpecialFolders Object:

<package>
   <job id="vbs">
      <script language="VBScript">
         set WshShell = WScript.CreateObject("WScript.Shell")
         strDesktop = WshShell.SpecialFolders("Desktop")
         set oShellLink = WshShell.CreateShortcut(strDesktop & "\Shortcut Script.lnk")
         oShellLink.TargetPath = WScript.ScriptFullName
         oShellLink.WindowStyle = 1
         oShellLink.Hotkey = "CTRL+SHIFT+F"
         oShellLink.IconLocation = "notepad.exe, 0"
         oShellLink.Description = "Shortcut Script"
         oShellLink.WorkingDirectory = strDesktop
         oShellLink.Save
      </script>
   </job>

   <job id="js">
      <script language="JScript">
         var WshShell = WScript.CreateObject("WScript.Shell");
         strDesktop = WshShell.SpecialFolders("Desktop");
         var oShellLink = WshShell.CreateShortcut(strDesktop + "\\Shortcut Script.lnk");
         oShellLink.TargetPath = WScript.ScriptFullName;
         oShellLink.WindowStyle = 1;
         oShellLink.Hotkey = "CTRL+SHIFT+F";
         oShellLink.IconLocation = "notepad.exe, 0";
         oShellLink.Description = "Shortcut Script";
         oShellLink.WorkingDirectory = strDesktop;
         oShellLink.Save();
      </script>
   </job>
</package>

Properties

Item Property

Methods

Count Method

See Also

Running Your Scripts | SpecialFolders Property


WshSpecialFolders Object Properties and Methods

Properties

Item Property

Length Property

Methods

Count Method


WshUnnamed Object

Unnamed PropertyWshArguments Object

Provides access to the unnamed arguments from the command line.

Remarks

The WshUnnamed object is a read-only collection that is returned by the Unnamed property of the WshArguments object. Individual argument values are retrieved from this collection using zero-based indexes. Two of the WshArguments object's properties are filtered arguments collections — one contains the named arguments (the WshNamed object), the other contains the unnamed arguments (the WshUnnamed object). In total, this gives you three ways to access sets of command-line arguments.

  • You can access the entire set of arguments (those with and without names) with the WshArguments object.
  • You can access the arguments that have names with the WshNamed object.
  • You can access the arguments that have no names with the WshUnnamed object.

Example

The following code displays the number of named and unnamed command-line arguments.

<package>
<job id="JS">
<script language="JScript">

var argsNamed = WScript.Arguments.Named;
var argsUnnamed = WScript.Arguments.Unnamed;

WScript.Echo("There are " + argsNamed.length + " named arguments.");
WScript.Echo("There are " + argsUnnamed.length + " unnamed arguments.");

</script>
</job>

<job id="VBS">
<script language="VBScript">

Dim argsNamed, argsUnnamed
Set argsNamed = WScript.Arguments.Named
Set argsUnnamed = WScript.Arguments.Unnamed

WScript.Echo "There are " & argsNamed.Count & " named arguments."
WScript.Echo "There are " & argsUnnamed.Count & " unnamed arguments."

</script>
</job>
</package>

Properties

Item Property | Length Property (WshArguments object)

Methods

Count Method

See Also

WshArguments Object | WshNamed Object


WshUnnamed Object Properties and Methods

Properties

Item Property

Length Property

Methods

Count Method


WshUrlShortcut Object

WshShell Object

Allows you to create a shortcut to an Internet resource programmatically.

Remarks

The WshUrlShortcut object is a child object of the WshShell object — you must use the WshShell method CreateShortcut to create a WshUrlShortcut object (e.g., WshShell.CreateShortcut(strDesktop & "\Shortcut Script.lnk")).

Example

The following example demonstrates the creation of a URL shortcut to www.microsoft.com.

<package>
   <job id="vbs">
      <script language="VBScript">
         set WshShell = WScript.CreateObject("WScript.Shell")
         set oUrlLink = WshShell.CreateShortcut(strDesktop & "\Microsoft Web Site.url")
         oUrlLink.TargetPath = "http://www.microsoft.com"
         oUrlLink.Save
      </script>
   </job>

   <job id="js">
      <script language="JScript">
         var WshShell = WScript.CreateObject("WScript.Shell");
         var oUrlLink = WshShell.CreateShortcut(strDesktop + "\\Microsoft Web Site.url");
         oUrlLink.TargetPath = "http://www.microsoft.com";
         oUrlLink.Save();
      </script>
   </job>
</package>

Properties

FullName Property (WshUrlShortcut Object) | TargetPath Property

Methods

Save Method

See Also

Running Your Scripts | CreateShortcut Method


WshUrlShortcut Object Properties and Methods

Properties

FullName Property

TargetPath Property

Methods

Save Method


Properties

In this Section

Arguments Property
Returns the WshArguments object.
AtEndOfLine Property
Returns a Boolean value indicating whether the end of an input line has been reached.
AtEndOfStream Property
Returns a Boolean value indicating whether the end of an input stream has been reached.
Character Property
Reports the specific character in the line of code that contained the error.
Column Property
Returns the column number of the current character position in an input stream.
ComputerName Property
Returns the name of the computer.
CurrentDirectory Property
Allows you to set or retrieve the active script's current working folder.
Description Property
Returns the description of a shortcut.
Environment Property
Returns the WshEnvironment object.
Error Property (WshRemote)
Exposes a WshRemoteError object.
ExitCode Property
Returns the exit code set by a script/program run using the Exec() method.
FullName Property
Returns a fully qualified path name.
Hotkey Property
Allows you to assign a key combination to a shortcut and determine the key combination to a shortcut.
IconLocation Property
Allows you to assign an icon to a shortcut and determine which icon has been assigned to a shortcut.
Interactive Property
Allows you to set the script mode programmatically, as well as determine the script mode programmatically.
Item Property
Exposes a specified item from a collection.
Item Property (WshNamed)
Provides access to the items in the WshNamed object.
Item Property (WshUnnamed)
Returns an item using a zero-based index.
Length Property
Returns the number of items in a collection.
Line Property (WScript)
Returns the current line number in an input stream.
Line Property (WshRemote)
Identifies the line in a script that contains an error-causing statement.
Name Property
Returns the friendly name of the WScript object (the host executable file).
Number Property
Reports the error number representing a script error.
Path PropertyPath
Returns the name of the directory containing the WScript object (the host executable file).
ProcessID Property
Reports the process ID (PID) of a process started with the WshScriptExec object.
ScriptFullName Property
Returns the full path-name of the currently running script.
ScriptName Property
Returns the file name of the currently running script.
Source Property
Identifies the COM object responsible for causing the script error.
SourceText Property
Contains the line of source code that caused an error.
SpecialFolders Property
Returns the WshSpecialFolders object.
Status Property (WshRemote)
Reports the current running-condition of the remote script.
Status Property (WshScriptExec)
Provides status information about a script run with the Exec() method.
StdErr Property (WScript)
Exposes the write-only error output stream for the current script.
StdErr Property (WshScriptExec)
Exposes the read-only stderr output stream of the Exec object.
StdIn Property (WScript)
Exposes the read-only input stream for the current script.
StdIn Property (WshScriptExec)
Exposes the write-only stdin input stream of the Exec object.
StdOut Property (WScript)
Exposes the write-only output stream for the current script.
StdOut Property (WshScriptExec)
Exposes the write-only stdout output stream of the Exec object.
TargetPath Property
Allows you to assign a path to the executable file to which a shortcut points, as well as a determine the path to the executable file pointed to by a shortcut.
UserDomain Property
Returns the user's domain name.
UserName Property
Returns the name of the user.
Version Property
Returns the version of WSH.
WindowStyle Property
Allows you to assign a window style to a shortcut, as well as determine the type of window style used by a shortcut.
WorkingDirectory Property
Allows you to assign a working directory to a shortcut, as well as determine the working directory used by a shortcut.

Related Sections

WSH Language
List of elements that make up WSH Reference.
WSH Basics
Learn the basics of WSH.


Arguments Property (Shortcut Object)

Sets the arguments for a shortcut, or identifies a shortcut's arguments.

object.Arguments

Arguments

object
WshShortcut object.

Remarks

The Arguments property returns a string.

Example

The following code sets the Arguments property.

[VBScript]
set WshShell = WScript.CreateObject("WScript.Shell")
strDesktop = WshShell.SpecialFolders("Desktop")
set oShellLink = WshShell.CreateShortcut(strDesktop & "\Shortcut Script.lnk")
oShellLink.TargetPath = WScript.ScriptFullName
oShellLink.WindowStyle = 1
oShellLink.Hotkey = "Ctrl+Alt+f"
oShellLink.IconLocation = "notepad.exe, 0"
oShellLink.Description = "Shortcut Script"
oShellLink.WorkingDirectory = strDesktop
oShellLink.Arguments = "C:\myFile.txt"
oShellLink.Save
[JScript]
var WshShell = WScript.CreateObject("WScript.Shell");
var strDesktop = WshShell.SpecialFolders("Desktop");
var oShellLink = WshShell.CreateShortcut(strDesktop + "\\Shortcut Script.lnk");
oShellLink.TargetPath = WScript.ScriptFullName;
oShellLink.WindowStyle= 1;
oShellLink.Hotkey= "Ctrl+Alt+f";
oShellLink.IconLocation= "notepad.exe, 0";
oShellLink.Description= "Shortcut Script";
oShellLink.WorkingDirectory= strDesktop;
oShellLink.Arguments = "C:\\myFile.txt"; oShellLink.Save();

See Also

WshShortcut Object | WshShell Object | CreateShortcut Method


Arguments Property (WScript Object)

Returns the WshArguments object (a collection of arguments).

object.Arguments

Arguments

object
WScript object.

Remarks

The Arguments property contains the WshArguments object (a collection of arguments). Use a zero-based index to retrieve individual arguments from this collection.

Example

The following code samples display the entire set of command-line parameters associated with a script.

[VBScript]
Set objArgs = WScript.Arguments
For I = 0 to objArgs.Count - 1
   WScript.Echo objArgs(I)
Next
[JScript]
objArgs = WScript.Arguments;
for (i = 0; i < objArgs.length; i++)
{
   WScript.Echo(objArgs(i));
}

See Also

WScript Object | WshArguments Object | WshNamed Object | WshUnnamed Object


AtEndOfLine Property

Returns a Boolean value indicating whether the end of a line in an input stream has been reached.

object.AtEndOfLine

Arguments

object
StdIn text stream object.

Remarks

The AtEndOfLine property contains a Boolean value indicating whether the end of a line in an input stream has been reached. The AtEndOfLine property returns True if the stream pointer immediately precedes the end-of-line marker in an input stream, False if it does not. The StdIn, StdOut, and StdErr properties and methods work only when the script is run with CScript.exe. If the script is run with WScript.exe, an error occurs.

Example

The following samples will read a line of text from the keyboard and display whatever was typed when the end of the line is seen.

[VBScript]
Dim Input
Input = ""

Do While Not WScript.StdIn.AtEndOfLine
   Input = Input & WScript.StdIn.Read(1)
Loop
WScript.Echo Input
[JScript]
var input = "";
while (!WScript.StdIn.AtEndOfLine)
{
   input += WScript.StdIn.Read(1);
}
WScript.Echo(input);

See Also

StdIn Property | Error Messages


AtEndOfStream Property

Returns a Boolean value indicating whether the end of an input stream has been reached.

object.AtEndOfStream

Arguments

object
StdIn text stream object.

Remarks

The AtEndOfStream property contains a Boolean value indicating whether the end of an input stream has been reached. The AtEndOfStream property returns True if the stream pointer is at the end of an input stream, False if not. The StdIn, StdOut, and StdErr properties and methods work only when the script is run with CScript.exe. If the script is run with WScript.exe, an error occurs.

Example

The following code samples demonstrate the AtEndOfStream property by reading a standard directory listing from "dir", stripping the top and bottom lines that aren't actual entries, and double spacing the directory entries.

[VBScript]
Dim StdIn, StdOut, Str1, Str2

Set StdIn = WScript.StdIn
Set StdOut = WScript.StdOut

Str1 = ""
Str2 = ""For i = 0 to 4
   StdIn.SkipLine
Next

i = 0
Do While Not StdIn.AtEndOfStream
     If i >= 2 Then
          StdOut.WriteLine Str1
     End If
     i = i + 1
     Str1 = Str2
     Str2 = StdIn.ReadLine
Loop
[JScript]
var 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();
}

See Also

StdIn Property | Error Messages


BuildVersion Property

Returns the Windows Script Host build version number.

Object.BuildVersion

Parameters

Object
WScript object.

Remarks

The BuildVersion property returns an integer value.

The full version number of Windows Script Host consists of the product release version number followed by the build version number. For example, if the Windows Script Host product release version number is 5.6, and the build version number is 6626, the full version number is 5.6.6626.

Example

The following code returns the full version number of the Windows Script Host. This consists of the product release version number plus the build version number.

WScript.Echo WScript.Version & "." & WScript.BuildVersion;

See Also

Version Property


Character Property

Reports the specific character in a line of code that contains an error.

Object.Character

Arguments

Object
WshRemoteError object.

Remarks

The Character property returns a signed long integer.

Some errors are not associated with a particular character position. For example, consider the error Expected End If. In this case, there is no line (a line of code is missing). In such a case, the Character property returns zero (0).

The character position is based on an offset of one (1) (the first character in a line resides at position one).

Example

The following JScript code demonstrates how the WshRemoteError object exposes the character in the line of code that contained the error.

[VBScript]
Dim Controller, RemoteScript
Set Controller = WScript.CreateObject("WSHController")
Set RemoteScript = Controller.CreateScript("test.js", "remoteserver")
WScript.ConnectObject RemoteScript, "remote_"
RemoteScript.Execute

Do While RemoteScript.Status <> 2
    WScript.Sleep 100
Loop

Sub remote_Error
    Dim theError
    Set theError = RemoteScript.Error
    WScript.Echo "Error - Line: " & theError.Line & ", Char: " & theError.Character & vbCrLf & "Description: " & theError.Description
    WScript.Quit -1
End Sub
[JScript]
var Controller = WScript.CreateObject("WSHController");
var RemoteScript = Controller.CreateScript("test.js", "remoteserver");
WScript.ConnectObject(RemoteScript, "remote_");
RemoteScript.Execute();

while (RemoteScript.Status != 2) {
    WScript.Sleep(100);
}

function remote_Error()
{
    var theError = RemoteScript.Error;
    WScript.Echo("Error - Line: " + theError.Line + ", Char: " + theError.Character + "\nDescription: " + theError.Description);
    WScript.Quit(-1);
}

See Also

WshRemote Object | WshRemoteError Object | Line Property| Description Property | SourceText Property | Number Property | Source Property


Column Property

Returns the column number of the current character position in an input stream.

object.Column

Arguments

object
StdIn text stream object.

Remarks

The Column property contains a read-only integer value indicating the column number of the current character position in an input stream. The Column property is equal to 1 after a newline character is written (even before any other character is written). The StdIn, StdOut, and StdErr properties and methods work only when the script is run with CScript.exe. If the script is run with WScript.exe, an error occurs.

Example

The following code demonstrates the use of the Column property by reading input from the keyboard and breaking it into lines of 20 characters.

[VBScript]
Dim Input
Input = ""

Do While Not WScript.StdIn.AtEndOfLine
   Input = Input & WScript.StdIn.Read(1)
   If (WScript.StdIn.Column - 1) Mod 20 = 0 Then
      Input = Input & vbCrLf
   End If
Loop
WScript.Echo Input
[JScript]
var input = "";
while (!WScript.StdIn.AtEndOfLine)
{
   input += WScript.StdIn.Read(1);
   if ((WScript.StdIn.Column - 1) % 20 == 0)
   input += "\n";
}
WScript.Echo(input);

See Also

StdIn Property | Error Messages


ComputerName Property

Returns the name of the computer system.

object.ComputerName

Arguments

object
WshNetwork object.

Remarks

The ComputerName property contains a string value indicating the name of the computer system.

Example

The following example demonstrates the use of the ComputerName property.

<package>
   <job id="vbs">
      <script language="VBScript">
         Set WshNetwork = WScript.CreateObject("WScript.Network")
         WScript.Echo "Domain = " & WshNetwork.UserDomain
         WScript.Echo "Computer Name = " & WshNetwork.ComputerName
         WScript.Echo "User Name = " & WshNetwork.UserName
      </script>
   </job>

   <job id="js">
      <script language="JScript">
         var WshNetwork = WScript.CreateObject("WScript.Network");
         WScript.Echo("Domain = " + WshNetwork.UserDomain);
         WScript.Echo("Computer Name = " + WshNetwork.ComputerName);
         WScript.Echo("User Name = " + WshNetwork.UserName);
         }
      </script>
   </job>
</package>

See Also

Running Your Scripts | WshNetwork Object


CurrentDirectory Property

Retrieves or changes the current active directory.

object.CurrentDirectory

Arguments

object
WshShell object.

Remarks

The CurrentDirectory returns a string that contains the fully qualified path of the current working directory of the active process.

Example

The following code displays the current active directory.

[VBScript]
Dim WshShell
Set WshShell = WScript.CreateObject("WScript.Shell")
WScript.Echo WshShell.CurrentDirectory
[JScript]
var WshShell = WScript.CreateObject ("WScript.Shell");
WScript.Echo (WshShell.CurrentDirectory);

See Also

WshShell Object


Description Property

Returns a shortcut's description.

object.Description

Arguments

object
WshShortcut object.

Remarks

The Description property contains a string value describing a shortcut.

Example

The following example demonstrates the use of the Description Property.

<package>
   <job id="vbs">
      <script language="VBScript">
         set WshShell = WScript.CreateObject("WScript.Shell")
         strDesktop = WshShell.SpecialFolders("Desktop")
         set oShellLink = WshShell.CreateShortcut(strDesktop & "\Shortcut Script.lnk")
         oShellLink.TargetPath = WScript.ScriptFullName
         oShellLink.WindowStyle = 1
         oShellLink.Hotkey = "Ctrl+Alt+e"
         oShellLink.IconLocation = "notepad.exe, 0"
         oShellLink.Description = "Shortcut Script"
         oShellLink.WorkingDirectory = strDesktop
         oShellLink.Save
         set oUrlLink = WshShell.CreateShortcut(strDesktop & "\Microsoft Web Site.url")
         oUrlLink.TargetPath = "http://www.microsoft.com"
         oUrlLink.Save
      </script>
   </job>

   <job id="js">
      <script language="JScript">
         var WshShell = WScript.CreateObject("WScript.Shell");
         strDesktop = WshShell.SpecialFolders("Desktop");
         var oShellLink = WshShell.CreateShortcut(strDesktop + "\\Shortcut Script.lnk");
         oShellLink.TargetPath = WScript.ScriptFullName;
         oShellLink.WindowStyle = 1;
         oShellLink.Hotkey = "Ctrl+Alt+e";
         oShellLink.IconLocation = "notepad.exe, 0";
         oShellLink.Description = "Shortcut Script";
         oShellLink.WorkingDirectory = strDesktop;
         oShellLink.Save();
         var oUrlLink = WshShell.CreateShortcut(strDesktop + "\\Microsoft Web Site.url");
         oUrlLink.TargetPath = "http://www.microsoft.com";
         oUrlLink.Save();
      </script>
   </job>
</package>

See Also

Running Your Scripts | WshShortcut Object


Description Property (WshRemoteError)

Contains a brief description of the error that caused the remote script to terminate.

Object.Description

Arguments

Object
WshRemoteError object.

Remarks

The Description property returns a string.

If an error description is not available, the Description property returns an empty string.

Example

The following JScript code demonstrates how the WshRemoteError object exposes the description of the error.

[VBScript]
Dim Controller, RemoteScript
Set Controller = WScript.CreateObject("WSHController")
Set RemoteScript = Controller.CreateScript("test.js", "remoteserver")
WScript.ConnectObject RemoteScript, "remote_"
RemoteScript.Execute

Do While RemoteScript.Status <> 2
    WScript.Sleep 100
Loop

Sub remote_Error
    Dim theError
    Set theError = RemoteScript.Error
    WScript.Echo "Error - Line: " & theError.Line & ", Char: " & theError.Character & vbCrLf & "Description: " & theError.Description
    WScript.Quit -1
End Sub
[JScript]
var Controller = WScript.CreateObject("WSHController");
var RemoteScript = Controller.CreateScript("test.js", "remoteserver");
WScript.ConnectObject(RemoteScript, "remote_");
RemoteScript.Execute();

while (RemoteScript.Status != 2) {
    WScript.Sleep(100);
}

function remote_Error()
{
    var theError = RemoteScript.Error;
    WScript.Echo("Error - Line: " + theError.Line + ", Char: " + theError.Character + "\nDescription: " + theError.Description);
    WScript.Quit(-1);
}

See Also

WshRemote Object | WshRemoteError Object | Line Property | Character Property | SourceText Property | Number Property | Source Property


Environment Property

Returns the WshEnvironment object (a collection of environment variables).

object.Environment ([strType])

Arguments

object
WshShell object.
strType
Optional. Specifies the location of the environment variable.

Remarks

The Environment property contains the WshEnvironment object (a collection of environment variables). If strType is supplied, it specifies where the environment variable resides with possible values of System, User, Volatile, or Process. If strType is not supplied, the Environment property returns different environment variable types depending on the operating system.

Type of Environment Variable | Operating System
System | Microsoft Windows NT/2000
Process | Windows 95/98/Me
Note For Windows 95/98/Me, only one strType is permitted — Process.

The following table lists some of the variables that are provided with the Windows operating system. Scripts can access environment variables that have been set by other applications.

Note None of the following variables 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

Example

The following code retrieves the system environment variable NUMBER_OF_PROCESSORS.

[VBScript]
Set WshShell = WScript.CreateObject("WScript.Shell")
Set WshSysEnv = WshShell.Environment("SYSTEM")
WScript.Echo WshSysEnv("NUMBER_OF_PROCESSORS")
[JScript]
var WshShell = WScript.CreateObject("WScript.Shell");
var WshSysEnv = WshShell.Environment("SYSTEM");
WScript.Echo(WshSysEnv("NUMBER_OF_PROCESSORS"));

See Also

WshEnvironment Object | WshShell Object


Error Property (WshRemote)

Exposes the WshRemoteError object, which holds information about the error that caused the remote script to terminate prematurely.

Object.Error

Arguments

Object
WshRemote object.

Remarks

The Error property returns a WshRemoteError object.

Example

The following code demonstrates how the Error property of the WshRemote object exposes a WshRemoteError object, which exposes the line, character, and description of the error.

[VBScript]
Dim Controller, RemoteScript
Set Controller = WScript.CreateObject("WSHController")
Set RemoteScript = Controller.CreateScript("test.js", "remoteserver")
WScript.ConnectObject RemoteScript, "remote_"
RemoteScript.Execute

Do While RemoteScript.Status <> 2
    WScript.Sleep 100
Loop

Sub remote_Error
    Dim theError
    Set theError = RemoteScript.Error
    WScript.Echo "Error - Line: " & theError.Line & ", Char: " & theError.Character & vbCrLf & "Description: " & theError.Description
    WScript.Quit -1
End Sub
[JScript]
var Controller = WScript.CreateObject("WSHController");
var RemoteScript = Controller.CreateScript("test.js", "remoteserver");
WScript.ConnectObject(RemoteScript, "remote_");
RemoteScript.Execute();

while (RemoteScript.Status != 2) {
    WScript.Sleep(100);
}

function remote_Error()
{
    var theError = RemoteScript.Error;
    WScript.Echo("Error - Line: " + theError.Line + ", Char: " + theError.Character + "\nDescription: " + theError.Description);    WScript.Quit(-1);
}

See Also

WshController Object | WshRemote Object | WshRemoteError Object | Status Property | Execute Method | Terminate Method | Start Event | End Event | Error Event


ExitCode Property

Returns the exit code set by a script or program run using the Exec() method.

Object.ExitCode

Parameters

Object
WshScriptExec Object

Remarks

Executables set an exit code when they finish running. This conveys the status information when a process ends. Often, it is used to send an error code (or some other piece of information) back to the caller. If the process has not finished, the ExitCode property returns 0. The values returned from ExitCode depend on the application that was called.

Example

The following code shows an example of the ExitCode property.

[VBScript]
Dim WshShell, oExec
Set WshShell = CreateObject("WScript.Shell")
Set oExec    = WshShell.Exec("%comspec% /c dire")

Function ReadAllFromAny(oExec)

     If Not oExec.StdOut.AtEndOfStream Then
          ReadAllFromAny = oExec.StdOut.ReadAll
          Exit Function
     End If

     If Not oExec.StdErr.AtEndOfStream Then
          ReadAllFromAny = oExec.StdErr.ReadAll
          Exit Function
     End If

     ReadAllFromAny = -1
End Function

Dim allInput, tryCount

allInput = ""
tryCount = 0

Do While True

     Dim input
     input = ReadAllFromAny(oExec)

     If -1 = input Then
          If tryCount > 10 And oExec.Status = 1 Then
               Exit Do
          End If
          tryCount = tryCount + 1
          WScript.Sleep 100
     Else
          allInput = allInput & input
          tryCount = 0
     End If
Loop

If oExec.ExitCode <> 0 Then
     WScript.Echo "Warning: Non-zero exit code"
End If

WScript.Echo allInput
[JScript]
var WshShell = new ActiveXObject("WScript.Shell");
var oExec    = WshShell.Exec("%comspec% /c dire");

function ReadAllFromAny(oExec)
{
     if (!oExec.StdOut.AtEndOfStream)
          return oExec.StdOut.ReadAll();

     if (!oExec.StdErr.AtEndOfStream)
          return oExec.StdErr.ReadAll();

     return -1;
}

var allInput = "";
var tryCount = 0;

while (true)
{
     var input = ReadAllFromAny(oExec);
     if (-1 == input)
     {
          if (tryCount++ > 10 && oExec.Status == 1)
               break;
          WScript.Sleep(100);
     }
     else
     {
          allInput += input;
          tryCount = 0;
     }
}

if (oExec.ExitCode != 0)
{
     WScript.Echo("Warning: Non-zero exit code");
}

WScript.Echo(allInput);

See Also

Exec Method | WshScriptExec Object


FullName Property (WScript Object)

Returns the fully qualified path of the host executable (CScript.exe or WScript.exe).

object.FullName

Arguments

object
WScript object.

Remarks

The FullName property is a read-only string representing the fully qualified path of the host executable.

Example

The following JScript code uses the FullName property:

WScript.Echo (WScript.FullName);

produces the following output.

C:\WINNT\System32\cscript.exe

See Also

Path Property | WScript Object | WshShortcut Object | WshUrlShortcut Object


FullName Property (WshShortcut Object)

Returns the fully qualified path of the shortcut object's target.

object.FullName

Arguments

object
WshShortcut object.

Remarks

The FullName property contains a read-only string value indicating the fully qualified path to the shortcut's target.

Example

The following code retrieves the fully qualified path of a shortcut.

[VBScript]
set WshShell = WScript.CreateObject("WScript.Shell")
strDesktop = WshShell.SpecialFolders("Desktop")
set oShellLink = WshShell.CreateShortcut(strDesktop & "\Shortcut Script.lnk")
oShellLink.TargetPath = WScript.ScriptFullName
oShellLink.WindowStyle = 1
oShellLink.Hotkey = "CTRL+SHIFT+F"
oShellLink.IconLocation = "notepad.exe, 0"
oShellLink.Description = "Shortcut Script"
oShellLink.WorkingDirectory = strDesktop
oShellLink.Save
WScript.Echo oShellLink.FullName
[JScript]
var WshShell = new ActiveXObject("WScript.Shell");
strDesktop = WshShell.SpecialFolders("Desktop");
var oShellLink = WshShell.CreateShortcut(strDesktop + "\\Shortcut Script.lnk");
oShellLink.TargetPath = WScript.ScriptFullName;
oShellLink.WindowStyle = 1;
oShellLink.Hotkey = "CTRL+SHIFT+F";
oShellLink.IconLocation = "notepad.exe, 0";
oShellLink.Description = "Shortcut Script";
oShellLink.WorkingDirectory = strDesktop;
oShellLink.Save();
WScript.Echo(oShellLink.FullName);

See Also

Path Property | WScript Object | WshShortcut Object | WshUrlShortcut Object


FullName Property (WshUrlShortcut Object)

Returns the fully qualified path of the shortcut object's target.

object.FullName

Arguments

object
WshUrlShortcut object.

Remarks

String. Read-only.

The FullName property is a read-only string representing the fully qualified path to the shortcut's target.

Example

The following code retrieves the fully qualified path of a URL shortcut.

[VBScript]
set oUrlLink = WshShell.CreateShortcut(strDesktop & "\Microsoft Web Site.url")
oUrlLink.TargetPath = "http://www.microsoft.com"
oUrlLink.Save
WScript.Echo oUrlLink.FullName
[JScript]
var oUrlLink = WshShell.CreateShortcut(strDesktop + "\\Microsoft Web Site.url");
oUrlLink.TargetPath = "http://www.microsoft.com";
oUrlLink.Save();
WScript.Echo (oUrlLink.FullName);

See Also

Path Property | WScript Object | WshShortcut Object | WshUrlShortcut Object


Hotkey Property

Assigns a key-combination to a shortcut, or identifies the key-combination assigned to a shortcut.

object.Hotkey = strHotkey

Arguments

object
WshShortcut object.
strHotkey
A string representing the key-combination to assign to the shortcut.

Syntax

The syntax of strHotkey is:

[KeyModifier]KeyName
KeyModifier
Can be any one of the following: ALT+, CTRL+, SHIFT+, EXT+.

Note EXT+ means "Extended key." — it appears here in case a new type of SHIFT-key is added to the character set in the future.

KeyName
a ... z, 0 ... 9, F1 … F12, ...

The KeyName is not case-sensitive.

Remarks

A hotkey is a combination of keys that starts a shortcut when all associated keys are held down at the same time.

  • Hotkeys can be used to start shortcuts located on your system's desktop and in the Windows Start menu.
    Note Another name for a hotkey is a Keyboard Shortcut.

In Windows 2000, valid Hotkeys always begin with CTRL + ALT.

Example

The following example demonstrates the use of the HotKey property.

<package>
   <job id="vbs">
      <script language="VBScript">
         set WshShell = WScript.CreateObject("WScript.Shell")
         strDesktop = WshShell.SpecialFolders("Desktop")
         set oShellLink = WshShell.CreateShortcut(strDesktop & "\Shortcut Script.lnk")
         oShellLink.TargetPath = WScript.ScriptFullName
         oShellLink.WindowStyle = 1
         oShellLink.Hotkey = "Ctrl+Alt+e"
         oShellLink.IconLocation = "notepad.exe, 0"
         oShellLink.Description = "Shortcut Script"
         oShellLink.WorkingDirectory = strDesktop
         oShellLink.Save
      </script>
   </job>

   <job id="js">
      <script language="JScript">
         var WshShell = WScript.CreateObject("WScript.Shell");
         strDesktop = WshShell.SpecialFolders("Desktop");
         var oShellLink = WshShell.CreateShortcut(strDesktop + "\\Shortcut Script.lnk");
         oShellLink.TargetPath = WScript.ScriptFullName;
         oShellLink.WindowStyle = 1;
         oShellLink.Hotkey = "Ctrl+Alt+e";
         oShellLink.IconLocation = "notepad.exe, 0";
         oShellLink.Description = "Shortcut Script";
         oShellLink.WorkingDirectory = strDesktop;
         oShellLink.Save();
      </script>
   </job>
</package>

See Also

Running Your Scripts | Running Your Scripts | WshSpecialFolders Object | WshShortcut Object


IconLocation Property

Assigns an icon to a shortcut, or identifies the icon assigned to a shortcut.

object.IconLocation = strIconLocation

Arguments

object
WshShortcut object.
strIconLocation
A string that locates the icon. The string should contain a fully qualified path and an index associated with the icon. See example for more details.

Remarks

String.

Example

The following example demonstrates the use of the IconLocation property.

<package>
   <job id="vbs">
      <script language="VBScript">
         set WshShell = WScript.CreateObject("WScript.Shell")
         strDesktop = WshShell.SpecialFolders("Desktop")
         set oShellLink = WshShell.CreateShortcut(strDesktop & "\Shortcut Script.lnk")
         oShellLink.TargetPath = WScript.ScriptFullName
         oShellLink.WindowStyle = 1
         oShellLink.Hotkey = "Ctrl+Alt+e"
         oShellLink.IconLocation = "notepad.exe, 0"  'Zero is the index
         oShellLink.Description = "Shortcut Script"
         oShellLink.WorkingDirectory = strDesktop
         oShellLink.Save
      </script>
   </job>

   <job id="js">
      <script language="JScript">
         var WshShell = WScript.CreateObject("WScript.Shell");
         strDesktop = WshShell.SpecialFolders("Desktop");
         var oShellLink = WshShell.CreateShortcut(strDesktop + "\\Shortcut Script.lnk");
         oShellLink.TargetPath = WScript.ScriptFullName;
         oShellLink.WindowStyle = 1;
         oShellLink.Hotkey = "Ctrl+Alt+e";
         oShellLink.IconLocation = "notepad.exe, 0";  //Zero is the index
         oShellLink.Description = "Shortcut Script";
         oShellLink.WorkingDirectory = strDesktop;
         oShellLink.Save();
      </script>
   </job>
</package>

See Also

Running Your Scripts | WshShortcut Object


Interactive Property

Sets the script mode, or identifies the script mode.

object.Interactive

Arguments

object
WScript object.

Remarks

The Interactive Property returns a Boolean value.

There are two modes, batch and interactive. In interactive mode (the default), the script provides user interaction. Input to and output from the Windows Script Host is enabled. The script can echo information to dialog boxes and can wait for the user to provide feedback. In batch mode, this type of user interaction is not supported — all input and output to WSH is disabled. You can also set the script mode using the Windows Script Host command line switches //I (for Interactive), and //B (for Batch).

Example

The following JScript code displays the script mode.

WScript.Echo WScript.Interactive;

The following JScript code sets the script mode to batch.

WScript.Interactive = false;

See Also

WScript Object


Item Property

Exposes a specified item from a collection.

Object.Item(natIndex)

Arguments

Object
The result of the EnumNetworkDrive or EnumPrinterConnections methods, or the object returned by the Environment or SpecialFolders properties.
natIndex
Item to retrieve.

Remarks

Item is the default property for each collection. For EnumNetworkDrive and EnumPrinterConnections collections, index is an integer; for the Environment and SpecialFolders collections, index is a string.

WshShell.SpecialFolders.Item (strFolderName) returns "Empty" in VBScript and "undefined" in JScript if the requested folder (strFolderName) is not available.

The following table lists special folders along with the version of Windows that supports them.

Folder | 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

Example

The following code displays network mapping information for the drives and printers.

<package>
   <job id="vbs">
      <script language="VBScript">
         Set WshNetwork = WScript.CreateObject("WScript.Network")
         Set oDrives = WshNetwork.EnumNetworkDrives
         Set oPrinters = WshNetwork.EnumPrinterConnections
         WScript.Echo "Network drive mappings:"
         For i = 0 to oDrives.Count - 1 Step 2
            WScript.Echo "Drive " & oDrives.Item(i) & " = " & oDrives.Item(i+1)
         Next
         WScript.Echo
         WScript.Echo "Network printer mappings:"
         For i = 0 to oPrinters.Count - 1 Step 2
            WScript.Echo "Port " & oPrinters.Item(i) & " = " & oPrinters.Item(i+1)
         Next
      </script>
   </job>

   <job id="js">
      <script language="JScript">
         var WshNetwork = WScript.CreateObject("WScript.Network");
         var oDrives = WshNetwork.EnumNetworkDrives();
         var oPrinters = WshNetwork.EnumPrinterConnections();
         WScript.Echo();
         WScript.Echo("Network drive mappings:");
         for(i = 0; i < oDrives.length; i += 2){
            WScript.Echo("Drive " + oDrives.Item(i) + " = " + oDrives.Item(i + 1));
         }
         WScript.Echo();
         WScript.Echo("Network printer mappings:");
         for(i = 0; i < oPrinters.length; i += 2){
            WScript.Echo("Port " + oPrinters.Item(i) + " = " + oPrinters.Item(i + 1));
         }
      </script>
   </job>
</package>

See Also

EnumNetworkDrive Method | EnumPrinterConnections Method | Environment Property | SpecialFolders Property


Item Property (WshNamed)

Provides access to the items in the WshNamed object.

Object.Item(key)

Parameters

Object
WshNamed object
key
The name of the item you want to retrieve.

Remarks

The Item property returns a string. For collections, it returns an item based on the specified key. When entering the arguments at the command line, you can use blanks in string arguments if you enclose the string in quotes. Consider the following example:
myscript.vbs /stringarg:"This string has spaces"

The quotes will be removed in the WshNamed collection. For an argument to be in the WshNamed collection, it must have been used on the command line. If the argument has no value (such as a simple argument or an empty string), the Item property returns an empty string. Requesting a non-existent named argument from the Item property causes an error. To check if an argument exists, use the Exists method.

Example 1

In the following example, two named arguments are supplied to run a script. Inside the script, code causes the named arguments to be output. The Item property is used to index into the named arguments collection.

The following line is typed at the command prompt to run the script.

myScript.vbs /c:arg1 /d:arg2

If the following code is executed inside the script:

WScript.Echo WScript.Arguments.Named.Item("c")
WScript.Echo WScript.Arguments.Named.Item("d")

then the following output is produced:

arg1
arg2

See Also

WshNamed Object | WshUnnamed Object | Count Method | Item Property | Exists Method


Item Property (WshUnnamed)

Returns an item using a zero-based index.

Object.Item(key)

Parameters

Object
WshUnnamed object.
key
Associated with either a collection or a WshUnnamed object.

Remarks

The Item property returns a string. For collections, it returns an item based on the specified key.

For the unnamed object, items are not named, so you cannot pass the name of the WshUnnamed argument.

The WshUnnamed argument items are stored in the order that they were included on the command line.

When entering the WshUnnamed argument at the command line, you can use blanks in string arguments if you enclose them in quotes.

The quotes are removed in the WshUnnamed collection.

Example

The following example demonstrates how the Item property can be used to return items in the WshUnnamed collection. In this example, two unnamed arguments are supplied to run a script. Inside the script, code causes the unnamed arguments to be output. The Item property is used to index into the unnamed arguments collection.

The following line is typed at the command prompt to run the script.

myScript.vbs arg1 arg2

When the following code is executed inside the script:

WScript.Echo WScript.Arguments.Unnamed.Item(0)
WScript.Echo WScript.Arguments.Unnamed.Item(1)

the following output is produced:

arg1
arg2

See Also

Arguments Property | WshUnnamed Object | WshUnnamed Object | Count Method | Item Property (WshNamed) | Exists Method


length Property (WshArguments object)

Returns the number of command-line parameters belonging to a script (the number of items in an argument's collection).

object.length

Arguments

object
WshArguments object.

Remarks

The length property is a read-only integer that you use in scripts when you write in JScript. It is similar to VBScript's Count method.

See Also

WshArguments Object | Arguments Property | Count Method


length Property (WshEnvironment object)

Returns the number of Windows environment variables on the local computer system (the number of items in an Environment collection).

object.length

Arguments

object
WshEnvironment object.

Remarks

The length property is a read-only integer that you use in scripts when you write in JScript. It is similar to VBScript's Count method.

See Also

WshEnvironment Object | Count Method


length Property (WshSpecialFolders object)

Returns the number of Windows special folders on the local computer system (the number of items in a SpecialFolders collection).

object.length

Arguments

object
WshSpecialFolders object.

Remarks

The length property is a read-only integer that you use in scripts when you write in JScript. It is similar to VBScript's Count method.

See Also

WshSpecialFolders Object | Count Method


Line Property (WScript)

Returns the current line number in an input stream.

object.strStream.Line

Arguments

object
WScript object.
strStream
StdIn property.

Remarks

The Line property is a read-only integer.

After a stream is first opened, Line will initially be 1.

The StdIn, StdOut, and StdErr properties and methods work only when the script is run with CScript.exe. If the script is run with WScript.exe, an error occurs.

Example

The following code demonstrates the use of the Line property.

[VBScript]
Dim StdIn, StdOut
Set StdIn = WScript.StdIn
Set StdOut = WScript.StdOut

Do While Not StdIn.AtEndOfStream
     str = StdIn.ReadLine
     StdOut.WriteLine "Line " & (StdIn.Line - 1) & ": " & str
Loop
[JScript]
var stdin = WScript.StdIn;
var stdout = WScript.StdOut;

while (!stdin.AtEndOfStream)
{
     var str = stdin.ReadLine();
     stdout.WriteLine("Line " + (stdin.Line - 1) + ": " + str);
}

See Also

Error Messages | StdIn Property


Line Property (WshRemoteError)

Identifies the line in a script that contains an error.

Object.Line

Arguments

Object
WshRemoteError object.

Remarks

The Line property returns an unsigned long integer.

Notice that some errors do not occur on a particular line. For example, consider the error Expected End If. In this case, there is no line (a line of code is missing). In such a case, the Line property returns zero (0).

Example

The following JScript code demonstrates how the WshRemoteError object exposes the line in which the error occurred.

[VBScript]
Dim Controller, RemoteScript
Set Controller = WScript.CreateObject("WSHController")
Set RemoteScript = Controller.CreateScript("test.js", "remoteserver")
WScript.ConnectObject RemoteScript, "remote_"
RemoteScript.Execute

Do While RemoteScript.Status <> 2
    WScript.Sleep 100
Loop

Sub remote_Error
    Dim theError
    Set theError = RemoteScript.Error
    WScript.Echo "Error - Line: " & theError.Line & ", Char: " & theError.Character & vbCrLf & "Description: " & theError.Description
    WScript.Quit -1
End Sub
[JScript]
var Controller = WScript.CreateObject("WSHController");
var RemoteScript = Controller.CreateScript("test.js", "remoteserver");
WScript.ConnectObject(RemoteScript, "remote_");
RemoteScript.Execute();

while (RemoteScript.Status != 2) {
    WScript.Sleep(100);
}

function remote_Error()
{
    var theError = RemoteScript.Error;
    WScript.Echo("Error - Line: " + theError.Line + ", Char: " + theError.Character + "\nDescription: " + theError.Description);
    WScript.Quit(-1);
}

See Also

WshRemote Object | WshRemoteError Object | Character Property | Description Property | Line Property | SourceText Property | Number Property | Source Property


Name Property (WScript Object)

Returns the name of the WScript object (the host executable file).

object.Name

Arguments

object
WScript object.

Remarks

The Name property is a read-only string.

Example

The following JScript code shows how to use the Name property.

WScript.Echo (WScript.Name);

See Also

WScript Object


Named Property

Returns the WshNamed object (a collection of named arguments).

Object.Named

Parameters

Object
WshArguments object.

Remarks

The Named property returns the WshNamed collection, the collection of named arguments. Use the name of the argument to find out if the argument was included and to access its value.

Example

The following code displays the number of named and unnamed command-line arguments.

<package>
<job id="JS">
<script language="JScript">

var argsNamed = WScript.Arguments.Named;
var argsUnnamed = WScript.Arguments.Unnamed;

WScript.Echo("There are " + argsNamed.length + " named arguments.");
WScript.Echo("There are " + argsUnnamed.length + " unnamed arguments.");

</script>
</job>

<job id="VBS">
<script language="VBScript">

Dim argsNamed, argsUnnamed
Set argsNamed = WScript.Arguments.Named
Set argsUnnamed = WScript.Arguments.Unnamed

WScript.Echo "There are " & argsNamed.Count & " named arguments."
WScript.Echo "There are " & argsUnnamed.Count & " unnamed arguments."

</script>
</job>
</package>

See Also

WshArguments Object | WshNamed Object | Unnamed Property


Number Property

Reports the error number representing a script error.

Object.Number

Arguments

Object
WshRemoteError object.

Remarks

That Number property returns an unsigned long integer.

Example

The following JScript code demonstrates how the WshRemoteError object exposes the error number.

[VBScript]
Dim Controller, RemoteScript
Set Controller = WScript.CreateObject("WSHController")
Set RemoteScript = Controller.CreateScript("test.js", "remoteserver")
WScript.ConnectObject RemoteScript, "remote_"
RemoteScript.Execute

Do While RemoteScript.Status <> 2
    WScript.Sleep 100
Loop

Sub remote_Error
    Dim theError
    Set theError = RemoteScript.Error
    WScript.Echo "Error " & theError.Number & " - Line: " & theError.Line & ", Char: " & theError.Character & vbCrLf & "Description: " & theError.Description
    WScript.Quit -1
End Sub
[JScript]
var Controller = WScript.CreateObject("WSHController");
var RemoteScript = Controller.CreateScript("test.js", "remoteserver");
WScript.ConnectObject(RemoteScript, "remote_");
RemoteScript.Execute();

while (RemoteScript.Status != 2) {
    WScript.Sleep(100);
}

function remote_Error()
{
    var theError = RemoteScript.Error;
    WScript.Echo("Error " + theError.Number + " - Line: " + theError.Line + ", Char: " + theError.Character + "\nDescription: " + theError.Description);
    WScript.Quit(-1);
}

See Also

WshRemote Object | WshRemoteError Object | Description Property | Line Property | Character Property| SourceText Property| Source Property


Path Property

Returns the name of the directory containing the host executable (CScript.exe or WScript.exe).

object.Path

Arguments

object
WScript object.

Remarks

The Path property is a read-only string.

Example

The following VBScript code echoes the directory where the executable file resides.

WScript.Echo (WScript.Path);

See Also

FullName Property | WScript Object


ProcessID Property

The process ID (PID) for a process started with the WshScriptExec object.

Object.ProcessID

Parameters

Object
WshScriptExec object.

Remarks

You can use the ProcessID property to activate an application (as an argument to the AppActivate method).

Example

The following code uses the ProcessID property to activate the calculator and notepad applications.

[VBScript]
Sub delayedSendKeys(str)
     WScript.Sleep 100
     WshShell.SendKeys str
End Sub

Dim WshShell, oCalc, oNotepad
Set WshShell = CreateObject("WScript.Shell")
Set oCalc = WshShell.Exec("calc")
Set oNotepad = WshShell.Exec("notepad")
WScript.Sleep 500

WshShell.AppActivate oCalc.ProcessID
delayedSendKeys "1{+}1~"
delayedSendKeys "^C"
delayedSendKeys "%{F4}"

WshShell.AppActivate oNotepad.ProcessID
delayedSendKeys "1 {+} 1 = ^V"
[JScript]
function delayedSendKeys(str)
{
     WScript.Sleep(100);
     WshShell.SendKeys(str);
}

var WshShell = new ActiveXObject("WScript.Shell");
var oCalc = WshShell.Exec("calc");
var oNotepad = WshShell.Exec("notepad");
WScript.Sleep(500);

WshShell.AppActivate(oCalc.ProcessID);
delayedSendKeys("1{+}1~");
delayedSendKeys("^C");
delayedSendKeys("%{F4}");

WshShell.AppActivate(oNotepad.ProcessID);
delayedSendKeys("1 {+} 1 = ^V");

See Also

WshScriptExec Object | AppActivate Method


RelativePath Property

Assigns a relative path to a shortcut, or identifies the relative path of a shortcut.

object.RelativePath

Arguments

object
WshShortcut object.

Remarks

String.

Example

The following code sets the relative path of a shortcut.

[VBScript]
Dim WshShell, WshShortcut
Set WshShell = WScript.CreateObject ("WScript.Shell")
Set WshShortcut = WshShell.CreateShortcut("MyScript.lnk")
WshShortcut.RelativePath = "C:\Scripts\"
[JScript]
var WshShell = WScript.CreateObject ("WScript.Shell");
var WshShortcut = WshShell.CreateShortcut("MyScript.lnk");
WshShortcut.RelativePath = "C:\\Scripts\\";

See Also

WshShortcut Object


ScriptFullName Property

Returns the full path of the currently running script.

object.ScriptFullName

Arguments

object
WScript object.

Remarks

The ScriptFullName property is a read-only string.

Example

The following example demonstrates the use of the ScriptFullName property.

<package>
   <job id="vbs">
      <script language="VBScript">
         set WshShell = WScript.CreateObject("WScript.Shell")
         strDesktop = WshShell.SpecialFolders("Desktop")
         set oShellLink = WshShell.CreateShortcut(strDesktop & "\Shortcut Script.lnk")
         oShellLink.TargetPath = WScript.ScriptFullName
         oShellLink.WindowStyle = 1
         oShellLink.Hotkey = "Ctrl+Alt+e"
         oShellLink.IconLocation = "notepad.exe, 0"
         oShellLink.Description = "Shortcut Script"
         oShellLink.WorkingDirectory = strDesktop
         oShellLink.Save
         set oUrlLink = WshShell.CreateShortcut(strDesktop & "\Microsoft Web Site.url")
         oUrlLink.TargetPath = "http://www.microsoft.com"
         oUrlLink.Save
      </script>
   </job>

   <job id="js">
      <script language="JScript">
         var WshShell = WScript.CreateObject("WScript.Shell");
         strDesktop = WshShell.SpecialFolders("Desktop");
         var oShellLink = WshShell.CreateShortcut(strDesktop + "\\Shortcut Script.lnk");
         oShellLink.TargetPath = WScript.ScriptFullName;
         oShellLink.WindowStyle = 1;
         oShellLink.Hotkey = "Ctrl+Alt+e";
         oShellLink.IconLocation = "notepad.exe, 0";
         oShellLink.Description = "Shortcut Script";
         oShellLink.WorkingDirectory = strDesktop;
         oShellLink.Save();
         var oUrlLink = WshShell.CreateShortcut(strDesktop + "\\Microsoft Web Site.url");
         oUrlLink.TargetPath = "http://www.microsoft.com";
         oUrlLink.Save();
      </script>
   </job>
</package>

See Also

Running Your Scripts | ScriptName Property | WScript Object


ScriptName Property

Returns the file name of the currently running script.

object.ScriptName

Arguments

object
WScript object.

Remarks

The ScriptName property is a read-only string.

Example

The following VBScript code echoes the name of the script being run.

WScript.Echo WScript.ScriptName

See Also

ScriptFullName Property | WScript Object


Source Property

Identifies the COM object responsible for causing the script error.

Object.Source

Arguments

Object
WshRemoteError object.

Remarks

The Source property returns a string.

Example

The following JScript code demonstrates how the WshRemoteError object exposes the COM object responsible for causing the script error.

[VBScript]
Dim Controller, RemoteScript
Set Controller = WScript.CreateObject("WSHController")
Set RemoteScript = Controller.CreateScript("test.js", "remoteserver")
WScript.ConnectObject RemoteScript, "remote_"
RemoteScript.Execute

Do While RemoteScript.Status <> 2
    WScript.Sleep 100
Loop

Sub remote_Error
    Dim theError
    Set theError = RemoteScript.Error
    WScript.Echo "Error - Line: " & theError.Line & ", Char: " & theError.Character & vbCrLf & "Description: " & theError.Description & vbCrLf & "Source: " & theError.Source
    WScript.Quit -1
End Sub
[JScript]
var Controller = WScript.CreateObject("WSHController");
var RemoteScript = Controller.CreateScript("test.js", "remoteserver");
WScript.ConnectObject(RemoteScript, "remote_");
RemoteScript.Execute();

while (RemoteScript.Status != 2) {
    WScript.Sleep(100);
}

function remote_Error()
{
    var theError = RemoteScript.Error;
    WScript.Echo("Error - Line: " + theError.Line + ", Char: " + theError.Character + "\nDescription: " + theError.Description + "\nSource: " + theError.Source);
    WScript.Quit(-1);
}

See Also

WshRemote Object | WshRemoteError Object | Description Property | Line Property | Character Property| SourceText Property | Number Property


SourceText Property

Contains the line of source code that caused an error.

Object.SourceText

Arguments

Object
WshRemoteError object.

Remarks

The SourceText property returns a string.

It is not always possible to obtain the source text. If that is the case, the SourceText property returns an empty string.

Example

The following JScript code demonstrates how the WshRemoteError object exposes the line of source code that caused an error.

[VBScript]
Dim Controller, RemoteScript
Set Controller = WScript.CreateObject("WSHController")
Set RemoteScript = Controller.CreateScript("test.js", "remoteserver")
WScript.ConnectObject RemoteScript, "remote_"
RemoteScript.Execute

Do While RemoteScript.Status <> 2
    WScript.Sleep 100
Loop

Sub remote_Error
    Dim theError
    Set theError = RemoteScript.Error
    WScript.Echo "Error - Line: " & theError.Line & ", Char: " & theError.Character & vbCrLf & "Description: " & theError.Description & vbCrLf & "Source Text: " & theError.SourceText
    WScript.Quit -1
End Sub
[JScript]
var Controller = WScript.CreateObject("WSHController");
var RemoteScript = Controller.CreateScript("test.js", "remoteserver");
WScript.ConnectObject(RemoteScript, "remote_");
RemoteScript.Execute();

while (RemoteScript.Status != 2) {
    WScript.Sleep(100);
}

function remote_Error()
{
    var theError = RemoteScript.Error;
    WScript.Echo("Error - Line: " + theError.Line + ", Char: " + theError.Character + "\nDescription: " + theError.Description + "\nSource Text: "_+ theError.SourceText);
    WScript.Quit(-1);
}

See Also

WshRemote Object | WshRemoteError Object | Description Property | Line Property | Character Property| Number Property | Source Property


SpecialFolders Property

Returns a SpecialFolders object (a collection of special folders).

object.SpecialFolders(objWshSpecialFolders)

Arguments

object
WshShell object.
objWshSpecialFolders
The name of the special folder.

Remarks

The WshSpecialFolders object is a collection. It contains the entire set of Windows special folders, such as the Desktop folder, the Start Menu folder, and the Personal Documents folder. The special folder name is used to index into the collection to retrieve the special folder you want. The SpecialFolders property returns an empty string if the requested folder (strFolderName) is not available. For example, Windows 95 does not have an AllUsersDesktop folder and returns an empty string if strFolderNameis AllUsersDesktop.

The following special folders are available:

  • AllUsersDesktop
  • AllUsersStartMenu
  • AllUsersPrograms
  • AllUsersStartup
  • Desktop
  • Favorites
  • Fonts
  • MyDocuments
  • NetHood
  • PrintHood
  • Programs
  • Recent
  • SendTo
  • StartMenu
  • Startup
  • Templates

Example

The following example demonstrates the use of the SpecialFolders property:

<package>
   <job id="vbs">
      <script language="VBScript">
         set WshShell = WScript.CreateObject("WScript.Shell")
         strDesktop = WshShell.SpecialFolders("Desktop")
         set oShellLink = WshShell.CreateShortcut(strDesktop & "\Shortcut Script.lnk")
         oShellLink.TargetPath = WScript.ScriptFullName
         oShellLink.WindowStyle = 1
         oShellLink.Hotkey = "Ctrl+Alt+e"
         oShellLink.IconLocation = "notepad.exe, 0"
         oShellLink.Description = "Shortcut Script"
         oShellLink.WorkingDirectory = strDesktop
         oShellLink.Save
         set oUrlLink = WshShell.CreateShortcut(strDesktop & "\Microsoft Web Site.url")
         oUrlLink.TargetPath = "http://www.microsoft.com"
         oUrlLink.Save
      </script>
   </job>

   <job id="js">
      <script language="JScript">
         var WshShell = WScript.CreateObject("WScript.Shell");
         strDesktop = WshShell.SpecialFolders("Desktop");
         var oShellLink = WshShell.CreateShortcut(strDesktop + "\\Shortcut Script.lnk");
         oShellLink.TargetPath = WScript.ScriptFullName;
         oShellLink.WindowStyle = 1;
         oShellLink.Hotkey = "Ctrl+Alt+e";
         oShellLink.IconLocation = "notepad.exe, 0";
         oShellLink.Description = "Shortcut Script";
         oShellLink.WorkingDirectory = strDesktop;
         oShellLink.Save();
         var oUrlLink = WshShell.CreateShortcut(strDesktop + "\\Microsoft Web Site.url");
         oUrlLink.TargetPath = "http://www.microsoft.com";
         oUrlLink.Save();
      </script>
   </job>
</package>

See Also

Running Your Scripts | WshSpecialFolders Object | WshShell Object


Status Property (WshRemote)

Reports the current status of the remote script.

Object.Status

Arguments

Object
WshRemote object.

Remarks

The Status property returns a read-only enumerated data type.

Values

The Status property returns one of three possible values.

Return Value | 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.

Example

The following JScript code demonstrates how to use the Status property in a test block that checks to see if a remote script terminated normally.

[VBScript]
Dim Controller, RemoteScript
Set Controller = WScript.CreateObject("WSHController")
Set RemoteScript = Controller.CreateScript("test.js", "remoteserver")
RemoteScript.Execute

Do While RemoteScript.Status <> 2
    WScript.Sleep 100
Loop
[JScript]
var Controller = WScript.CreateObject("WSHController");
var RemoteScript = Controller.CreateScript("test.js", "remoteserver");
RemoteScript.Execute();

while (RemoteScript.Status != 2) {
    WScript.Sleep(100);
}

See Also

WshController Object | WshRemote Object | Error Property | Execute Method | Terminate Method | Start Event | End Event | Error Event


Status Property (WshScriptExec)

Provides status information about a script run with the Exec() method.

Object.Status

Arguments

Object
WshScriptExec object.

Remarks

The Status property is used when a program is run asynchronously.

Return Values

The Status property returns a value from an enumerated type.

WshRunning ( = 0)
The job is still running.
WshFinished ( = 1)
The job has completed.

Example

The following code runs calc.exe and echoes the final status to the screen.

[VBScript]
Dim WshShell, oExec
Set WshShell = CreateObject("WScript.Shell")

Set oExec = WshShell.Exec("calc")

Do While oExec.Status = 0
     WScript.Sleep 100
Loop

WScript.Echo oExec.Status
[JScript]
var WshShell = new ActiveXObject("WScript.Shell");
var oExec = WshShell.Exec("calc");

while (oExec.Status == 0)
{
     WScript.Sleep(100);
}

WScript.Echo(oExec.Status);

See Also

Exec Method | WshScriptExec Object


StdErr Property (WScript)

Exposes the write-only error output stream for the current script.

object.StdErr

Arguments

object
WScript object.

Remarks

The StdErr property returns an object representing the standard error stream. The StdIn, StdOut, and StdErr streams can be accessed while using CScript.exe only. Attempting to access these streams while using WScript.exe produces an error.

See Also

Error Messages | WScript Object


StdErr Property (WshScriptExec)

Provides access to the stderr output stream of the Exec object.

Object.StdErr

Arguments

Object
WshScriptExec object.

Remarks

Use the StdErr property to retrieve data sent to the stderr stream from a process started with Exec.

Example

The following code demonstrates the StdErr object by attempting to execute a non-existent command and displaying the results.

[VBScript]
Dim WshShell, oExec
Set WshShell = CreateObject("WScript.Shell")
Set oExec    = WshShell.Exec("%comspec% /c dire")

Function ReadAllFromAny(oExec)

     If Not oExec.StdOut.AtEndOfStream Then
          ReadAllFromAny = oExec.StdOut.ReadAll
          Exit Function
     End If

     If Not oExec.StdErr.AtEndOfStream Then
          ReadAllFromAny = "STDERR: " + oExec.StdErr.ReadAll
          Exit Function
     End If

     ReadAllFromAny = -1
End Function

Dim allInput, tryCount

allInput = ""
tryCount = 0

Do While True

     Dim input
     input = ReadAllFromAny(oExec)

     If -1 = input Then
          If tryCount > 10 And oExec.Status = 1 Then
               Exit Do
          End If
          tryCount = tryCount + 1
          WScript.Sleep 100
     Else
          allInput = allInput & input
          tryCount = 0
     End If
Loop

WScript.Echo allInput
[JScript]
var WshShell = new ActiveXObject("WScript.Shell");
var oExec    = WshShell.Exec("%comspec% /c dire");

function ReadAllFromAny(oExec)
{
     if (!oExec.StdOut.AtEndOfStream)
          return oExec.StdOut.ReadAll();

     if (!oExec.StdErr.AtEndOfStream)
          return "STDERR: " + oExec.StdErr.ReadAll();

     return -1;
}

var allInput = "";
var tryCount = 0;

while (true)
{
     var input = ReadAllFromAny(oExec);
     if (-1 == input)
     {
          if (tryCount++ > 10 && oExec.Status == 1)
               break;
          WScript.Sleep(100);
     }
     else
     {
          allInput += input;
          tryCount = 0;
     }
}

WScript.Echo(allInput);

See Also

WshScriptExec Object | StdIn Property | StdOut Property


StdIn Property (WScript)

Exposes the read-only input stream for the current script.

object.StdIn

Arguments

object
WScript object.

Remarks

The StdIn property returns an object representing the standard input stream. The StdIn, StdOut, and StdErr streams can be accessed while using CScript.exe only. Attempting to access these streams while using WScript.exe produces an error.

See Also

Error Messages | WScript Object | Read Method | ReadAll Method | ReadLine Method | Skip Method | SkipLine Method | AtEndOfLine Property | Close Method | Column Property | Line Property (WScript)


StdIn Property (WshScriptExec)

Exposes the stdin input stream of the Exec object.

Object.StdIn

Arguments

Object
WshScriptExec object.

Remarks

Use the StdIn property to pass data to a process started using Exec.

Example

The following code starts a batch file and waits for the user input prompt. After entering the needed data through the StdIn stream, the batch file will be able to complete.

[VBScript]
Dim WshShell, oExec, input
Set WshShell = CreateObject("WScript.Shell")
Set oExec    = WshShell.Exec("test.bat")
input = ""

Do While True

     If Not oExec.StdOut.AtEndOfStream Then
          input = input & oExec.StdOut.Read(1)
          If InStr(input, "Press any key") <> 0 Then Exit Do
     End If
     WScript.Sleep 100
Loop

oExec.StdIn.Write VbCrLf

Do While oExec.Status <> 1
     WScript.Sleep 100
Loop
[JScript]
var WshShell = new ActiveXObject("WScript.Shell");
var oExec    = WshShell.Exec("test.bat");
var input = "";

while (true)
{
     if (!oExec.StdOut.AtEndOfStream)
     {
          input += oExec.StdOut.Read(1);
          if (input.indexOf("Press any key") != -1)
               break;
     }
     WScript.Sleep(100);
}

oExec.StdIn.Write("\n");

while (oExec.Status != 1)
     WScript.Sleep(100);

See Also

WshScriptExec Object | StdIn Property | StdErr Property


StdOut Property (WScript)

Exposes the write-only output stream for the current script.

object.StdOut

Arguments

object
WScript object.

Remarks

The StdOut property returns an object representing the standard output stream. The StdIn, StdOut, and StdErr streams can be accessed while using CScript.exe only. Attempting to access these streams while using WScript.exe produces an error.

See Also

Error Messages | WScript Object | Write Method | WriteBlankLines Method | WriteLine Method | Close Method | Column Property | Line Property (WScript)


StdOut Property (WshScriptExec)

Exposes the write-only stdout output stream of the Exec object.

Object.StdOut

Arguments

Object
WshScriptExec object.

Remarks

The StdOut property contains a read-only copy of any information the script may have sent to the standard output.

Example

The following code starts a batch file and waits for the user input prompt. After entering the needed data through the StdIn stream, the batch file will be able to complete.

[VBScript]
Dim WshShell, oExec, input
Set WshShell = CreateObject("WScript.Shell")
Set oExec    = WshShell.Exec("test.bat")
input = ""

Do While True

     If Not oExec.StdOut.AtEndOfStream Then
          input = input & oExec.StdOut.Read(1)
          If InStr(input, "Press any key") <> 0 Then Exit Do
     End If
     WScript.Sleep 100
Loop

oExec.StdIn.Write VbCrLf

Do While oExec.Status <> 1
     WScript.Sleep 100
Loop
[JScript]
var WshShell = new ActiveXObject("WScript.Shell");
var oExec    = WshShell.Exec("test.bat");
var input = "";

while (true)
{
     if (!oExec.StdOut.AtEndOfStream)
     {
          input += oExec.StdOut.Read(1);
          if (input.indexOf("Press any key") != -1)
               break;
     }
     WScript.Sleep(100);
}

oExec.StdIn.Write("\n");

while (oExec.Status != 1)
     WScript.Sleep(100);

See Also

WshScriptExec Object | StdIn Property | StdErr Property


TargetPath Property

The path to the shortcut's executable.

object.TargetPath

Arguments

object
WshShortcut or WshUrlShortcut object.

Remarks

String.

This property is for the shortcut's target path only. Any arguments to the shortcut must be placed in the Argument's property.

Example

The following example demonstrates the use of the TargetPath property:

<package>
   <job id="vbs">
      <script language="VBScript">
         set WshShell = WScript.CreateObject("WScript.Shell")
         strDesktop = WshShell.SpecialFolders("Desktop")
         set oShellLink = WshShell.CreateShortcut(strDesktop & "\Shortcut Script.lnk")
         oShellLink.TargetPath = WScript.ScriptFullName
         oShellLink.WindowStyle = 1
         oShellLink.Hotkey = "Ctrl+Alt+e"
         oShellLink.IconLocation = "notepad.exe, 0"
         oShellLink.Description = "Shortcut Script"
         oShellLink.WorkingDirectory = strDesktop
         oShellLink.Save
         set oUrlLink = WshShell.CreateShortcut(strDesktop & "\Microsoft Web Site.url")
         oUrlLink.TargetPath = "http://www.microsoft.com"
         oUrlLink.Save
      </script>
   </job>

   <job id="js">
      <script language="JScript">
         var WshShell = WScript.CreateObject("WScript.Shell");
         strDesktop = WshShell.SpecialFolders("Desktop");
         var oShellLink = WshShell.CreateShortcut(strDesktop + "\\Shortcut Script.lnk");
         oShellLink.TargetPath = WScript.ScriptFullName;
         oShellLink.WindowStyle = 1;
         oShellLink.Hotkey = "Ctrl+Alt+e";
         oShellLink.IconLocation = "notepad.exe, 0";
         oShellLink.Description = "Shortcut Script";
         oShellLink.WorkingDirectory = strDesktop;
         oShellLink.Save();
         var oUrlLink = WshShell.CreateShortcut(strDesktop + "\\Microsoft Web Site.url");
         oUrlLink.TargetPath = "http://www.microsoft.com";
         oUrlLink.Save();
      </script>
   </job>
</package>

See Also

Running Your Scripts | WshShortcut Object | WshUrlShortcut Object


Unnamed Property

Returns the WshUnnamed object (a collection of unnamed arguments).

Object.Unnamed

Parameters

Object
WshArguments object.

Remarks

The Unnamed property returns the WshUnnamed collection, the collection of unnamed arguments. The arguments are presented in the order that they were entered on the command line. The first unnamed argument at index 0.

Example

The following code displays the number of named and unnamed command-line arguments.

<package>
<job id="JS">
<script language="JScript">

var argsNamed = WScript.Arguments.Named;
var argsUnnamed = WScript.Arguments.Unnamed;

WScript.Echo("There are " + argsNamed.length + " named arguments.");
WScript.Echo("There are " + argsUnnamed.length + " unnamed arguments.");

</script>
</job>

<job id="VBS">
<script language="VBScript">

Dim argsNamed, argsUnnamed
Set argsNamed = WScript.Arguments.Named
Set argsUnnamed = WScript.Arguments.Unnamed

WScript.Echo "There are " & argsNamed.Count & " named arguments."
WScript.Echo "There are " & argsUnnamed.Count & " unnamed arguments."

</script>
</job>
</package>

See Also

WshArguments Object | WshUnnamed Object | Named Property


UserDomain Property

Returns a user's domain name.

object.UserDomain

Arguments

object
WshNetwork object.

Remarks

String.

The UserDomain property does not work on Windows98 and Windows ME unless the USERDOMAIN environment variable is set. The variable is not set by default.

Example

The following example demonstrates the use of the UserDomain property:

<package>
   <job id="vbs">
      <script language="VBScript">
         Set WshNetwork = WScript.CreateObject("WScript.Network")
         WScript.Echo "Domain = " & WshNetwork.UserDomain
         WScript.Echo "Computer Name = " & WshNetwork.ComputerName
         WScript.Echo "User Name = " & WshNetwork.UserName
      </script>
   </job>

   <job id="js">
      <script language="JScript">
         var WshNetwork = WScript.CreateObject("WScript.Network");
         WScript.Echo("Domain = " + WshNetwork.UserDomain);
         WScript.Echo("Computer Name = " + WshNetwork.ComputerName);
         WScript.Echo("User Name = " + WshNetwork.UserName);
         }
      </script>
   </job>
</package>

See Also

Running Your Scripts | WshNetwork Object


UserName Property

Returns the name of a user.

object.UserName

Arguments

object
WshNetwork object.

Remarks

String.

If you are using this property in a login script, see Creating an Automated Login Script.

Example

The following example demonstrates the use of the UserName property:

<package>
   <job id="vbs">
      <script language="VBScript">
         Set WshNetwork = WScript.CreateObject("WScript.Network")
         WScript.Echo "Domain = " & WshNetwork.UserDomain
         WScript.Echo "Computer Name = " & WshNetwork.ComputerName
         WScript.Echo "User Name = " & WshNetwork.UserName
      </script>
   </job>

   <job id="js">
      <script language="JScript">
         var WshNetwork = WScript.CreateObject("WScript.Network");
         WScript.Echo("Domain = " + WshNetwork.UserDomain);
         WScript.Echo("Computer Name = " + WshNetwork.ComputerName);
         WScript.Echo("User Name = " + WshNetwork.UserName);
         }
      </script>
   </job>
</package>

See Also

Running Your Scripts | WshNetwork Object


Version Property

Returns the version of Windows Script Host.

object.Version

Arguments

object
WScript object.

Remarks

String.

Example

The following VBScript code echoes the current version of Windows Script Host.

WScript.Echo WScript.Version

See Also

WScript Object


WindowStyle Property

Assigns a window style to a shortcut, or identifies the type of window style used by a shortcut.

object.WindowStyle = intWindowStyle

Arguments

object
WshShortcut object.
intWindowStyle
Sets the window style for the program being run.

Remarks

The WindowStyle property returns an integer.

The following table lists the available settings for intWindowStyle.

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

Example

The following example demonstrates the use of the WindowStyle property:

<package>
   <job id="vbs">
      <script language="VBScript">
         set WshShell = WScript.CreateObject("WScript.Shell")
         strDesktop = WshShell.SpecialFolders("Desktop")
         set oShellLink = WshShell.CreateShortcut(strDesktop & "\Shortcut Script.lnk")
         oShellLink.TargetPath = WScript.ScriptFullName
         oShellLink.WindowStyle = 1
         oShellLink.Hotkey = "Ctrl+Alt+e"
         oShellLink.IconLocation = "notepad.exe, 0"
         oShellLink.Description = "Shortcut Script"
         oShellLink.WorkingDirectory = strDesktop
         oShellLink.Save
         set oUrlLink = WshShell.CreateShortcut(strDesktop & "\Microsoft Web Site.url")
         oUrlLink.TargetPath = "http://www.microsoft.com"
         oUrlLink.Save
      </script>
   </job>

   <job id="js">
      <script language="JScript">
         var WshShell = WScript.CreateObject("WScript.Shell");
         strDesktop = WshShell.SpecialFolders("Desktop");
         var oShellLink = WshShell.CreateShortcut(strDesktop + "\\Shortcut Script.lnk");
         oShellLink.TargetPath = WScript.ScriptFullName;
         oShellLink.WindowStyle = 1;
         oShellLink.Hotkey = "Ctrl+Alt+e";
         oShellLink.IconLocation = "notepad.exe, 0";
         oShellLink.Description = "Shortcut Script";
         oShellLink.WorkingDirectory = strDesktop;
         oShellLink.Save();
         var oUrlLink = WshShell.CreateShortcut(strDesktop + "\\Microsoft Web Site.url");
         oUrlLink.TargetPath = "http://www.microsoft.com";
         oUrlLink.Save();
      </script>
   </job>
</package>

See Also

Running Your Scripts | WshShortcut Object


WorkingDirectory Property

Assign a working directory to a shortcut, or identifies the working directory used by a shortcut.

object.WorkingDirectory = strWorkingDirectory

Arguments

object
WshShortcut object.
strWorkingDirectory
String. Directory in which the shortcut starts.

Remarks

String.

Example

The following example demonstrates the use of the WorkingDirectory property:

<package>
   <job id="vbs">
      <script language="VBScript">
         set WshShell = WScript.CreateObject("WScript.Shell")
         strDesktop = WshShell.SpecialFolders("Desktop")
         set oShellLink = WshShell.CreateShortcut(strDesktop & "\Shortcut Script.lnk")
         oShellLink.TargetPath = WScript.ScriptFullName
         oShellLink.WindowStyle = 1
         oShellLink.Hotkey = "Ctrl+Alt+e"
         oShellLink.IconLocation = "notepad.exe, 0"
         oShellLink.Description = "Shortcut Script"
         oShellLink.WorkingDirectory = strDesktop
         oShellLink.Save
         set oUrlLink = WshShell.CreateShortcut(strDesktop & "\Microsoft Web Site.url")
         oUrlLink.TargetPath = "http://www.microsoft.com"
         oUrlLink.Save
      </script>
   </job>

   <job id="js">
      <script language="JScript">
         var WshShell = WScript.CreateObject("WScript.Shell");
         strDesktop = WshShell.SpecialFolders("Desktop");
         var oShellLink = WshShell.CreateShortcut(strDesktop + "\\Shortcut Script.lnk");
         oShellLink.TargetPath = WScript.ScriptFullName;
         oShellLink.WindowStyle = 1;
         oShellLink.Hotkey = "Ctrl+Alt+e";
         oShellLink.IconLocation = "notepad.exe, 0";
         oShellLink.Description = "Shortcut Script";
         oShellLink.WorkingDirectory = strDesktop;
         oShellLink.Save();
         var oUrlLink = WshShell.CreateShortcut(strDesktop + "\\Microsoft Web Site.url");
         oUrlLink.TargetPath = "http://www.microsoft.com";
         oUrlLink.Save();
      </script>
   </job>
</package>

See Also

Running Your Scripts


Methods

In this Section

AddPrinterConnection Method
Adds a DOS-style printer connection to your computer.
AddWindowsPrinterConnection Method
Adds a Windows-style printer connection to your computer.
AppActivate Method
Activates an application window.
Close Method
Closes an open stream.
ConnectObject Method
Connects an object's event sources to functions with a given prefix.
Count Method
Returns the number of switches in the WshNamed or WshUnnamed objects.
CreateObject Method
Creates an object specified by the strProgID parameter.
CreateScript Method
Creates a WshRemote object (an object that represents an instance of a script running in a remote process).
CreateShortcut Method
Creates an object reference to a shortcut or URLshortcut.
DisconnectObject Method
Disconnects a previously connected object from Windows Script Host.
Echo Method
Sends output to a dialog box or the console.
EnumNetworkDrives Method
Returns the current network drive mappings.
EnumPrinterConnections Method
Returns the current network printer mappings.
Exec Method
Runs an application in a child command-shell, providing access to the stdin/stdout/stderr channels, and the sharing of environment variables.
Execute Method
Starts execution of a remote script object.
Exists Method
Indicates whether a specific key value exists in the WshNamed object.
ExpandEnvironmentStrings Method
Expands the requested environment variable from the running process and returns the result string.
GetObject Method
Retrieves an Automation object from a file or an object specified by the strProgID parameter.
getResource Method
Returns the value of a resource defined with the resource element.
LogEvent Method
Logs an event in the Windows NT event log or WSH.log file.
MapNetworkDrive Method
Maps the share point specified by strRemoteName to the local resource name strLocalName.
Popup Method
Displays a pop-up message box window that contains the message contained in strText.
Quit Method
Quits execution with a specified error code.
Read Method
Reads a specified number of characters from an input stream and returns the resulting string.
ReadAll Method
Reads an entire input stream and returns the resulting string.
ReadLine Method
Reads an entire line (up to, but not including, the newline character) from an input stream and returns the resulting string.
RegDelete Method
Deletes from the registry the key or value named by strName.
RegRead Method
Returns the registry key or value named by strName.
RegWrite Method
Sets the registry key or value named by strName.
Remove Method
Deletes the environment variable specified by strName.
RemoveNetworkDrive Method
Removes the current resource connection denoted by strName.
RemovePrinterConnection Method
Removes the current resource connection denoted by strName.
Run Method
Creates a new process that executes strCommand.
Save Method
Saves a shortcut to the specified location.
SendKeys Method
Sends one or more keystrokes to the active window (as if typed on the keyboard).
SetDefaultPrinter Method
Sets the default printer to the remote printer specified.
ShowUsage Method
Displays information about how a script should be used.
Skip Method
Skips a specified number of characters when reading an input stream.
SkipLine Method
Skips the next line when reading an input stream.
Sleep Method
Places the script process into an inactive state for the number of milliseconds specified and then continues execution.
Terminate Method (WshScriptExec)
Instructs the script engine to end the process started by the Exec method.
Write Method
Writes a specified string to an output stream.
WriteBlankLines Method
Writes a specified number of newline characters to an output stream.
WriteLine Method
Writes a specified string and newline character to an output stream.

Related Sections

WSH Language
List of elements that make up WSH Reference.
WSH Basics
Learn the basics of WSH.


AddPrinterConnection Method

Adds a remote MS-DOS-based printer connection to your computer system.

object.AddPrinterConnection(strLocalName, strRemoteName[,bUpdateProfile][,strUser][,strPassword])

Arguments

object
WshNetwork object.
strLocalName
Sting value indicating the local name to assign to the connected printer.
strRemoteName
Sting value indicating the name of the remote printer.
bUpdateProfile
Optional. Boolean value indicating whether the printer mapping is stored in the current user's profile. If bUpdateProfile is supplied and is true, the mapping is stored in the user profile. The default value is false.
strUser
Optional. String value indicating the user name. If you are mapping a remote printer using the profile of someone other than current user, you can specify strUser and strPassword.
strPassword
Optional. String value indicating the user password. If you are mapping a remote printer using the profile of someone other than current user, you can specify strUser and strPassword.

Remarks

The AddPrinterConnection method adds a network printer to an MS-DOS printer port, such as LPT1. You cannot use this method to add a remote Windows-based printer connection. To add a remote Windows-based printer connection, use the AddWindowsPrinterConnection method.

Example

The following code uses the AddPrinterConnection method to connect a network printer to LPT1.

[VBScript]
Set WshNetwork = WScript.CreateObject("WScript.Network")
WshNetwork.AddPrinterConnection "LPT1", "\\Server\Print1"
[JScript]
var WshNetwork = WScript.CreateObject("WScript.Network");
WshNetwork.AddPrinterConnection ("LPT1", "\\\\Server\\Print1");

See Also

WshNetwork Object | AddWindowsPrinterConnection Method | EnumPrinterConnections Method | RemovePrinterConnection Method | SetDefaultPrinter Method


AddWindowsPrinterConnection Method

Adds a Windows-based printer connection to your computer system.

Windows NT/2000:
object.AddWindowsPrinterConnection(
   strPrinterPath
)
Windows 9x/Me:
object.AddWindowsPrinterConnection(
   strPrinterPath,
   strDriverName[,strPort]
)

Arguments

object
WshNetwork object.
strPrinterPath
String value indicating the path to the printer connection.
strDriverName
String value indicating the name of the driver (ignored if used on Windows NT/Windows 2000).
strPort
Optional. String value specifying a printer port for the printer connection (ignored on Windows NT/Windows 2000).

Remarks

Using this method is similar to using the Printer option on Control Panel to add a printer connection. Unlike the AddPrinterConnection method, this method allows you to create a printer connection without directing it to a specific port, such as LPT1. If the connection fails, an error is thrown. In Windows 9x/Me, the printer driver must already be installed on the machine for the AddWindowsPrinterConnection method to work. If the driver is not installed, Windows returns an error message.

Example 1

The following code uses the AddWindowsPrinterConnection method to connect a network printer to a Windows NT/2000 computer system.

[VBScript]
Set WshNetwork = WScript.CreateObject("WScript.Network")
PrinterPath = "\\printserv\DefaultPrinter"
WshNetwork.AddWindowsPrinterConnection PrinterPath
[JScript]
var WshNetwork = WScript.CreateObject("WScript.Network");
var PrinterPath = "\\\\printserv\\DefaultPrinter";
WshNetwork.AddWindowsPrinterConnection(PrinterPath);

Example 2

The following code uses the AddWindowsPrinterConnection method to connect a network printer to a Windows 9x/Me computer system.

[VBScript]
Set WshNetwork = WScript.CreateObject("WScript.Network")
PrinterPath = "\\printserv\DefaultPrinter"
PrinterDriver = "Lexmark Optra S 1650"
WshNetwork.AddWindowsPrinterConnection PrinterPath, PrinterDriver
[JScript]
var WshNetwork = WScript.CreateObject("WScript.Network");
var PrinterPath = "\\\\printserv\\DefaultPrinter";
var PrinterDriver = "Lexmark Optra S 1650";
WshNetwork.AddWindowsPrinterConnection(PrinterPath, PrinterDriver);

See Also

WshNetwork Object | AddPrinterConnection Method | EnumPrinterConnections Method | RemovePrinterConnection Method | SetDefaultPrinter Method


AppActivate Method

Activates an application window.

object.AppActivate title

Arguments

object
WshShell object.
title
Specifies which application to activate. This can be a string containing the title of the application (as it appears in the title bar) or the application's Process ID.

Remarks

The AppActivate method returns a Boolean value that identifies whether the procedure call is successful. This method changes the focus to the named application or window, but it does not affect whether it is maximized or minimized. Focus moves from the activated application window when the user takes action to change the focus (or closes the window).

In determining which application to activate, the specified title is compared to the title string of each running application. If no exact match exists, any application whose title string begins with title is activated. If an application still cannot be found, any application whose title string ends with title is activated. If more than one instance of the application named by title exists, one instance is arbitrarily activated.

Example

The following example demonstrates the use of a single .wsf file for two jobs in different script languages (VBScript and JScript). The functionality of both jobs is the same — each runs the Windows calculator and sends it keystrokes to execute a simple calculation.

The following example starts the Windows calculator and uses AppActivate to ensure that the calculator is at the top.

<package>
   <job id="vbs">
      <script language="VBScript">
         set WshShell = WScript.CreateObject("WScript.Shell")
         WshShell.Run "calc"
         WScript.Sleep 100
         WshShell.AppActivate "Calculator"
         WScript.Sleep 100
         WshShell.SendKeys "1{+}"
         WScript.Sleep 500
         WshShell.SendKeys "2"
         WScript.Sleep 500
         WshShell.SendKeys "~"
         WScript.Sleep 500
         WshShell.SendKeys "*3"
         WScript.Sleep 500
         WshShell.SendKeys "~"
         WScript.Sleep 2500
      </script>
   </job>

   <job id="js">
      <script language="JScript">
         var WshShell = WScript.CreateObject("WScript.Shell");
         WshShell.Run("calc");
         WScript.Sleep(100);
         WshShell.AppActivate("Calculator");
         WScript.Sleep(100);
         WshShell.SendKeys("1{+}");
         WScript.Sleep(500);
         WshShell.SendKeys("2");
         WScript.Sleep(500);
         WshShell.SendKeys("~");
         WScript.Sleep(500);
         WshShell.SendKeys("*3");
         WScript.Sleep(500);
         WshShell.SendKeys("~");
         WScript.Sleep(2500);
      </script>
   </job>
</package>

See Also

Running Your Scripts | WshShell Object | SendKeys Method


Close Method

Closes a text stream.

object.Close

Arguments

object
StdIn, StdOut, or StdErr text stream objects.

Remarks

The StdIn, StdOut, and StdErr properties and methods work when running the script with the CScript.exe host executable file only. An error is returned when run with WScript.exe. It is not necessary to close standard streams; they close automatically when the process ends. If you close a standard stream, be aware that any other pointers to that standard stream become invalid. This method is provided for compatibility with the TextStream object.

See Also

StdErr Property | StdIn Property | StdOut Property | Error Messages


ConnectObject Method

Connects the object's event sources to functions with a given prefix.

object.ConnectObject(strObject, strPrefix)

Arguments

object
WScript object.
strObject
Required. String value indicating the name of the object you want to connect.
strPrefix
Required. String value indicating the function prefix.

Remarks

Connected objects are useful when you want to sync an object's events. The ConnectObject method connects the object's outgoing interface to the script file after creating the object. Event functions are a combination of this prefix and the event name.

Example

The following example demonstrates using the ConnectObject method to connect to the WshRemote object's Error event.

[VBScript]
Dim Controller, RemoteScript
Set Controller = WScript.CreateObject("WSHController")
Set RemoteScript = Controller.CreateScript("test.js", "remoteserver")
WScript.ConnectObject RemoteScript, "remote_"
RemoteScript.Execute

Do While RemoteScript.Status <> 2
    WScript.Sleep 100
Loop

Sub remote_Error
    Dim theError
    Set theError = RemoteScript.Error
    WScript.Echo "Error " & theError.Number & " - Line: " & theError.Line & ", Char: " & theError.Character & vbCrLf & "Description: " & theError.Description
    WScript.Quit -1
End Sub
[JScript]
var Controller = WScript.CreateObject("WSHController");
var RemoteScript = Controller.CreateScript("test.js", "remoteserver");
WScript.ConnectObject(RemoteScript, "remote_");
RemoteScript.Execute();

while (RemoteScript.Status != 2) {
    WScript.Sleep(100);
}

function remote_Error()
{
    var theError = RemoteScript.Error;
    WScript.Echo("Error " + theError.Number + " - Line: " + theError.Line + ", Char: " + theError.Character + "\nDescription: " + theError.Description);
    WScript.Quit(-1);
}

See Also

WScript Object | DisconnectObject Method | CreateObject Method | GetObject Method


Count Method

Returns the number of switches in the WshNamed or WshUnnamed objects.

object.Count

Arguments

object
Arguments object.

Remarks

The Count method returns an integer value. The Count method is primarily intended for VBScript users. JScript users should generally use the length property instead.

Example (WshNamed)

The following example demonstrates the Count method using the WshNamed object. Begin by typing the following text at the Command Prompt.

myScript.vbs /c:"WSH is a wonderful thing" /s:"scripts are wonderful"

Next, add the following VBScript code.

For i = 0 to WScript.Arguments.Count-1
    WScript.Echo WScript.Arguments.Named(i)
next i

Following is the result.

WSH is a wonderful thing
scripts are wonderful

Example (WshUnnamed)

The following example demonstrates the Count method using the WshUnnamed object. Begin by typing the following text at the command line.

myscript.vbs "WSH is a wonderful thing" "scripts are wonderful"

Next, add the following VBScript code.

For i = 0 to WScript.Arguments.Count-1
    WScript.Echo WScript.Arguments.Unnamed(i)
next i

Following is the result.

WSH is a wonderful thing
scripts are wonderful

See Also

Arguments Property | WshNamed Object | WshUnnamed Object | Item Property | Exists Method | Length Property


CreateObject Method

Creates a COM object.

object.CreateObject(strProgID[,strPrefix])

Arguments

object
WScript object.
strProgID
String value indicating the programmatic identifier (ProgID) of the object you want to create.
strPrefix
Optional. String value indicating the function prefix.

Remarks

Objects created with the CreateObject method using the strPrefix argument are connected objects. These are useful when you want to sync an object's events. The object's outgoing interface is connected to the script file after the object is created. Event functions are a combination of this prefix and the event name. If you create an object and do not supply the strPrefix argument, you can still sync events on the object by using the ConnectObject method. When the object fires an event, WSH calls a subroutine with strPrefix attached to the beginning of the event name. For example, if strPrefix is MYOBJ and the object fires an event named OnBegin, Windows Script Host calls the MYOBJ_OnBegin subroutine located in the script. The CreateObject method returns a pointer to the object's IDispatch interface.

Example

The following VBScript code uses the CreateObject method to create a WshNetwork object:

Set WshNetwork = WScript.CreateObject("WScript.Network")

See Also

WScript Object | GetObject Method | ConnectObject Method | DisconnectObject Method


CreateScript Method

Creates a WshRemote object.

object.CreateScript(CommandLine,[MachineName])

Parameters

object
WshController Object.
Commandline
Required. String value indicating the script's path and switches as they would be typed at the command prompt. The path to the script should appear as seen from the controller computer system rather than the computer system on which you want to run the script.
MachineName
Optional. String value indicating the name of the remote computer system (the computer on which you want to run the remote script). It is specified in the Uniform Naming Convention (UNC).

Remarks

The CreateScript method returns a handle to an instance of a WshRemote object. The path part of the script name does not need to be local — it can refer to a script on a network share. This makes it possible to sit at one computer system, retrieve a script from another computer system, and run it on a third computer system. If a machine name is not provided, the remote script object runs on the controller computer system (this is the default). If a machine name is provided, the remote script object runs on the named computer system. The CreateScript method establishes a connection with the remote computer system and sets it up to run the script, but the script does not actually start until you call the Execute method of the WshRemote object.

Example

The following example demonstrates how the CreateScript method of the WshController object is used to create a WshRemote object (an instance of a remote script).

[VBScript]
Dim Controller, RemoteScript
Set Controller = WScript.CreateObject("WSHController")
Set RemoteScript = Controller.CreateScript("test.js", "remoteserver")
WScript.ConnectObject RemoteScript, "remote_"
RemoteScript.Execute

Do While RemoteScript.Status <> 2
    WScript.Sleep 100
Loop

WScript.DisconnectObject RemoteScript

Sub remote_Error
    Dim theError
    Set theError = RemoteScript.Error
    WScript.Echo "Error " & theError.Number & " - Line: " & theError.Line & ", Char: " & theError.Character & vbCrLf & "Description: " & theError.Description
    WScript.Quit -1
End Sub
[JScript]
var Controller = WScript.CreateObject("WSHController");
var RemoteScript = Controller.CreateScript("test.js", "remoteserver");
WScript.ConnectObject(RemoteScript, "remote_");
RemoteScript.Execute();

while (RemoteScript.Status != 2) {
    WScript.Sleep(100);
}

WScript.DisconnectObject(RemoteScript);

function remote_Error()
{
    var theError = RemoteScript.Error;
    WScript.Echo("Error " + theError.Number + " - Line: " + theError.Line + ", Char: " + theError.Character + "\nDescription: " + theError.Description);
    WScript.Quit(-1);
}

See Also

CreateObject Method | CreateScript Method | WshRemote Object | Execute Method


CreateShortcut Method

Creates a new shortcut, or opens an existing shortcut.

object.CreateShortcut(strPathname)

Arguments

object
WshShell object.
strPathname
String value indicating the pathname of the shortcut to create.

Remarks

The CreateShortcut method returns either a WshShortcut object or a WshURLShortcut object. Simply calling the CreateShortcut method does not result in the creation of a shortcut. The shortcut object and changes you may have made to it are stored in memory until you save it to disk with the Save method. To create a shortcut, you must:

  1. Create an instance of a WshShortcut object.
  2. Initialize its properties.
  3. Save it to disk with the Save method.
    Note A common problem is putting arguments in the TargetPath property of the shortcut object, which doesn't work. All arguments to the shortcut must be put in the Arguments property.

Example

The following example creates a WshShell object and uses the CreateShortcut method to create two shortcuts.

<package>
   <job id="vbs">
      <script language="VBScript">
         set WshShell = WScript.CreateObject("WScript.Shell")
         strDesktop = WshShell.SpecialFolders("Desktop")
         set oShellLink = WshShell.CreateShortcut(strDesktop & "\Shortcut Script.lnk")
         oShellLink.TargetPath = WScript.ScriptFullName
         oShellLink.WindowStyle = 1
         oShellLink.Hotkey = "CTRL+SHIFT+F"
         oShellLink.IconLocation = "notepad.exe, 0"
         oShellLink.Description = "Shortcut Script"
         oShellLink.WorkingDirectory = strDesktop
         oShellLink.Save
         set oUrlLink = WshShell.CreateShortcut(strDesktop & "\Microsoft Web Site.url")
         oUrlLink.TargetPath = "http://www.microsoft.com"
         oUrlLink.Save
      </script>
   </job>

   <job id="js">
      <script language="JScript">
         var WshShell = WScript.CreateObject("WScript.Shell");
         strDesktop = WshShell.SpecialFolders("Desktop");
         var oShellLink = WshShell.CreateShortcut(strDesktop + "\\Shortcut Script.lnk");
         oShellLink.TargetPath = WScript.ScriptFullName;
         oShellLink.WindowStyle = 1;
         oShellLink.Hotkey = "CTRL+SHIFT+F";
         oShellLink.IconLocation = "notepad.exe, 0";
         oShellLink.Description = "Shortcut Script";
         oShellLink.WorkingDirectory = strDesktop;
         oShellLink.Save();
         var oUrlLink = WshShell.CreateShortcut(strDesktop + "\\Microsoft Web Site.url");
         oUrlLink.TargetPath = "http://www.microsoft.com";
         oUrlLink.Save();
      </script>
   </job>
</package>

See Also

Running Your Scripts | WshShortcut Object | WshUrlShortcut Object | WshShell Object


DisconnectObject Method

Disconnects a connected object's event sources.

object.DisconnectObject(obj)

Arguments

object
WScript object.
obj
String value indicating the name of the object to disconnect.

Remarks

Once an object has been "disconnected," WSH will not respond to its events. The object is still capable of firing events, though. Note that the DisconnectObject method does nothing if the specified object is not already connected.

Example

The following example demonstrates using the DisconnectObject method to disconnect to the WshRemote object's Error event after a remote script has completed.

[VBScript]
Dim Controller, RemoteScript
Set Controller = WScript.CreateObject("WSHController")
Set RemoteScript = Controller.CreateScript("test.js", "remoteserver")
WScript.ConnectObject RemoteScript, "remote_"
RemoteScript.Execute

Do While RemoteScript.Status <> 2
    WScript.Sleep 100
Loop

WScript.DisconnectObject RemoteScript

Sub remote_Error
    Dim theError
    Set theError = RemoteScript.Error
    WScript.Echo "Error " & theError.Number & " - Line: " & theError.Line & ", Char: " & theError.Character & vbCrLf & "Description: " & theError.Description
    WScript.Quit -1
End Sub
[JScript]
var Controller = WScript.CreateObject("WSHController");
var RemoteScript = Controller.CreateScript("test.js", "remoteserver");
WScript.ConnectObject(RemoteScript, "remote_");
RemoteScript.Execute();

while (RemoteScript.Status != 2) {
    WScript.Sleep(100);
}

WScript.DisconnectObject(RemoteScript)

function remote_Error()
{
    var theError = RemoteScript.Error;
    WScript.Echo("Error " + theError.Number + " - Line: " + theError.Line + ", Char: " + theError.Character + "\nDescription: " + theError.Description);
    WScript.Quit(-1);
}

See Also

WScript Object | ConnectObject Method | CreateObject Method | GetObject Method


Echo Method

Outputs text to either a message box or the command console window.

object.Echo [Arg1] [,Arg2] [,Arg3] ...

Arguments

object
WScript object.
Arg1, Arg2, Arg3 ...
Optional. String value indicating the list of items to be displayed.

Remarks

The Echo method behaves differently depending on which WSH engine you are using.

WSH engine | Text Output
Wscript.exe | graphical message box
Cscript.exe | command console window

Each displayed item is separated with a space character. When using CScript.exe, each item is displayed with a newline character. If no items are provided as arguments to the Echo method, a blank line is output.

Example

The following example uses the Echo Method to display the domain name, computer name, and user name for the current machine, and to display network mapping information for the drives and printers.

<package>
   <job id="vbs">
      <script language="VBScript">
         Set WshNetwork = WScript.CreateObject("WScript.Network")
         Set oDrives = WshNetwork.EnumNetworkDrives
         Set oPrinters = WshNetwork.EnumPrinterConnections
         WScript.Echo "Domain = " & WshNetwork.UserDomain
         WScript.Echo "Computer Name = " & WshNetwork.ComputerName
         WScript.Echo "User Name = " & WshNetwork.UserName
         WScript.Echo
         WScript.Echo "Network drive mappings:"
         For i = 0 to oDrives.Count - 1 Step 2
            WScript.Echo "Drive " & oDrives.Item(i) & " = " & oDrives.Item(i+1)
         Next
         WScript.Echo
         WScript.Echo "Network printer mappings:"
         For i = 0 to oPrinters.Count - 1 Step 2
            WScript.Echo "Port " & oPrinters.Item(i) & " = " & oPrinters.Item(i+1)
         Next
      </script>
   </job>

   <job id="js">
      <script language="JScript">
         var WshNetwork = WScript.CreateObject("WScript.Network");
         var oDrives = WshNetwork.EnumNetworkDrives();
         var oPrinters = WshNetwork.EnumPrinterConnections();
         WScript.Echo("Domain = " + WshNetwork.UserDomain);
         WScript.Echo("Computer Name = " + WshNetwork.ComputerName);
         WScript.Echo("User Name = " + WshNetwork.UserName);
         WScript.Echo();
         WScript.Echo("Network drive mappings:");
         for(i=0; i<oDrives.Count(); i+=2){
            WScript.Echo("Drive " + oDrives.Item(i) + " = " + oDrives.Item(i+1));
         }
         WScript.Echo();
         WScript.Echo("Network printer mappings:");
         for(i=0; i<oPrinters.Count(); i+=2){
            WScript.Echo("Port " + oPrinters.Item(i) + " = " + oPrinters.Item(i+1));
         }
      </script>
   </job>
</package>

See Also

Running Your Scripts | WScript Object


EnumNetworkDrives Method

Returns the current network drive mapping information.

objDrives = object.EnumNetworkDrives

Arguments

object
WshNetwork object.
objDrives
Variable that holds the network drive mapping information.

Remarks

The EnumNetworkDrives method returns a collection. This collection is an array that associates pairs of items — network drive local names and their associated UNC names. Even-numbered items in the collection represent local names of logical drives. Odd-numbered items represent the associated UNC share names. The first item in the collection is at index zero (0).

Example

The following example uses EnumNetworkDrives to generate a list of the networked drives and displays the mapping information.

<package>
   <job id="vbs">
      <script language="VBScript">
         Set WshNetwork = WScript.CreateObject("WScript.Network")
         Set oDrives = WshNetwork.EnumNetworkDrives
         Set oPrinters = WshNetwork.EnumPrinterConnections
         WScript.Echo "Network drive mappings:"
         For i = 0 to oDrives.Count - 1 Step 2
            WScript.Echo "Drive " & oDrives.Item(i) & " = " & oDrives.Item(i+1)
         Next
         WScript.Echo
         WScript.Echo "Network printer mappings:"
         For i = 0 to oPrinters.Count - 1 Step 2
            WScript.Echo "Port " & oPrinters.Item(i) & " = " & oPrinters.Item(i+1)
         Next
      </script>
   </job>

   <job id="js">
      <script language="JScript">
         var WshNetwork = WScript.CreateObject("WScript.Network");
         var oDrives = WshNetwork.EnumNetworkDrives();
         var oPrinters = WshNetwork.EnumPrinterConnections();
         WScript.Echo("Network drive mappings:");
         for(i = 0; i < oDrives.length; i += 2) {
            WScript.Echo("Drive " + oDrives.Item(i) + " = " + oDrives.Item(i + 1));
         }
         WScript.Echo();
         WScript.Echo("Network printer mappings:");
         for(i = 0; i < oPrinters.length; i += 2) {
            WScript.Echo("Port " + oPrinters.Item(i) + " = " + oPrinters.Item(i + 1));
         }
      </script>
   </job>
</package>

See Also

Running Your Scripts | WshNetwork Object | MapNetworkDrive Method | RemoveNetworkDrive Method


EnumPrinterConnections Method

Returns the current network printer mapping information.

objPrinters = object.EnumPrinterConnections

Arguments

object
WshNetwork object.
objPrinters
Variable that holds the network printer mapping information.

Remarks

The EnumPrinterConnections method returns a collection. This collection is an array that associates pairs of items — network printer local names and their associated UNC names. Even-numbered items in the collection represent printer ports. Odd-numbered items represent the networked printer UNC names. The first item in the collection is at index zero (0).

Example

The following example uses the EnumPrinterConnections method to generate a list of networked printers and displays this mapping information.

<package>
   <job id="vbs">
      <script language="VBScript">
         Set WshNetwork = WScript.CreateObject("WScript.Network")
         Set oDrives = WshNetwork.EnumNetworkDrives
         Set oPrinters = WshNetwork.EnumPrinterConnections
         WScript.Echo "Network drive mappings:"
         For i = 0 to oDrives.Count - 1 Step 2
            WScript.Echo "Drive " & oDrives.Item(i) & " = " & oDrives.Item(i+1)
         Next
         WScript.Echo
         WScript.Echo "Network printer mappings:"
         For i = 0 to oPrinters.Count - 1 Step 2
            WScript.Echo "Port " & oPrinters.Item(i) & " = " & oPrinters.Item(i+1)
         Next
   </script>
</job>

   <job id="js">
      <script language="JScript">
         var WshNetwork = WScript.CreateObject("WScript.Network");
         var oDrives = WshNetwork.EnumNetworkDrives();
         var oPrinters = WshNetwork.EnumPrinterConnections();
         WScript.Echo("Network drive mappings:");
         for(i = 0; i < oDrives.length; i += 2) {
            WScript.Echo("Drive " + oDrives.Item(i) + " = " + oDrives.Item(i + 1));
         }
         WScript.Echo();
         WScript.Echo("Network printer mappings:");
         for(i = 0; i < oPrinters.length; i += 2) {
            WScript.Echo("Port " + oPrinters.Item(i) + " = " + oPrinters.Item(i + 1));
         }
      </script>
   </job>
</package>

See Also

Running Your Scripts | WshNetwork Object | AddPrinterConnection Method | AddWindowsPrinterConnection Method | RemovePrinterConnection Method | SetDefaultPrinter Method


Exec Method

Runs an application in a child command-shell, providing access to the StdIn/StdOut/StdErr streams.

object.Exec(strCommand)

Arguments

object
WshShell object.
strCommand
String value indicating the command line used to run the script. The command line should appear exactly as it would if you typed it at the command prompt.

Remarks

The Exec method returns a WshScriptExec object, which provides status and error information about a script run with Exec along with access to the StdIn, StdOut, and StdErr channels. The Exec method allows the execution of command line applications only. The Exec method cannot be used to run remote scripts. Do not confuse the Exec method with the Execute method (of the WshRemote object).

Example

The following example demonstrates the basics of the Exec method.

[VBScript]
Dim WshShell, oExec
Set WshShell = CreateObject("WScript.Shell")

Set oExec = WshShell.Exec("calc")

Do While oExec.Status = 0
     WScript.Sleep 100
Loop

WScript.Echo oExec.Status
[JScript]
var WshShell = new ActiveXObject("WScript.Shell");
var oExec = WshShell.Exec("calc");

while (oExec.Status == 0)
{
     WScript.Sleep(100);
}

WScript.Echo(oExec.Status);

See Also

WshScriptExec Object


Execute Method

Starts execution of a remote script object.

object.Execute

Parameters

object
WshRemote Object

Remarks

The Start event of the WshRemote object is fired when the script starts executing. Do not confuse the Execute method with the Exec method (of the WScript object).

Example

The following example demonstrates how the Execute method is used to create a WshRemote object (start an instance of a remote script).

[VBScript]
Dim Controller, RemoteScript
Set Controller = WScript.CreateObject("WSHController")
Set RemoteScript = Controller.CreateScript("remote1.js")
RemoteScript.Execute

Do While RemoteScript.Status <> 2
    WScript.Sleep 100
Loop
[JScript]
var Controller = WScript.CreateObject("WSHController");
var RemoteScript = Controller.CreateScript("remote1.js");
RemoteScript.Execute();

while (RemoteScript.Status != 2) {
    WScript.Sleep(100);
}

See Also

WshController Object | WshRemote Object | Status Property | Error Property | Terminate Method | Start Event | End Event


Exists Method

Indicates whether a specific key value exists in the WshNamed object.

object.Exists(key)

Parameters

object
WshNamed object.
Key
String value indicating an argument of the WshNamed object.

Remarks

The Exists method returns a Boolean value. It returns true if the requested argument was specified on the command line (otherwise, it returns false).

Example

Consider the following information typed at the command line.

myScript.vbs /c:"WSH is a wonderful thing"

You could use these two lines of JScript code to find out whether the following command line switches were used to start the script.

WScript.Echo(WScript.Arguments.Named.Exists("C"));
WScript.Echo(WScript.Arguments.Named.Exists("D"));

See Also

Arguments Property | WshNamed Object | WshUnnamed Object | Count Method | Item Property


ExpandEnvironmentStrings Method

Returns an environment variable's expanded value.

object.ExpandEnvironmentStrings(strString)

Arguments

object
WshShell object.
strString
String value indicating the name of the environment variable you want to expand.

Remarks

The ExpandEnvironmentStrings method expands environment variables defined in the PROCESS environment space only. Environment variable names, which must be enclosed between "%" characters, are not case-sensitive.

Example

The following code expands the Windows Directory environment variable and displays it:

[VBScript]
set WshShell = WScript.CreateObject("WScript.Shell")
WScript.Echo "WinDir is " & WshShell.ExpandEnvironmentStrings("%WinDir%")
[JScript]
var WshShell = WScript.CreateObject("WScript.Shell");
WScript.Echo("WinDir is " + WshShell.ExpandEnvironmentStrings("%WinDir%"));

See Also

WshShell Object


GetObject Method

Retrieves an existing object with the specified ProgID, or creates a new one from a file.

object.GetObject(strPathname [,strProgID], [strPrefix])

Arguments

object
WScript object.
strPathname
The fully qualified path name of the file that contains the object persisted to disk.
strProgID
Optional. The object's program identifier (ProgID).
strPrefix
Optional. Used when you want to sync the object's events. If you supply the strPrefix argument, WSH connects the object's outgoing interface to the script file after creating the object.

Remarks

Use the GetObject method when an instance of the object exists in memory, or when you want to create the object from a file. If no current instance exists and you do not want the object created from a file, use the CreateObject method. The GetObject method can be used with all COM classes, independent of the language used to create the object. If you supply the strPrefix argument, WSH connects the object's outgoing interface to the script file after creating the object. When the object fires an event, WSH calls a subroutine with strPrefix attached to the beginning of the event name. For example, if strPrefix is MYOBJ_ and the object fires an event named OnBegin, WSH calls the MYOBJ_OnBegin subroutine located in the script.

If an object is registered as a single-instance object, only one instance of the object is created (regardless of how many times GetObject is executed). The GetObject method always returns the same instance when called with the zero-length string syntax (""), and it causes an error if you do not supply the path parameter. You cannot use the GetObject method to obtain a reference to a Microsoft Visual Basic class created with Visual Basic 4.0 or earlier.

Example

The following VBScript code starts the application associated with the specified file (strPathname):

Dim MyObject As Object
Set MyObject = GetObject("C:\CAD\SCHEMA.CAD")
MyApp = MyObject.Application

Some applications allow you to activate part of a file. To do this, add an exclamation mark (!) to the end of the file name, and follow it with a string that identifies the part of the file you want to activate. For example, in a drawing application, a drawing stored in a file might have multiple layers. The following code activates a layer within a drawing file called SCHEMA.CAD:

Set LayerObject = GetObject("C:\CAD\SCHEMA.CAD!Layer3")

If you do not specify the object's class (strProgID), COM determines the application to start from the file name. Some files can support more than one class of object. For example, a drawing might support three different types of objects: an application object, a drawing object, and a toolbar object. All may be part of the same file.

In the following VBScript code, the drawing application FIGMENT starts and opens the object DRAWING from within the file SAMPLE.DRW.

Dim MyObject As Object
Set MyObject = GetObject("C:\DRAWINGS\SAMPLE.DRW", "FIGMENT.DRAWING")

See Also

WScript Object | CreateObject Method | DisconnectObject Method


getResource Method

Returns the value of a resource defined with the <resource> element.

getResource(resourceID)

Arguments

resourceID
A string that uniquely identifies the resource information contained within a set of resource tags in a *.WSF script file.

Remarks

The getResource method returns a string. Use the <resource> element to isolate strings or numbers that are within the .wsf file and that you want to reference. This feature makes it easy to maintain a set of strings that are localized into several languages. A WSH script file (*.wsf) can contain several different pieces of resource information — each one with a unique resource identifier.

Example

The following WSH script defines a resource called errNonNumeric. The value of errNonNumeric is displayed if the parameter upperBound is not a number.

<package>
<job id="JS">
<resource id="errNonNumeric">Error: A non-numeric value was entered where a number was expected.</resource>
<script language="JScript">

function getRandomNumber(upperBound)
{
   var realUpperBound = parseInt(upperBound);
   if (!isNaN(realUpperBound))
      return (realUpperBound * Math.random) + 1
   else
   {
      WScript.Echo(getResource("errNonNumeric"));
      WScript.Quit(-1);
   }
}

NewValue = getRandomNumber("Bad Value");

</script>
</job>

<job id="VBS">
<resource id="errNonNumeric">Error: A non-numeric value was entered where a number was expected.</resource>
<script language="VBScript">

Function getRandomNumber(upperBound)
   If IsNumeric(upperBound) Then
      getRandomNumber = CInt(upperBound * Rnd + 1)
   Else
      WScript.Echo getResource("errNonNumeric")
      WScript.Quit -1
   End If
End Function

NewValue = getRandomNumber("Bad Value")

</script>
</job>
</package>

See Also

<resource> Element


LogEvent Method

Adds an event entry to a log file.

object.LogEvent(intType, strMessage [,strTarget])

Arguments

object
WshShell object.
intType
Integer value representing the event type.
strMessage
String value containing the log entry text.
strTarget
Optional. String value indicating the name of the computer system where the event log is stored (the default is the local computer system). Applies to Windows NT/2000 only.

Remarks

The LogEvent method returns a Boolean value (true if the event is logged successfully, otherwise false). In Windows NT/2000, events are logged in the Windows NT Event Log. In Windows 9x/Me, events are logged in WSH.log (located in the Windows directory). There are six event types.

Type | Value
0 | SUCCESS
1 | ERROR
2 | WARNING
4 | INFORMATION
8 | AUDIT_SUCCESS
16 | AUDIT_FAILURE

Example

The following code logs SUCCESS or ERROR depending on the outcome of the function runLoginScript().

[VBScript]
Set WshShell = WScript.CreateObject("WScript.Shell")
rc = runLoginScript()      'Returns true if logon succeeds.

if rc then
   WshShell.LogEvent 0, "Logon Script Completed Successfully"
else
   WshShell.LogEvent 1, "Logon Script failed"
end if
[JScript]
var WshShell = WScript.CreateObject("WScript.Shell");
var rc = runLoginScript();

if (rc)
   WshShell.LogEvent(0, "Logon Script Completed Successfully");
else
   WshShell.LogEvent(1, "Logon Script failed");

See Also

WshShell Object


MapNetworkDrive Method

Adds a shared network drive to your computer system.

object.MapNetworkDrive(strLocalName, strRemoteName, [bUpdateProfile], [strUser], [strPassword])

Arguments

object
WshNetwork object.
strLocalName
String value indicating the name by which the mapped drive will be known locally.
strRemoteName
String value indicating the share's UNC name (\\xxx\yyy).
bUpdateProfile
Optional. Boolean value indicating whether the mapping information is stored in the current user's profile. If bUpdateProfile is supplied and has a value of true, the mapping is stored in the user profile (the default is false).
strUser
Optional. String value indicating the user name. You must supply this argument if you are mapping a network drive using the credentials of someone other than the current user.
strPassword
Optional. String value indicating the user password. You must supply this argument if you are mapping a network drive using the credentials of someone other than the current user.

Remarks

An attempt to map a non-shared network drive results in an error.

Example

The following code maps the logical drive "E" to a network share with the UNC name "\\Server\Public."

[VBScript]
Dim WshNetwork
Set WshNetwork = WScript.CreateObject("WScript.Network")
WshNetwork.MapNetworkDrive "E:", "\\Server\Public"
[JScript]
var WshNetwork = WScript.CreateObject("WScript.Network");
WshNetwork.MapNetworkDrive ("E:", "\\\\Server\\Public");

See Also

WshNetwork Object | EnumNetworkDrives Method | RemoveNetworkDrive Method


Popup Method

Displays text in a pop-up message box.

intButton = object.Popup(strText,[nSecondsToWait],[strTitle],[nType])

Arguments

object
WshShell object.
strText
String value containing the text you want to appear in the pop-up message box.
nSecondsToWait
Optional. Numeric value indicating the maximum length of time (in seconds) you want the pop-up message box displayed.
strTitle
Optional. String value containing the text you want to appear as the title of the pop-up message box.
nType
Optional. Numeric value indicating the type of buttons and icons you want in the pop-up message box. These determine how the message box is used.
IntButton
Integer value indicating the number of the button the user clicked to dismiss the message box. This is the value returned by the Popup method.

Remarks

The Popup method displays a message box regardless of which host executable file is running (WScript.exe or CScript.exe). If nSecondsToWaitis equals zero (the default), the pop-up message box remains visible until closed by the user. If nSecondsToWaitis is greater than zero, the pop-up message box closes after nSecondsToWait seconds. If you do not supply the argument strTitle, the title of the pop-up message box defaults to "Windows Script Host." The meaning of nType is the same as in the Microsoft Win32® application programming interface MessageBox function. The following tables show the values and their meanings. You can combine values in these tables.

Note 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

Example

The following code generates a simple pop-up window.

[VBScript]
Dim WshShell, BtnCode
Set WshShell = WScript.CreateObject("WScript.Shell")

BtnCode = WshShell.Popup("Do you feel alright?", 7, "Answer This Question:", 4 + 32)

Select Case BtnCode
   case 6      WScript.Echo "Glad to hear you feel alright."
   case 7      WScript.Echo "Hope you're feeling better soon."
   case -1     WScript.Echo "Is there anybody out there?"
End Select
[JScript]
var WshShell = WScript.CreateObject("WScript.Shell");
var BtnCode = WshShell.Popup("Do you feel alright?", 7, "Answer This Question:", 4 + 32);
switch(BtnCode) {
   case 6:
      WScript.Echo("Glad to hear you feel alright.");
      break;
   case 7:
      WScript.Echo("Hope you're feeling better soon.");
      break;
   case -1:
      WScript.Echo("Is there anybody out there?");
      break;
}

See Also

WshShell Object | Echo Method


Quit Method

Forces script execution to stop at any time.

object.Quit([intErrorCode])

Arguments

object
WScript object.
intErrorCode
Optional. Integer value returned as the process's exit code. If you do not include the intErrorCode parameter, no value is returned.

Remarks

The Quit method can return an optional error code. If the Quit method is the final instruction in your script (and you have no need to return a non-zero value), you can leave it out, and your script will end normally.

Example

The following JScript code snippet quits execution and returns an error code of 1:

WScript.Quit (1);

// This line of code is never executed.
var i = 0;

See Also

WScript Object


Read Method

Returns a specified number of characters from an input stream.

object.Read(characters)

Arguments

object
StdIn text stream object.
characters
Integer value indicating the number of characters you want to read.

Remarks

The Read method returns a string. The StdIn, StdOut, and StdErr properties and methods work when running the script with the CScript.exe host executable file only. An error is returned when run with WScript.exe. Reading begins at the current position pointer location and moves forward one character at a time.

The Read method does not return until the enter key is pressed. Only the number of characters requested will be returned. Any additional characters will be returned on subsequent calls to the Read, ReadLine, or ReadAll methods.

Example

The following code uses the Read method to get a character from the keyboard and display it on the console.

[VBScript]
Dim Input
Input = ""

Do While Not WScript.StdIn.AtEndOfLine
   Input = Input & WScript.StdIn.Read(1)
Loop
WScript.Echo Input
[JScript]
var input = "";
while (!WScript.StdIn.AtEndOfLine)
{
   input += WScript.StdIn.Read(1);
}
WScript.Echo(input);

See Also

StdIn Property (WScript)


ReadAll Method

Returns all characters from an input stream.

object.ReadAll

Arguments

object
StdIn text stream object.

Remarks

The ReadAll method returns a string. The StdIn, StdOut, and StdErr properties and methods work when running the script with the CScript.exe host executable file only. An error is returned when run with WScript.exe.

Example

The following code demonstrates the use of ReadAll.

[VBScript]
Dim Input
Input = ""

Do While Not WScript.StdIn.AtEndOfStream
   Input = Input & WScript.StdIn.ReadAll
Loop
WScript.Echo Input
[JScript]
var input = "";
while (!WScript.StdIn.AtEndOfStream)
{
   input += WScript.StdIn.ReadAll();
}
WScript.Echo(input);

See Also

StdIn Property | FileSystemObject Object


ReadLine Method

Returns an entire line from an input stream.

object.ReadLine

Arguments

object
StdIn text stream object.

Remarks

The ReadLine method returns a string. The StdIn, StdOut, and StdErr properties and methods work when running the script with the CScript.exe host executable file only. An error is returned when run with WScript.exe. A line is a sequence of characters that ends with a newline character.

Note Although this method extracts the newline character, it does not add it to the string.

Example

The following code demonstrates the use of the ReadLine method.

[VBScript]
Dim StdIn, StdOut
Set StdIn = WScript.StdIn
Set StdOut = WScript.StdOut

Do While Not StdIn.AtEndOfStream
     str = StdIn.ReadLine
     StdOut.WriteLine "Line " & (StdIn.Line - 1) & ": " & str
Loop
[JScript]
var stdin = WScript.StdIn;
var stdout = WScript.StdOut;

while (!stdin.AtEndOfStream)
{
     var str = stdin.ReadLine();
     stdout.WriteLine("Line " + (stdin.Line - 1) + ": " + str);
}

See Also

StdIn Property | FileSystemObject Object


RegDelete Method

Deletes a key or one of its values from the registry.

object.RegDelete(strName)

Arguments

object
WshShell object.
strName
String value indicating the name of the registry key or key value you want to delete.

Remarks

Specify a key-name by ending strName with a final backslash; leave it off to specify a value-name. Fully qualified key-names and value-names are prefixed with a root key. You may use abbreviated versions of root key names with the RegDelete method. The five possible root keys you can use are listed in the following table.

Root key Name | Abbreviation
HKEY_CURRENT_USER | HKCU
HKEY_LOCAL_MACHINE | HKLM
HKEY_CLASSES_ROOT | HKCR
HKEY_USERS | HKEY_USERS
HKEY_CURRENT_CONFIG | HKEY_CURRENT_CONFIG

Example

The following code creates a key and two values, reads them, and deletes them.

[VBScript]
Dim WshShell, bKey
Set WshShell = WScript.CreateObject("WScript.Shell")

WshShell.RegWrite "HKCU\Software\ACME\FortuneTeller\", 1, "REG_BINARY"
WshShell.RegWrite "HKCU\Software\ACME\FortuneTeller\MindReader", "Goocher!", "REG_SZ"

bKey = WshShell.RegRead("HKCU\Software\ACME\FortuneTeller\")
WScript.Echo WshShell.RegRead("HKCU\Software\ACME\FortuneTeller\MindReader")

WshShell.RegDelete "HKCU\Software\ACME\FortuneTeller\MindReader"
WshShell.RegDelete "HKCU\Software\ACME\FortuneTeller\"
WshShell.RegDelete "HKCU\Software\ACME\"
[JScript]
var WshShell = WScript.CreateObject("WScript.Shell");

WshShell.RegWrite ("HKCU\\Software\\ACME\\FortuneTeller\\", 1, "REG_BINARY");
WshShell.RegWrite ("HKCU\\Software\\ACME\\FortuneTeller\\MindReader", "Goocher!", "REG_SZ");

var bKey =    WshShell.RegRead ("HKCU\\Software\\ACME\\FortuneTeller\\");
WScript.Echo (WshShell.RegRead ("HKCU\\Software\\ACME\\FortuneTeller\\MindReader"));

WshShell.RegDelete ("HKCU\\Software\\ACME\\FortuneTeller\\MindReader");
WshShell.RegDelete ("HKCU\\Software\\ACME\\FortuneTeller\\");
WshShell.RegDelete ("HKCU\\Software\\ACME\\");

See Also

WshShell Object | RegRead Method | RegWrite Method


RegRead Method

Returns the value of a key or value-name from the registry.

object.RegRead(strName)

Arguments

object
WshShell object.
strName
String value indicating the key or value-name whose value you want.

Remarks

The RegRead method returns values of the following five types.

Type | Description | 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

Example

The following code creates a key and two values, reads them, and deletes them.

[VBScript]
Dim WshShell, bKey
Set WshShell = WScript.CreateObject("WScript.Shell")

WshShell.RegWrite "HKCU\Software\ACME\FortuneTeller\", 1, "REG_BINARY"
WshShell.RegWrite "HKCU\Software\ACME\FortuneTeller\MindReader", "Goocher!", "REG_SZ"

bKey = WshShell.RegRead("HKCU\Software\ACME\FortuneTeller\")
WScript.Echo WshShell.RegRead("HKCU\Software\ACME\FortuneTeller\MindReader")

WshShell.RegDelete "HKCU\Software\ACME\FortuneTeller\MindReader"
WshShell.RegDelete "HKCU\Software\ACME\FortuneTeller\"
WshShell.RegDelete "HKCU\Software\ACME\"
[JScript]
var WshShell = WScript.CreateObject ("WScript.Shell");

WshShell.RegWrite ("HKCU\\Software\\ACME\\FortuneTeller\\", 1, "REG_BINARY");
WshShell.RegWrite ("HKCU\\Software\\ACME\\FortuneTeller\\MindReader", "Goocher!", "REG_SZ");

var bKey =    WshShell.RegRead ("HKCU\\Software\\ACME\\FortuneTeller\\");
WScript.Echo (WshShell.RegRead ("HKCU\\Software\\ACME\\FortuneTeller\\MindReader"));

WshShell.RegDelete ("HKCU\\Software\\ACME\\FortuneTeller\\MindReader");
WshShell.RegDelete ("HKCU\\Software\\ACME\\FortuneTeller\\");
WshShell.RegDelete ("HKCU\\Software\\ACME\\");

See Also

WshShell Object | RegDelete Method | RegWrite Method


RegWrite Method

Creates a new key, adds another value-name to an existing key (and assigns it a value), or changes the value of an existing value-name.

object.RegWrite(strName, anyValue [,strType])

Arguments

object
WshShell object.
strName
String value indicating the key-name, value-name, or value you want to create, add, or change.
anyValue
The name of the new key you want to create, the name of the value you want to add to an existing key, or the new value you want to assign to an existing value-name.
strType
Optional. String value indicating the value's data type.

Remarks

Specify a key-name by ending strName with a final backslash. Do not include a final backslash to specify a value name. The RegWrite method automatically converts the parameter anyValue to either a string or an integer. The value of strType determines its data type (either a string or an integer). The options for strType are listed in the following table.

Converted to | strType
String | REG_SZ
String | REG_EXPAND_SZ
Integer | REG_DWORD
Integer | REG_BINARY
Note The REG_MULTI_SZ type is not supported for the RegWrite method.
Tip RegWrite will write at most one DWORD to a REG_BINARY value. Larger values are not supported with this method.

Fully qualified key-names and value-names are prefixed with a root key. You may use abbreviated versions of root key names with the RegWrite method. The five root keys are listed in the following table.

Root key Name | Abbreviation
HKEY_CURRENT_USER | HKCU
HKEY_LOCAL_MACHINE | HKLM
HKEY_CLASSES_ROOT | HKCR
HKEY_USERS | HKEY_USERS
HKEY_CURRENT_CONFIG | HKEY_CURRENT_CONFIG

The four possible data types you can specify with strType are listed in the following table.

Type | Description | 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

Example

The following code creates a key and two values, reads them, and deletes them.

[VBScript]
Dim WshShell, bKey
Set WshShell = WScript.CreateObject("WScript.Shell")

WshShell.RegWrite "HKCU\Software\ACME\FortuneTeller\", 1, "REG_BINARY"
WshShell.RegWrite "HKCU\Software\ACME\FortuneTeller\MindReader", "Goocher!", "REG_SZ"

bKey = WshShell.RegRead("HKCU\Software\ACME\FortuneTeller\")
WScript.Echo WshShell.RegRead("HKCU\Software\ACME\FortuneTeller\MindReader")

WshShell.RegDelete "HKCU\Software\ACME\FortuneTeller\MindReader"
WshShell.RegDelete "HKCU\Software\ACME\FortuneTeller\"
WshShell.RegDelete "HKCU\Software\ACME\"
[JScript]
var WshShell = WScript.CreateObject("WScript.Shell");

WshShell.RegWrite ("HKCU\\Software\\ACME\\FortuneTeller\\", 1, "REG_BINARY");
WshShell.RegWrite ("HKCU\\Software\\ACME\\FortuneTeller\\MindReader", "Goocher!", "REG_SZ");

var bKey =    WshShell.RegRead ("HKCU\\Software\\ACME\\FortuneTeller\\");
WScript.Echo (WshShell.RegRead ("HKCU\\Software\\ACME\\FortuneTeller\\MindReader"));

WshShell.RegDelete ("HKCU\\Software\\ACME\\FortuneTeller\\MindReader");
WshShell.RegDelete ("HKCU\\Software\\ACME\\FortuneTeller\\");
WshShell.RegDelete ("HKCU\\Software\\ACME\\");

See Also

WshShell Object | RegDelete Method | RegRead Method


Remove Method

Removes an existing environment variable.

object.Remove(strName)

Arguments

object
WshEnvironment object.
strName
String value indicating the name of the environment variable you want to remove.

Remarks

The Remove method removes environment variables from the following types of environments: PROCESS, USER, SYSTEM, and VOLATILE. Environment variables removed with the Remove method are not removed permanently; they are only removed for the current session.

Example

The following code removes the Process environment variable TestVar.

[VBScript]
Dim WshShell, WshEnv
Set WshShell = WScript.CreateObject("WScript.Shell")
Set WshEnv = WshShell.Environment("PROCESS")
WshEnv("TestVar") = "Windows Script Host"
WScript.Echo WshShell.ExpandEnvironmentStrings("The value of the test variable is: '%TestVar%'")
WshEnv.Remove "TestVar"
WScript.Echo WshShell.ExpandEnvironmentStrings("The value of the test variable is: '%TestVar%'")
[JScript]
var WshShell = WScript.CreateObject("WScript.Shell");
var WshEnv = WshShell.Environment("PROCESS");
WshEnv("TestVar") = "Windows Script Host";
WScript.Echo(WshShell.ExpandEnvironmentStrings("The value of the test variable is: '%TestVar%'"));
WshEnv.Remove("TestVar");
WScript.Echo(WshShell.ExpandEnvironmentStrings("The value of the test variable is: '%TestVar%'"));

See Also

WshEnvironment Object | Environment Property


RemoveNetworkDrive Method

Removes a shared network drive from your computer system.

object.RemoveNetworkDrive(strName, [bForce], [bUpdateProfile])

Arguments

object
WshNetwork object.
strName
String value indicating the name of the mapped drive you want to remove. The strName parameter can be either a local name or a remote name depending on how the drive is mapped.
bForce
Optional. Boolean value indicating whether to force the removal of the mapped drive. If bForce is supplied and its value is true, this method removes the connections whether the resource is used or not.
bUpdateProfile
Optional. String value indicating whether to remove the mapping from the user's profile. If bUpdateProfile is supplied and its value is true, this mapping is removed from the user profile. bUpdateProfile is false by default.

Remarks

If the drive has a mapping between a local name (drive letter) and a remote name (UNC name), then strName must be set to the local name. If the network path does not have a local name (drive letter) mapping, then strName must be set to the remote name.

Example

The following code removes the logical drive "E."

[VBScript]
Dim WshNetwork
Set WshNetwork = WScript.CreateObject("WScript.Network")
WshNetwork.RemoveNetworkDrive "E:"
[JScript]
var WshNetwork = WScript.CreateObject("WScript.Network");
WshNetwork.RemoveNetworkDrive ("E:");

See Also

WshNetwork Object | EnumNetworkDrives Method | MapNetworkDrive Method


RemovePrinterConnection Method

Removes a shared network printer connection from your computer system.

object.RemovePrinterConnection(strName, [bForce], [bUpdateProfile])

Arguments

object
WshNetwork object.
strName
String value indicating the name that identifies the printer. It can be a UNC name (in the form \\xxx\yyy) or a local name (such as LPT1).
bForce
Optional. Boolean value indicating whether to force the removal of the mapped printer. If set to true (the default is false), the printer connection is removed whether or not a user is connected.
bUpdateProfile
Optional. Boolean value. If set to true (the default is false), the change is saved in the user's profile.

Remarks

The RemovePrinterConnection method removes both Windows and MS-DOS based printer connections. If the printer was connected using the method AddPrinterConnection, strName must be the printer's local name. If the printer was connected using the AddWindowsPrinterConnection method or was added manually (using the Add Printer wizard), then strName must be the printer's UNC name.

Example

The following code disconnects a network printer.

[VBScript]
Set WshNetwork = WScript.CreateObject("WScript.Network")
PrinterPath = "\\printserv\DefaultPrinter"
WshNetwork.RemovePrinterConnection PrinterPath, true, true
[JScript]
var WshNetwork = WScript.CreateObject("WScript.Network");
var PrinterPath = "\\\\PRN-CORP1\\B41-4523-A";
WshNetwork.RemovePrinterConnection(PrinterPath, true, true);

See Also

WshNetwork Object | AddPrinterConnection Method | AddWindowsPrinterConnection Method | EnumPrinterConnections Method | SetDefaultPrinter Method


Run Method

Runs a program in a new process.

object.Run(strCommand, [intWindowStyle], [bWaitOnReturn])

Arguments

object
WshShell object.
strCommand
String value indicating the command line you want to run. You must include any parameters you want to pass to the executable file.
intWindowStyle
Optional. Integer value indicating the appearance of the program's window. Note that not all programs make use of this information.
bWaitOnReturn
Optional. Boolean value indicating whether the script should wait for the program to finish executing before continuing to the next statement in your script. If set to true, script execution halts until the program finishes, and Run returns any error code returned by the program. If set to false (the default), the Run method returns immediately after starting the program, automatically returning 0 (not to be interpreted as an error code).

Remarks

The Run method returns an integer. The Run method starts a program running in a new Windows process. You can have your script wait for the program to finish execution before continuing. This allows you to run scripts and programs synchronously. Environment variables within the argument strCommand are automatically expanded. If a file type has been properly registered to a particular program, calling run on a file of that type executes the program. For example, if Word is installed on your computer system, calling Run on a *.doc file starts Word and loads the document. The following table lists the available settings for intWindowStyle.

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

Example 1

The following VBScript code opens a copy of the currently running script with Notepad.

Set WshShell = WScript.CreateObject("WScript.Shell")
WshShell.Run "%windir%\notepad " & WScript.ScriptFullName

The following VBScript code does the same thing, except it specifies the window type, waits for Notepad to be shut down by the user, and saves the error code returned from Notepad when it is shut down.

Set WshShell = WScript.CreateObject("WScript.Shell")
Return = WshShell.Run("notepad " & WScript.ScriptFullName, 1, true)

Example 2

The following VBScript code opens a command window, changes to the path to C:\ , and executes the DIR command.

Dim oShell
Set oShell = WScript.CreateObject ("WSCript.shell")
oShell.run "cmd /K CD C:\ & Dir"
Set oShell = Nothing

See Also

WshShell Object


Save Method

Saves a shortcut object to disk.

object.Save

Arguments

object
WshShortcut or WshUrlShortcut object.

Remarks

After using the CreateShortcut method to create a shortcut object and set the shortcut object's properties, the Save method must be used to save the shortcut object to disk. The Save method uses the information in the shortcut object's FullName property to determine where to save the shortcut object on a disk. You can only create shortcuts to system objects. This includes files, directories, and drives (but does not include printer links or scheduled tasks).

Example

The following example demonstrates the use of a single .wsf file for two jobs in different script languages (VBScript and JScript). Each job creates a shortcut to the script being run and a URLshortcut to www.microsoft.com.

<package>
   <job id="vbs">
      <script language="VBScript">
         set WshShell = WScript.CreateObject("WScript.Shell")
         strDesktop = WshShell.SpecialFolders("Desktop")
         set oShellLink = WshShell.CreateShortcut(strDesktop & "\Shortcut Script.lnk")
         oShellLink.TargetPath = WScript.ScriptFullName
         oShellLink.WindowStyle = 1
         oShellLink.Hotkey = "CTRL+SHIFT+F"
         oShellLink.IconLocation = "notepad.exe, 0"
         oShellLink.Description = "Shortcut Script"
         oShellLink.WorkingDirectory = strDesktop
         oShellLink.Save
         set oUrlLink = WshShell.CreateShortcut(strDesktop & "\Microsoft Web Site.url")
         oUrlLink.TargetPath = "http://www.microsoft.com"
         oUrlLink.Save
      </script>
   </job>

   <job id="js">
      <script language="JScript">
         var WshShell = WScript.CreateObject("WScript.Shell");
         strDesktop = WshShell.SpecialFolders("Desktop");
         var oShellLink = WshShell.CreateShortcut(strDesktop + "\\Shortcut Script.lnk");
         oShellLink.TargetPath = WScript.ScriptFullName;
         oShellLink.WindowStyle = 1;
         oShellLink.Hotkey = "CTRL+SHIFT+F";
         oShellLink.IconLocation = "notepad.exe, 0";
         oShellLink.Description = "Shortcut Script";
         oShellLink.WorkingDirectory = strDesktop;
         oShellLink.Save();
         var oUrlLink = WshShell.CreateShortcut(strDesktop + "\\Microsoft Web Site.url");
         oUrlLink.TargetPath = "http://www.microsoft.com";
         oUrlLink.Save();
      </script>
   </job>
</package>

See Also

Running Your Scripts | WshShortcut Object | WshUrlShortcut Object | FullName Property | TargetPath Property | WindowStyle Property | Hotkey Property | IconLocation Property | Description Property | WorkingDirectory Property


SendKeys Method

Sends one or more keystrokes to the active window (as if typed on the keyboard).

object.SendKeys(string)

Arguments

object
WshShell object.
string
String value indicating the keystroke(s) you want to send.

Remarks

Use the SendKeys method to send keystrokes to applications that have no automation interface. Most keyboard characters are represented by a single keystroke. Some keyboard characters are made up of combinations of keystrokes (CTRL+SHIFT+HOME, for example). To send a single keyboard character, send the character itself as the string argument. For example, to send the letter x, send the string argument "x".

Note 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 When used this way, these special characters are not enclosed within a set of braces.

To specify that a combination of SHIFT, CTRL, and ALT should be held down while several other keys are pressed, create a compound string argument with the modified keystrokes enclosed in parentheses. For example, to send the keystroke combination that specifies that the SHIFT key is held down while:

  • e and c are pressed, send the string argument "+(ec)".
  • e is pressed, followed by a lone c (with no SHIFT), send the string argument "+ec".

You can use the SendKeys method to send a pattern of keystrokes that consists of a single keystroke pressed several times in a row. To do this, create a compound string argument that specifies the keystroke you want to repeat, followed by the number of times you want it repeated. You do this using a compound string argument of the form {keystroke number}. For example, to send the letter "x" ten times, you would send the string argument "{x 10}". Be sure to include a space between keystroke and number.

Note The only keystroke pattern you can send is the kind that is comprised of a single keystroke pressed several times. For example, you can send "x" ten times, but you cannot do the same for "Ctrl+x".
Note You cannot send the PRINT SCREEN key {PRTSC} to an application.

Example

The following example demonstrates the use of a single .wsf file for two jobs in different script languages (VBScript and JScript). Each job runs the Windows calculator and sends it keystrokes to execute a simple calculation.

<package>
   <job id="vbs">
      <script language="VBScript">
         set WshShell = WScript.CreateObject("WScript.Shell")
         WshShell.Run "calc"
         WScript.Sleep 100
         WshShell.AppActivate "Calculator"
         WScript.Sleep 100
         WshShell.SendKeys "1{+}"
         WScript.Sleep 500
         WshShell.SendKeys "2"
         WScript.Sleep 500
         WshShell.SendKeys "~"
         WScript.Sleep 500
         WshShell.SendKeys "*3"
         WScript.Sleep 500
         WshShell.SendKeys "~"
         WScript.Sleep 2500
      </script>
   </job>

   <job id="js">
      <script language="JScript">
         var WshShell = WScript.CreateObject("WScript.Shell");
         WshShell.Run("calc");
         WScript.Sleep(100);
         WshShell.AppActivate("Calculator");
         WScript.Sleep(100);
         WshShell.SendKeys ("1{+}");
         WScript.Sleep(500);
         WshShell.SendKeys("2");
         WScript.Sleep(500);
         WshShell.SendKeys("~");
         WScript.Sleep(500);
         WshShell.SendKeys("*3");
         WScript.Sleep(500);
         WshShell.SendKeys("~");
         WScript.Sleep(2500);
      </script>
   </job>
</package>

See Also

WshShell Object | Run Method


SetDefaultPrinter Method

Assigns a remote printer the role Default Printer.

object.SetDefaultPrinter(strPrinterName)

Arguments

object
WshNetwork object.
strPrinterName
String value indicating the remote printer's UNC name.

Remarks

The SetDefaultPrinter method fails when using a DOS-based printer connection. You cannot use the SetDefaultPrinter method to determine the name of the current default printer.

Example

The following code uses the AddWindowsPrinterConnection method to connect a network printer and set it as the default printer.

[VBScript]
Set WshNetwork = WScript.CreateObject("WScript.Network")
PrinterPath = "\\research\library1"
WshNetwork.AddWindowsPrinterConnection PrinterPath
WshNetwork.SetDefaultPrinter PrinterPath
[JScript]
var WshNetwork = WScript.CreateObject("WScript.Network");
var PrinterPath = "\\\\research\\library1";
WshNetwork.AddWindowsPrinterConnection(PrinterPath);
WshNetwork.SetDefaultPrinter(PrinterPath);

See Also

WshNetwork Object | AddPrinterConnection Method | AddWindowsPrinterConnection Method | EnumPrinterConnections Method | RemovePrinterConnection Method


ShowUsage Method

Makes a script self-documenting by displaying information about how it should be used.

object.ShowUsage

Parameters

object
WScript Object.

Remarks

When you run the ShowUsage method, a help screen (referred to as the usage) appears and displays details about the script's command line options. This information comes from the runtime section of the *.WSF file. Everything written between the <runtime> and </runtime> tags is pieced together to produce what is called a "usage statement." The usage statement tells the user how to use the script.

Note The usage can also be displayed using the /? switch.

Example

The following example demonstrates how to set up usage information in a *.WSF script file.

<job>
    <runtime>
        <description>This script reboots a server</description>
        <named
            name = "Server"
            helpstring = "Server to run the script on"
            type = "string"
            required = "true"
        />
        <example>Example: reboot.wsf /server:scripting</example>
    </runtime>
<script language="VBScript">

If WScript.Arguments.Count <> 1 Then
   WScript.Arguments.ShowUsage
   WScript.Quit
End If

</script>
</job>

The JScript code for the equivalent script block would be:

if (WScript.Arguments.length != 1)
{
   WScript.Arguments.ShowUsage();
   WScript.Quit();
}

Calling the ShowUsage method from this script results in the following output:

This script reboots a server
Usage: reboot.wsf /server:value

Options:

server : Server to run the script onExample:
reboot.wsf /server:scripting

See Also

WScript Object


Sign Method

Signs a script stored in a string.

Object.Sign (FileExtension, Text, Certificate, Store)

Arguments

object
Scripting.Signer
FileExtension
A string designating the script extension type (.vbs, .js, or .wsf). This provides a mechanism by which the operating system can determine the type of script file being verified.
Text
A string containing the script to be signed.
Certificate
A string designating the author's certificate name.
Store
Optional. A string designating the name of the certificate store. Typically certificates that contain private keys — i.e., certificates you can use for code signing — are in a certificate store called "my". The default value is "my".

Remarks

The Sign method is used to digitally sign a script stored in a string. In order to create a digital signature, the caller must have a valid certificate.

Example

Dim Signer, UnsignedText, SignedText
Set Signer = CreateObject("Scripting.Signer")
UnsignedText = _
     "Dim X " & vbCrLf & _
     "X = 123" & vbCrLf & _
     "WScript.Echo X" & vbCrLf
SignedText = Signer.Sign(".VBS", UnsignedText, "Your Certificate Name Here")

See Also

Scripting.Signer Object | SignFile Method | Verify Method | VerifyFileMethod | Signing a Script


SignFile Method

Signs a script using a digital signature.

Object.SignFile (FileName, Certificate, Store)

Arguments

object
Scripting.Signer
FileName
A string containing the name of the script file.
Certificate
A string designating the author's certificate name.
Store
An optional string designating the name of the certificate store. Typically certificates that contain private keys — i.e., certificates you can use for code signing — are in a certificate store called "my". The default value is "my".

Remarks

In order to sign a digital signature, the author must have a valid certificate.

Example

The following example demonstrates not only signature checking but also the command-line argument.

<job>
<runtime>
<named name="file" helpstring="the file to sign" required="true" type="string"/>
<named name="cert" helpstring="the name of the signing certificate" required="true" type="string"/>
<named name="store" helpstring="the name of the certificate store" required="false" type="string"/>
</runtime>
<script language="vbscript">
Dim Signer, File, Cert, Store
If Not (WScript.Arguments.Named.Exists("cert") And WScript.Arguments.Named.Exists("file")) Then
     WScript.Arguments.ShowUsage
     WScript.Quit
End If
Set Signer = CreateObject("Scripting.Signer")
File  = WScript.Arguments.Named("file")
Cert  = WScript.Arguments.Named("cert")
If WScript.Arguments.Named.Exists("store") Then
     Store = WScript.Arguments.Named("store")
Else
     Store = "my"
End If
Signer.SignFile File, Cert, Store
</script>
</job>

See Also

Scripting.Signer Object | Sign Method | Verify Method | VerifyFile Method | Signing a Script


Skip Method

Skips a specified number of characters when reading from an input text stream.

object.Skip(characters)

Arguments

object
StdIn text stream object.
characters
Integer value indicating the number of characters you want to skip.

Remarks

The StdIn, StdOut, and StdErr properties and methods work when running the script with the CScript.exe host executable file only. An "Invalid Handle" error is returned when run with WScript.exe. The position pointer moves forward by the number of characters (bytes) specified in the argument characters. You cannot use the Skip method to skip backwards through a file (negative character values are not supported). The Skip method is limited to the open for reading mode only (you cannot skip a specified number of characters when writing to an output stream).

Example

The following code uses the Skip method to jump over the first character in a text stream, read a line from the keyboard, and write it to the StdOut text stream.

[VBScript]
WScript.StdIn.Skip 1
Input = WScript.StdIn.ReadLine
WScript.StdOut.Write Input
[JScript]
WScript.StdIn.Skip(1);
Input = WScript.StdIn.ReadLine();
WScript.StdOut.Write(Input);

See Also

StdIn Property


SkipLine Method

Skips the next line when reading from an input text stream.

object.SkipLine

Arguments

object
StdIn text stream object.

Remarks

A line is a sequence of characters that ends with a newline character. The StdIn, StdOut, and StdErr properties and methods work when running the script with the CScript.exe host executable file only. An "Invalid Handle" error is returned when run with WScript.exe. The position pointer moves forward to the point just past the next newline character. You cannot use the SkipLine method to skip backwards through a file. The SkipLine method is limited to the open for reading mode only (you cannot skip lines when writing to an output stream).

Example

The following code demonstrates the SkipLine method.

[VBScript]
Dim StdIn, StdOut, Str1, Str2

Set StdIn = WScript.StdIn
Set StdOut = WScript.StdOut

Str1 = ""
Str2 = ""

For i = 0 to 4
   StdIn.SkipLine
Next

i = 0
Do While Not StdIn.AtEndOfStream
     If i >= 2 Then
          StdOut.WriteLine Str1
     End If
     i = i + 1
     Str1 = Str2
     Str2 = StdIn.ReadLine
Loop
[JScript]
var 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();
}

See Also

StdIn Property


Sleep Method

Suspends script execution for a specified length of time, then continues execution.

object.Sleep(intTime)

Arguments

object
WScript object.
intTime
Integer value indicating the interval (in milliseconds) you want the script process to be inactive.

Remarks

The thread running the script is suspended, releasing its CPU utilization. Execution resumes as soon as the interval expires. Using the Sleep method can be useful when you are running asynchronous operations, multiple processes, or if your script includes code triggered by an event. To be triggered by an event, a script must be continually active (a script that has finished executing will certainly not detect an event). Events handled by the script will still be executed during a sleep.

Note Passing the Sleep method a 0 or –1 does not cause the script to suspend indefinitely.

Example

The following example demonstrates the use of a single .wsf file for two jobs in different script languages (VBScript and JScript). The functionality of both jobs is the same — each runs the Windows calculator and sends it keystrokes to execute a simple calculation.

<package>
   <job id="vbs">
      <script language="VBScript">
         set WshShell = WScript.CreateObject("WScript.Shell")
         WshShell.Run "calc"
         WScript.Sleep 100
         WshShell.AppActivate "Calculator"
         WScript.Sleep 100
         WshShell.SendKeys "1{+}"
         WScript.Sleep 500
         WshShell.SendKeys "2"
         WScript.Sleep 500
         WshShell.SendKeys "~"
         WScript.Sleep 500
         WshShell.SendKeys "*3"
         WScript.Sleep 500
         WshShell.SendKeys "~"
         WScript.Sleep 2500
      </script>
   </job>

   <job id="js">
      <script language="JScript">
         var WshShell = WScript.CreateObject("WScript.Shell");
         WshShell.Run("calc");
         WScript.Sleep(100);
         WshShell.AppActivate("Calculator");
         WScript.Sleep(100);
         WshShell.SendKeys("1{+}");
         WScript.Sleep(500);
         WshShell.SendKeys("2");
         WScript.Sleep(500);
         WshShell.SendKeys("~");
         WScript.Sleep(500);
         WshShell.SendKeys("*3");
         WScript.Sleep(500);
         WshShell.SendKeys("~");
         WScript.Sleep(2500);
      </script>
   </job>
</package>

See Also

Running Your Scripts | WScript Object


Terminate Method (WshScriptExec)

Instructs the script engine to end the process started by the Exec method.

object.Terminate

Arguments

object
WshScriptExec object.

Remarks

The Terminate method does not return a value. Use the Terminate method only as a last resort since some applications do not clean up properly. As a general rule, let the process run its course and end on its own. The Terminate method attempts to end a process using the WM_CLOSE message. If that does not work, it kills the process immediately without going through the normal shutdown procedure.

Example

The following JScript example demonstrates how to use the Terminate method to stop a running script.

var aScript = WScript.Exec("%comspec% /c myScript.js");
aScript.Terminate();

See Also

WshScriptExec Object


Verify Method

Verifies a digital signature retrieved as a string.

object.Verify (FileExtension, Text, ShowUI)

Arguments

object
Scripting.Signer
FileExtension
A string designating the script extension type (.vbs, .js, or .wsf). This provides a mechanism by which the operating system can determine the type of script file being verified.
Text
The text to verify.
ShowUI
A Boolean value. If the ShowUI argument is false, then the Scripting.Signer object determines whether a trusted source provided the signature without prompting the user. If it is true then the Scripting.Signer object may create dialog boxes to prompt the user if there is not sufficient information to determine trust.
Note On some 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.

Remarks

The Verify method is used to verify a digital signed script stored in a string.

Example

In this example the Verify method determines whether the script in the UnsignedText variable is trusted. (In this example there is no digital signature, so the Scripting.Signer object asks the user whether to extend trust.)

Dim Signer, UnsignedText, Trusted
Set Signer = CreateObject("Scripting.Signer")
UnsignedText = _
     "Dim X " & vbCrLf & _
     "X = 123" & vbCrLf & _
     "WScript.Echo X" & vbCrLf
Trusted = Signer.Verify(".VBS", UnsignedText, True)

See Also

Scripting.Signer Object | VerifyFile Method | Sign Method | SignFile Method | Verifying a Script


VerifyFile Method

Verifies the digital signature encapsulated in a script.

Object.VerifyFile (FileName, ShowUI)

Arguments

object
Scripting.Signer
FileName
A string containing the name of the script file.
ShowUI
A Boolean value. If the ShowUI argument is false, then the Scripting.Signer object determines whether a trusted source provided the signature without prompting the user. If it is true then the Scripting.Signer object may create dialog boxes to prompt the user if there is not sufficient information to determine trust.
Note On some operating systems, the 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.

Example

The following example demonstrates signature checking using the command-line argument processing features.

<job>
<runtime>
<named name="file" helpstring="the file to sign" required="true" type="string"/>
<named name="UI" helpstring="produce user interface for untrusted scripts" required="false"/>
</runtime>
<script language="vbscript">
Dim Signer, File, UI, OK
If Not WScript.Arguments.Named.Exists("file") Then
     WScript.Arguments.ShowUsage
     WScript.Quit
End If
Set Signer = CreateObject("Scripting.Signer")
File = WScript.Arguments.Named("file")
UI   = WScript.Arguments.Named.Exists("ui")
OK = Signer.VerifyFile(File, UI)
If OK Then
     WScript.Echo File & " is trusted."
Else
     WScript.Echo File & " is NOT trusted."
End If
</script>
</job>

See Also

Scripting.Signer Object | Verify Method | Sign Method | SignFile Method | Verifying a Script


Write Method

Sends a string to an output stream.

object.Write(strText)

Arguments

object
StdOut or StdErr text stream objects.
strText
String value indicating the text you want to write to the stream.

Remarks

The StdIn, StdOut, and StdErr properties and methods work when running the script with the CScript.exe host executable file only. An "Invalid Handle" error is returned when run with WScript.exe. The position pointer moves to the point just beyond the last character in strText.

Example

The following code demonstrates the use of the Write method.

[VBScript]
Dim strInput
strInput = WScript.StdIn.ReadAll
WScript.StdOut.Write strInput
[JScript]
var strInput = WScript.StdIn.ReadAll();
WScript.StdOut.Write(strInput);

See Also

StdErr Property | StdOut Property


WriteBlankLines Method

Sends a specified number of blank lines (newline characters) to an output stream.

object.WriteBlankLines(intLines)

Arguments

object
StdOut or StdErr text stream objects.
intLines
Integer value indicating the number of blank lines you want to write to the stream.

Remarks

Calling the WriteLine method without supplying the strText argument is equivalent to calling WriteBlankLines(1). The StdIn, StdOut, and StdErr properties and methods work when running the script with the CScript.exe host executable file only. An "Invalid Handle" error is returned when run with WScript.exe.

Example

The following code demonstrates the WriteBlankLines method.

[VBScript]
Dim StdIn, StdOut
Set StdIn = WScript.StdIn
Set StdOut = WScript.StdOut

Do While Not StdIn.AtEndOfStream
     str = StdIn.ReadLine
     StdOut.Write "Line " & (StdIn.Line - 1) & ": " & str
     StdOut.WriteBlankLines 1
Loop
[JScript]
var stdin = WScript.StdIn;
var stdout = WScript.StdOut;

while (!stdin.AtEndOfStream)
{
     var str = stdin.ReadLine();
     stdout.Write("Line " + (stdin.Line - 1) + ": " + str);
     stdout.WriteBlankLines(1);
}

See Also

StdErr Property | StdOut Property | WriteLine Method


WriteLine Method

Sends a string with a newline character to an output stream.

object.WriteLine([strText])

Arguments

object
StdOut or StdErr text stream objects.
strText
Optional. String value indicating the text you want to write to the stream. If omitted, a newline character is written to the output stream.

Remarks

The WriteLine method always appends a newline character to the string. Calling the WriteLine method without supplying the argument strText is equivalent to calling WriteBlankLines(1). The StdIn, StdOut, and StdErr properties and methods work when running the script with the CScript.exe host executable file only. An "Invalid Handle" error is returned when run with WScript.exe. A line is a sequence of characters that ends with a newline character.

Example

The following code demonstrates the WriteLine method.

[VBScript]
Dim StdIn, StdOut
Set StdIn = WScript.StdIn
Set StdOut = WScript.StdOut

Do While Not StdIn.AtEndOfStream
     str = StdIn.ReadLine
     StdOut.WriteLine "Line " & (StdIn.Line - 1) & ": " & str
Loop
[JScript]
var stdin = WScript.StdIn;
var stdout = WScript.StdOut;

while (!stdin.AtEndOfStream)
{
     var str = stdin.ReadLine();
     stdout.WriteLine("Line " + (stdin.Line - 1) + ": " + str);
}

See Also

StdErr Property | StdOut Property | WriteBlankLines Method


Events

In this Section

End Event
Signals the script engine to end execution of a remote script object.
Error Event
Signals the script engine to end execution of a remote script object when the remote script terminates prematurely due to an error.
Start Event
Signals the script engine to begin execution of a remote script object.

Related Sections

WSH Language
List of elements that make up WSH Reference.
WSH Basics
Learn the basics of WSH.


End Event

Event that is fired when the remote script completes.

Object_end

Parameters

object
WshRemote object.

Remarks

The End event is fired when the remote script object has finished executing. This can be when the remote script object has terminated normally, timed out, or terminated due to an error.

Example

var WshController = new ActiveXObject("WSHController");
var RemoteProc = WshController.CreateScript("foo.wsf", "remotemachine");
WScript.ConnectObject(RemoteProc, "RemoteProc_");
var Done = false;
RemoteProc.Execute();
while (!Done)
   WScript.Sleep(100);

function RemoteProc_End()
{
   WScript.Echo("The process has ended");
   Done = true;
}

function RemoteProc_Error()
{
   WScript.Echo("An error has occurred: " + RemoteProc.Error.Description);
   Done = true;
}

function RemoteProc_Start()
{
   WScript.Echo("The process has started");
}

See Also

WshController Object | WshRemote Object | Status Property | Error Property | Execute Method | Terminate Method | Start Event | Error Event


Error Event

Event that is fired when an error occurs in the remote script.

Object_Error

Parameters

object
WshRemote object.

Remarks

The remote script object fires the Error event when the remote script terminates prematurely. The Error property contains the WshRemoteError object (which holds information about the error that caused the remote script to terminate prematurely).

Example

var WshController = new ActiveXObject("WSHController");
var RemoteProc = WshController.CreateScript("foo.wsf", "remotemachine");
WScript.ConnectObject(RemoteProc, "RemoteProc_");
var Done = false;
RemoteProc.Execute();
while (!Done)
   WScript.Sleep(100);

function RemoteProc_End()
{
   WScript.Echo("The process has ended");
   Done = true;
}

function RemoteProc_Error()
{
   WScript.Echo("An error has occurred: " + RemoteProc.Error.Description);
   Done = true;
}

function RemoteProc_Start()
{
   WScript.Echo("The process has started");
}

See Also

WshController Object | WshRemote Object | WshRemoteError Object | Status Property | Error Property | Execute Method | Terminate Method | Start Event | End Event


Start Event

Event that is fired when the remote script begins executing.

Object_Start

Parameters

object
WshRemote object.

Remarks

The Start event is fired when the Execute method is called.

Example

var WshController = new ActiveXObject("WSHController");
var RemoteProc = WshController.CreateScript("foo.wsf", "remotemachine");
WScript.ConnectObject(RemoteProc, "RemoteProc_");
var Done = false;
RemoteProc.Execute();
while (!Done)
   WScript.Sleep(100);

function RemoteProc_End()
{
   WScript.Echo("The process has ended");
   Done = true;
}

function RemoteProc_Error()
{
   WScript.Echo("An error has occurred: " + RemoteProc.Error.Description);
   Done = true;
}

function RemoteProc_Start()
{
   WScript.Echo("The process has started");
}

See Also

WshController Object | WshRemote Object | Status Property | Error Property | Execute Method | Terminate Method | End Event | Error Event


Error Messages

In this Section

Here is a list of the errors messages you may encounter when running scripts in the Windows Script Host 5.6 environment.

//E option requires name of script engine.

//H option requires host name.

//T option requires timeout value.

A duplicate name for a named or unnamed element was encountered.

An attempt at saving your settings via the //S option failed.

Can't change default script host <host name>.

Can't find script engine <engine name> for script.

Can't find script file <script file name>.

Can't read script from stdin.

Can't save settings.

Command line option mismatch.

Could not connect object <object name>.

Could not locate automation class name <automation class name>.

Execution of the Windows Script Host failed.

Host name for //H option must be "cscript" or "wscript".

Initialization of the Windows Script Host failed.

Invalid attempt to call Exec without a command.

Invalid pathname.

Invalid root in registry key <name> for reading.

Invalid syntax in URL<name>.

Invalid timeout value for //T option.

Loading script <script name> failed.

Loading your settings failed.

Missing job name.

Protocol handler for <name> not found.

Remote script object can only be executed once.

Script execution time was exceeded on script <script name>. <script name> execution was terminated.

Script setting file <settings filename>is invalid.

The shortcut pathname must end with .lnk or .url.

There is no file extension in <file name>.

There is no printer called <name>.

There is no script engine for file extension <file extension>.

There is no script file specified.

Unable to execute - arguments list too long.

Unable to open registry key <name> for reading.

Unable to remove environment variable <name>.

Unable to remove registry key <name>.

Unable to save shortcut <name>.

Unable to set shortcut target to <name>.

Unable to write to wsh.log. Please check with your administrator.

Unable to wait for process.

Unable to execute remote script.

Unable to find job <job identifier>.

Unicode is not supported on this platform.

Unknown option <option designation> specified.

Windows Script Host access is disabled on this machine. Contact your administrator for details.

Related Sections

WSH Reference
List of elements that make up WSH Reference.
WSH Basics
Learn the basics of WSH.


//H option requires host name.

You failed to specify the default host name.

To correct this error

  • Specify the default host name when using the //H option.

See Also

Host name for //H option must be "cscript" or "wscript".


//T option requires timeout value.

You failed to input a timeout value for the //T option.

To correct this error

  • Input a timeout value using the //T option.

See Also

Invalid timeout value for //T option | Script execution time was exceeded on script <script name>. <script name> execution was terminated.


A duplicate name for a named or unnamed element was encountered.

You are attempting to name a <named> or <unnamed> element with a name that is already in use by another <named> or <unnamed> element. The "name" attribute of the <named> and <unnamed> elements must be unique throughout the <job>.

To correct this error

  • Choose a different name for the <named> or <unnamed> element.

See Also

WshArguments Object | WshNamed Object | WshUnnamed Object | <named> Element


An attempt at saving your settings via the //S option failed.

Again this is usually a systems permissions issue.

To correct this error

  • Consult your Administrator about potential network or security problems.

See Also

Can't change default script host <host name> | Setting Script Properties


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 The maximum command-line length that your system allows determines the number of files you can drag onto a script.

See Also

  • Drag and Drop Support | Command line option mismatch


Unable to write to wsh.log. Please check with your administrator.

On Windows 95/98 and Windows Millennium Editions, you are calling the method LogEvent(), but it fails because the wsh.log file is locked.

To correct this error

  • Unlock the wsh.log file if you the proper permissions or consult your system administrator.

See Also

LogEvent Method


Can't change default script host <host name>.

This is usually a systems permission issue and the likely cause is that the system registry has been locked by an Administrator.

To correct this error

  • Consult your Administrator about potential network or security problems.

See Also

An attempt at saving your settings via the //s option failed


Can't find script engine <engine name> for script.

Usually, this means that the script engine is not installed.

To correct this error

  • Consult your Administrator about potential network or security problems.
  • Make sure that the particular script engine is installed or that you are specifying the correct script engine.
  • Check your spelling.


Can't find script file <script file name>.

You have given an incorrect path or the script file is not there.

To correct this error

  • Check the path given and correct it.
  • Make sure that the file is actually there

See Also

Invalid pathname.


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.

Unable to save the control file (*.wsh) for this script.

To correct this error

  • Verify that you are not trying to save over a read-only file, a file that is open in another application, or a file locked by an administrator.
  • Consult your Administrator about potential network or security problems.

See Also

Setting Script Properties


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

It is likely that you are trying to sync events to an object or are sourcing events to an object that cannot accept those object events.

For example, IE can't be connected to events once it is created. You have to connect any object events to IE at the time it is created as the object as a part of the creation process.

To correct this error

  • Create the object and connect its object events to it during the creation process.

See Also

<object> Element | WScript Object


Could not locate automation class name <automation class name>.

Either you were unsuccessful in creating an automation class or the automation class was not properly installed.

To correct this error

  • Make sure the automation class that you created is installed.
  • Consult your Administrator about potential network or security problems.


//E option requires name of script engine.

You have not designated the script engine using the //E option.

To correct this error

  • Be sure to designate the script engine when using the //E option.

See Also

There is no script engine for file extension <file extension>.


Unable to remove environment variable <name>.

You are calling the method Environment.Remove() on an unrecognized environment variable.

This error generally occurs when using the Remove method. If the environment variable does not exist or is misspelled, the system is not able to remove it.

To correct this error

  • Check the names of the current environment variables and make sure they exist and are spelled correctly.

See Also

Remove Method | WshEnvironment Object


Execution of the Windows Script Host failed.

Usually, this is a systems permissions issue.

To correct this error

  • Consult your Administrator about potentially serious network or security problems.

See Also

Loading script <script name> failed


Host name for //H option must be "cscript" or "wscript".

You specified something other than "cscript" or "wscript" as your host name when you used the //H option.

To correct this error

  • Specify either "cscript" or "wscript" as the host name when using the //H option.

See Also

H option requires host name.


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.

You called the WshShell.Exec() method but did not supply a command to execute.

To correct this error

  • strCommand is a required argument. It is a string that represents the command line used to run the script.

See Also

Exec Method


Invalid pathname.

You have given an incorrect path.

To correct this error

  • Check the path given and correct it.

See Also

Can't find script file <script file name>.


The shortcut pathname must end with .lnk or .url

When you named your shortcut, either you did not give it a file extension or you gave it an extension other than *.lnk, nor *.url.

When using the CreateShortcut method, the file extension is incorrect or missing.

To correct this error

  • Check that the file extension for the shortcut ends with .lnk for a Windows shortcut or with .url for an Internet shortcut.

See Also

WshShortcut Object | WshUrlShortcut Object


Invalid timeout value for //T option.

The timeout value that you entered using the //T option is invalid. You must designate a non-negative integer for //T option.

To correct this error

  • Input an appropriate timeout value using the //T option. Specify a non-negative integer for //T.

See Also

//T option requires timeout value | Script execution time was exceeded on script <script name>. <script name> execution was terminated.


Loading script <script name> failed.

Usually, this is a systems permissions issue and you have been denied read access to the file in question.

To correct this error

  • Consult your Administrator about potentially serious network or security problems.

See Also

Loading your settings failed


Loading your settings failed.

Usually, this is a systems permissions issue.

To correct this error

  • Consult your Administrator about potentially serious network or security problems.

See Also

Loading script <script name> failed


Missing job name.

You have failed to specify the job name.

To correct this error

  • Specify the job name.

See Also

Unable to find job <job identifier>


There is no printer called <name>.

The SetDefaultPrinter method accepts only the names of currently installed printers. This error generally occurs if you specify the printer port instead of the name of the printer, or if you use the name of a printer that is not currently installed.

To correct this error

  • Check the names of the currently installed printers and make sure the specified printer is installed.
  • Check the spelling of the printer path for typing errors.
  • Make sure the networked printer is online.

See Also

SetDefaultPrinter Method | EnumPrinterConnections Method | AddWindowsPrinterConnection Method


Protocol handler for <name> not found.

This error generally occurs when the protocol handler for the URL shortcut target is misspelled. The two most common protocol handlers are HTTP and FTP.

To correct this error

  • Check the spelling of the protocol handler.

See Also

WshUrlShortcut Object


Invalid root in registry key <name> for reading.

You are calling the methods RegRead() or RegWrite() on an unrecognized root registry key.

This error generally occurs when using the RegRead or RegWrite methods with an invalid registry key.

To correct this error

  • Check the Windows registry and make sure the registry key exists and is spelled correctly.

See Also

RegRead Method | RegWrite Method | RegDelete Method


Unable to open registry key <name> for reading.

You are calling the method RegRead() on an unrecognized registry key.

This error generally occurs when using the RegRead method with an invalid registry key.

To correct this error

  • Check the Windows registry and make sure the registry key exists and is spelled correctly.

See Also

RegRead Method


Unable to remove registry key <name>.

You are calling the method RegDelete() on an unrecognized registry key.

This error generally occurs when using the RegDelete method on an invalid registry key.

To correct this error

  • Check the Windows registry and make sure the registry key exists and is spelled correctly.

See Also

RegDelete Method | RegRead Method | RegWrite Method


Remote script object can only be executed once.

You are attempting to rerun a remote script object.

To correct this error

  • Create another remote script object and run it instead.

See Also

WshRemote Object


Script execution time was exceeded on script <script name>. <script name> execution was terminated.

The script in question could not be executed within the user-defined execution time (//T).

To correct this error

  • Troubleshoot your script to determine why it is not executing within the time parameter (//T) that you set. Redesign your script so that it executes faster and/or change the time parameter (//T).

See Also

T option requires timeout value | Invalid timeout value for T option


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.


Invalid syntax in URL<name>.

This error generally occurs when the text that makes up the URL target contains incorrect syntax.

To correct this error

  • Check the spelling of the URL target for typing errors.

See Also

WshUrlShortcut Object


Unable to save shortcut <name>.

This error generally occurs when the name of the shortcut already exists or is a read-only file.

To correct this error

  • Change the read-only attribute to read/write.
  • Rename your shortcut to something unique.
  • Change the name of the existing shortcut.

See Also

WshShortcut Object | WshUrlShortcut Object


Unable to set shortcut target to <name>.

This error generally occurs when the protocol handler for the URL shortcut target is invalid or improperly registered. The two most common protocol handlers are HTTP and FTP.

To correct this error

  • Use a valid protocol handler.
  • Check the spelling of the protocol handler being used.
  • Contact your system administrator to make sure the protocol handler is properly installed.
  • Consult your Administrator about potential network or security problems.

See Also

WshUrlShortcut Object


There is no file extension in <file name>.

In order to determine what script engine is apt, the program usually needs the appropriate file extension.

To correct this error

  • Be sure include a correct file extension that is appropriate to the scripting language you wish to use, along with the file name.


There is no script engine for file extension <file extension>.

This file extension is not mapped to a script engine.

To correct this error

  • Check your file extension and also the spelling of your scripting language designation.
  • Use //E to designate a script engine.

See Also

E option requires name of script engine.


There is no script file specified.

You have failed to specify a script file.

To correct this error

  • Specify the appropriate script file.

See Also

Unknown option <option designation> specified


Unable to execute remote script.

The script failed to initialize.

To correct this error

  • Consult your Administrator about potential network or security problems.

See Also

WshRemote Object


Unable to find job <job identifier>.

You made a reference to an unrecognized job ID in your Windows Script file (*.wsf file).

To correct this error

  • Check the spelling of the job ID for typing errors.

See Also

Using Windows Script Files | <job> Element


Unable to wait for process.

This error generally occurs when the script is hung up waiting for a process that does not return a value, for example, waiting for the result from running a shortcut link.

To correct this error

  • Execute the program directly instead of using a shortcut.
  • Check the shortcut link to be sure it is still current.

See Also

Run Method


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.

You have specified an option that is invalid for Windows script host.

To correct this error

  • Use the Windows script host option appropriate to the script language you are using or specify another supported script language.
  • Also check your spelling.

See Also

There is no script file specified


Windows Script Host access is disabled on this machine. Contact your administrator for details.

Usually, this is a systems permissions issue.

To correct this error

  • Consult your Administrator about potential network or security problems.

See Also

Execution of the Windows Script Host failed


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®. 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. The areas discussed in this tutorial are shown in the following list.

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


Script Components Overview

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®. The following topics provide an overview of script component technology, and explain 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 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.

Note For more information about ActiveX Scripting interfaces, see the Microsoft Scripting Technologies Web site at www.microsoft.com.

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.

See Also

How Script Components Work | Creating Script Components


How Script Components Work

Windows® Script Component technology consists of three pieces:

  • The script component run-time (Scrobj.dll), which helps dispatch COM requests to your scripts. In COM terms, Scrobj.dll functions as the inproc server for script components.
  • Interface handlers, which 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 (an .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

Introducing Script Components | Creating Script Components


Creating Script Components

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.

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

A basic script component file contains these elements:

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

<?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 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:
    <implements type="ASP" id="iASP">

    The exact elements that appear inside an <implements> element depend on what interface you are implementing.

    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

Checking For Errors in Script Component Files | Creating a Script Component Type Library | Creating Registration Information | Exposing Events | Exposing Methods | Exposing Properties | 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

The Windows® Script Component package includes a Script Component Wizard that automates the process of creating a script component (.wsc) file. The wizard performs the following functions:

  • 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 You can download and install the Script Component Wizard from the Microsoft Scripting Technologies Web site on www.microsoft.com.

The wizard creates a skeleton script component with information you provide, and writes it out as an .wsc file. Edit the .wsc file and add your script to create the script component's functionality.

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

Script Component File Contents | Creating Registration Information | Creating Script Components | Script Component Files and XML Conformance


Creating Registration Information

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). By reading the registration information, applications can find and load the COM component.

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:
    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 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:
    <registration
description="My Test Component"
progid="Component.TestScript"
version="1"
classid="{2154c700-9253-11d1-a3ac-0aa0044eb5f}"/>
    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 A CDATA section is required to make the script in the <script> element opaque. For details, see Script Component Files and XML Conformance.
    <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:
    <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

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

Methods are implemented as functions or subroutines in your Windows® Script Component file.

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 A CDATA section is required to make the script in the <script> element opaque. For details, see Script Component Files and XML Conformance.
    <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 followoing ways in Visual Basic:

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:
    <public>
   <method name="factorial" dispid="0"/>
</public>
    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

Exposing Events | Exposing Properties | Script Component File Contents


Exposing Properties

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 A CDATA section is required to make the script in the <script> element opaque. For details, see Script Component Files and XML Conformance.
    <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>

Exposing a property using functions is similar to exposing a method.

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 A CDATA section is required to make the script in the <script> element opaque. For details, see Script Component Files and XML Conformance.
    <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:

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:
    <property name="sname" dispid="0"/>
    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

Exposing Events | Exposing Methods | Script Component File Contents | Script Component Files and XML Conformance


Exposing Events

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

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

<script language="VBScript">
<![CDATA[
Sub put_lowercaseName(newLCName)
   name = newLCName
   fireEvent("namechanged")
End Sub
]]>
</script>

See Also

Exposing Custom Events in Behavior Script Components | Exposing Methods | Exposing Properties | Handling Script Component Events in the Host Application | Script Component File Contents


Creating a Script Component Type Library

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 For information about using a type library in the host application, refer to the application's documentation.

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.GenerateTypeLib 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.GenerateTypeLib object by using syntax such as the following:
    set oTL = CreateObject("Scriptlet.GenerateTypeLib")
  2. Set the following properties of the Component.GenerateTypeLib 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 GenerateTypeLib 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:
    {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 GenerateTypeLib 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 A CDATA section is required to make the script in the <script> element opaque. For details, see Script Component Files and XML Conformance.
<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.GenerateTypeLib")
         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:
    rundll32.exe path\scrobj.dll,GenerateTypeLib 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):

rundll32.exe c:\winnt\system32\scrobj.dll,GenerateTypeLib
   -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 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

Script Component File Contents | Creating Registration Information | Checking For Errors in Script Component Files | Script Component Files and XML Conformance


Referencing Other Components

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

<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:
    <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 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.
    <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 getResourcefunction, as shown in the following example.
    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.
    <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

Script Component File Contents | Referencing Another Script Component in the Same Package


Referencing Another Script Component in the Same Package

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.

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

    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 A CDATA section is required to make the script in the <script> element opaque. For details, see Script Component Files and XML Conformance.
    <?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:

' 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 A CDATA section is required to make the script in the <script> element opaque. For details, see Script Component Files and XML Conformance.
<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

Script Component File Contents | <package> | <component>


Checking For Errors in Script Component Files

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:

<?component error="true" debug="true"?>
Tip Turn error reporting off before deploying your script component to a production environment.

See Also

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

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 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:
    <?XML version="1.0" ?>
    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

Script Component File Contents | Using The Script Component Wizard | Checking For Errors in Script Component Files


Using Script Components

After you have created a Windows® Script Component, you can use it in your applications. 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

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

  • In Windows Explorer, right-click the script component (.wsc) file, and then choose Register.

    –or–

  • Use the new version of Regsvr32.exe that ships with the script component package, and use this command:
    regsvr32 URL/component_name.wsc

    For example, to register a script component called MyComponent.wsc, use syntax such as this:

    regsvr32 file:\\myserver\MyComponent.wsc

    -or–

  • 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:
    regsvr32 scrobj.dll /n /i:URL/component_name.ext

    For example, to register a script component called MyComponent.wsc, use syntax such as this:

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

Creating Registration Information | Script Component File Contents | Using a Script Component in an Application


Using a Script Component in an Application

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.

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.

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

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.

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:

Set oComponent = CreateObject("Component.MyComponent")
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:
Dim WithEvents scMyComponent As MyComponent
Private Sub Command1_Click()
Set scMyComponent=CreateObject("MyComponent")
End Sub
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:

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

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:

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:

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

Set newS = CreateObject("Component.MyComponent", "myserver")
Note There can be a slight delay when you first instantiate a remote script component while DCOM establishes communication between the computers.

See Also

Creating Registration Information | Creating Script Components | How Script Components Work | Introducing Script Components | Registering a Script Component


Handling Script Component Events in the Host Application

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.

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.

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

An example in Visual Basic might look like this:

Dim WithEvents Scriptlet1 as MyScriptlet
Set Scriptlet1 = CreateObject("MyScriptlet")
Sub Scriptlet1_namechanged
   MsgBox("Value of name property changed")
End Sub

See Also

Exposing Events


Implementing ASP Script Components

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.

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 A CDATA section is required to make the script in the <script> element opaque. For details, see Script Component Files and XML Conformance.
<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:

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

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.

See Also

The "DHTML Behaviors" and "Using DHTML Behaviors" topics on the Site Builder Network (SBN) Workshop on the Microsoft Web site provide general


Creating a Behavior Script Component

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 A CDATA section is required to make the script in the <script> element opaque. For details, see Script Component Files and XML Conformance.
<?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 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 A CDATA section is required to make the script in the <script> element opaque. For details, see Script Component Files and XML Conformance.
<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.
    <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

Exposing Properties and Methods in Behavior Script Components | Exposing Custom Events in Behavior Script Components | Behavior Handler Reference


Exposing Properties and Methods in Behavior Script Components

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 A CDATA section is required to make the script in the <script> element opaque. For details, see Script Component Files and XML Conformance.
<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

Exposing Custom Events in Behavior Script Components


Exposing Custom Events in Behavior Script Components

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:

<public>
   <event name="onResultChange" />
</public>

The event can then be fired by calling the fireEvent method in script:

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

oEvent = createEventObject();
oEvent.myprop = "a new value"
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 A CDATA section is required to make the script in the <script> element opaque. For details, see Script Component Files and XML Conformance.
<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.

<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

Exposing Properties and Methods in Behavior Script Components


Script Component Reference

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

XML Elements

  • <?component?>
  • <?XML ?>
  • <comment>
  • <component>
  • <event>
  • <implements>
  • <method>
  • <object>
  • <package>
  • <property>
  • <public>
  • <reference>
  • <registration>
  • <resource>
  • <script>

Methods and Functions

  • createComponent
  • fireEvent
  • getResource


<?component?>

Specifies attributes for error handling.

<?component error="flag" debug="flag" ?>

Values

flag
A Boolean value: "true" or "false," 1 or 0, or "yes" or "no." The default value for all attributes is false.

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.

Example

<?component error="true" debug="true" ?>

See Also

Checking For Errors in Script Component Files | Script Component File Contents


<?XML ?>

Indicates that the file should be parsed as XML.

<?XML version="version" standalone="DTDflag" encoding="encname" ?>

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.

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.

Example

<?XML version="1.0" standalone="yes" encoding="UTF-16" ?>

See Also

Script Component Files and XML Conformance


<comment> Element

Marks text in a script component file that should be ignored.

<comment>
   text here
</comment>

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.

Example

The following script component fragment shows a <comment> element inside a <public> element.

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

See Also

Script Component File Contents


createComponent Function

Returns a reference to another script component in the same package (.wsc file).

value = createComponent(componentID)

Values

componentID
The unique identifier for the script component to create an instance of.

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.

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 A CDATA section is required to make the script in the <script> element opaque. For details, see Script Component Files and XML Conformance.
<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:

set o1 = CreateObject("component.FrontEnd")
Set o2 = o1.math()
msgbox(o2.add(4,5))

See Also

Referencing Another Script Component in the Same Package


<event> Element

Declares the name of a custom event that can be fired from within the script component.

<event name="name" dispid="dispid"/>

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.

Remarks

To fire an event, use the fireEventmethod.

Example

The following script component fragment defines two events (namechanged and querydone) and shows how to fire one of them (namechanged).

Note A CDATA section is required to make the script in the <script> element opaque. For details, see Script Component Files and XML Conformance.
<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>

See Also

<method> Element | <property> Element | Exposing Events | Exposing Methods | Exposing Properties | fireEvent Method


fireEvent Method

Sends notification of a custom event from the script component to the host application.

fireEvent(eventName[,...])

Values

eventName
The name of the event as defined in the <event> element.

Remarks

You can only fire events if they have been declared in the <public> element.

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.

Example

The following shows a fragment of a script component that defines the event namechanged and shows how to fire it.

Note A CDATA section is required to make the script in the <script> element opaque. For details, see Script Component Files and XML Conformance.
<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>

See Also

<event> Element | Exposing Events | fireEvent (Behavior)


getResource Function

Gets the value of a resource defined with the <resource> element.

value = getResource(resourceID)

Values

resourceID
A unique identifier for the resource within the script component.

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.

Example

The following script component fragment defines a resource (called errNonNumeric) and how to use it in script.

Note A CDATA section is required to make the script in the <script> element opaque. For details, see Script Component Files and XML Conformance.
<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>

See Also

Referencing Other Components


<implements> Element

Specifies additional COM interface handlers for a script component.

<implements type="COMHandlerName" [id="internalName"] [default=fAssumed]>
   handler-specific information here
</implements>

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

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.

Example

<implements type="Behavior">
   <event name="onResultChange" />
</implements>

See Also

How Script Components Work | Script Component File Contents


<method> Element

Declares a method.

<method name="methodName" internalName="functionName" dispid=dispID>
   [<parameter name="parameterID"/>]
</method>

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

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

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 A CDATA section is required to make the script in the <script> element opaque. For details, see Script Component Files and XML Conformance.
<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>

See Also

<event> Element | <property> Element | Exposing Events | Exposing Methods | Exposing Properties


<object> Element

Defines objects that can be referenced by script.

<object id="objID" [classid="clsid:GUID" | progid="progID"] events="true|false"/>

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:
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:
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.
events
(Optional) An attribute that allows you to hook events from the object. By default, events 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.

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.

Example

The following script component fragment includes an <object> element to create an object reference to the ADODB.Connection object.

Note A CDATA section is required to make the script in the <script> element opaque. For details, see Script Component Files and XML Conformance.
<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=myserver;uid=sa;database=pubs"
   cnn.Open
   If cnn.State = 1 Then
      cnnState = "open"
      cnn.Close
   Else
      cnnState = "closed"
   End If
End Function
]]>
</script>

See Also

Script Component File Contents


<package> Element

Encloses multiple script component definitions.

<package>
   one or more script components here
</package>

Remarks

The <package> element is optional when a .wsc file contains only one script component definition.

Example

<package>
<component id="MyScriptlet">
   (script component information here)
</component>

<component id="MyOtherScriptlet">
   (script component information here)
</component>
</package>

See Also

Script Component File Contents


<property> Element

Declares a property.

<property name="propertyName" [internalName="propertyVariable"] />

–or–

<property name="propertyName">
   <get [internalName="getFunctionName"] />
   <put [internalName="putFunctionName"] />
</property>

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).
Tip In XML, you can implement elements that have no content (such as the <property> element) by closing the element with />.

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:

<property name="myproperty" get put/>

which is functionally equivalent to:

<property name="myproperty">
   <get/>
   <put/>
</property>

If you wanted to explicitly name those accessors differently from the default, you can use the following syntax:

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

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 wih the functions readDOB and writeDOB. Finally, the mstatus property is implemented with the default functions get_mstatus and put_mstatus.

Note A CDATA section is required to make the script in the <script> element opaque. For details, see Script Component Files and XML Conformance.
<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>

See Also

<event> Element | <method> Element | Exposing Events | Exposing Methods | Exposing Properties


<public> Element

Encloses the script component's property, method, and event declarations.

<public>
   <property name="pname"/>
   <method name="mname"/>
   <event name="ename"/>
</public>

See Also

<event> Element | <method> Element | <property> Element | Exposing Events | Exposing Methods | Exposing Properties


<reference> Element

Includes a reference to an external type library.

<reference [object="progID" |guid="typelibGUID"] [version="version"]>

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.

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.

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 A CDATA section is required to make the script in the <script> element opaque. For details, see Script Component Files and XML Conformance.
<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=myserver;uid=sa;database=pubs"
   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>

See Also

Referencing Other Components


<registration> Element

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>

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 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 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, see Creating Remote Instances of Script Components in the topic "Using a Script Component in an Application."

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:

regsvr32 file:\\myserver\MyComponent.wsc
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 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.

Example

The following shows a typical <registration> element that includes both a prog ID and a class ID.

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

<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 A CDATA section is required to make the script in the <script> element opaque. For details, see Script Component Files and XML Conformance.
<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>

See Also

Creating Registration Information | Registering a Script Component


<resource> Element

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>

Values

ResourceID
A unique identifier for the resource within the script component.

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.

Example

The following script component fragment defines a resource (called errNonNumeric) and demonstrates how to use it in script.

Note A CDATA section is required to make the script in the <script> element opaque. For details, see Script Component Files and XML Conformance.
<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>

See Also

Referencing Other Components


<script> Element

Defines the script component's behavior.

<script language="language">
   script here
</script>

Values

language
The name of the scripting language used in the script component file, such as Microsoft® Visual Basic® Scripting Edition (VBScript) or JScript.

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 Do not include a CDATA section unless you also include the <?XML ?> declaration.

Example

<?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>

See Also

Script Component File Contents


<component> Element

Encloses an entire Windows Script Component definition.

<component id=componentid>
   script component information here
</component>

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.

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.

Example

The following shows a simple but complete script component that includes a factorial method and a name property.

Note A CDATA section is required to make the script in the <script> element opaque. For details, see Script Component Files and XML Conformance.
<?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>

See Also

Script Component File Contents


Behavior Handler Reference

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

Binds an event from the containing document to a function in the script component.

<attach event="eventName" handler="functionName" [for="elementName"]/>

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.

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 A CDATA section is required to make the script in the <script> element opaque. For details, see Script Component Files and XML Conformance.
<?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>

See Also

Creating a Behavior Script Component


attachNotification Method

Binds a function in the script component to a notification message sent from the host.

behavior.attachNotification (fpNotify)

Values

behavior
The ID of the <implements> element used to implement the Behavior interface.
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.

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 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 A CDATA section is required to make the script in the <script> element opaque. For details, see Script Component Files and XML Conformance.
<implements type="Behavior"/>
<script language="JScript">
<![CDATA[
   style.color = "green";
   style.letterSpacing = 5;
]]>
</script>

Example

The example below demonstrates how a function could be set up to trap notifications and process them as appropriate.

Note A CDATA section is required to make the script in the <script> element opaque. For details, see Script Component Files and XML Conformance.
<?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>

See Also

<event> Element


createEventObject Method

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

Values

behavior
The ID of the <implements> element used to implement the Behavior interface.
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.

Remarks

The same event object cannot be reused in multiple fireEvent calls.

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 A CDATA section is required to make the script in the <script> element opaque. For details, see Script Component Files and XML Conformance.
<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.

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

See Also

Exposing Custom Events in Behavior Script Components


element Property

Returns the element to which the behavior is being applied.

[oElement = ] Behavior.element

Values

oElement
Element to which the behavior is being applied.
Behavior
The ID of the <implements> element used to implement the Behavior interface.
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.

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.

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 A CDATA section is required to make the script in the <script> element opaque. For details, seeScript Component Files and XML Conformance.
<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>

See Also

For general information about applying behaviors to DHTML elements, see the "Using DHTML Behaviors" topic on the Site Builder Network (SBN)


<layout> Element

Defines HTML text inserted into the containing document.

<layout>
   <HTMLtag>Inserted text</HTMLtag>
</layout>

Values

HTMLTag
The name of HTML tag for which the element's text is a replacement.

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.

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.

<?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>

See Also

For general information about applying behaviors to DHTML elements, see the "Using DHTML Behaviors" topic on the Site Builder Network (SBN).


fireEvent method

Fires a custom event.

Behavior.fireEvent(sEvent[, oEvent])

Values

Behavior
The ID of the <implements> element used to implement the Behavior interface.
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.

Remarks

The same event object cannot be reused in multiple calls to the fireEvent method.

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 A CDATA section is required to make the script in the <script> element opaque. For details, see Script Component Files and XML Conformance.
<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.

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

See Also

Exposing Custom Events in Behavior Script Components | fireEvent


Microsoft Windows Script Interfaces-Introduction

Microsoft® Windows® Script Interfaces
Microsoft Windows Script Interfaces-Introduction 		Language Reference
Next

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
  • IDispatchEx
  • IProvideMultipleClassInfo
  • Active Script Debugging Interfaces
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.


Windows Script Hosts

Microsoft® Windows® Script Interfaces
Windows Script Hosts 		Language Reference
Previous
Next

When implementing Microsoft® Windows® Script host, you can safely assume that a scripting engine will only call 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.

Also, 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.


Windows Script Engines

Microsoft® Windows® Script Interfaces
Windows Script Engines 		Language Reference
Previous
Next

To implement an 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: 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.

  • Registry Standard
  • Script Engine States
  • Scripting Engine Threading

See the Script Interface Reference for more information.

Registry Standard

An Windows Script engine can identify itself using component categories. Windows Script currently defines two component categories.

Category | Decription
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, an Windows Script engine can be in one of several states.

State | Descriptioon
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 an 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.


Windows Script Interface Reference

Microsoft® Windows® Script Interfaces
Windows Script Interface Reference 		Language Reference
Previous
Next

The following interfaces are specific to Microsoft® Windows® Script hosts:

  • IActiveScriptSite
  • IActiveScriptSiteWindow

The following interfaces are specific to Windows Script Engines.

  • IActiveScript
  • IActiveScriptError
  • IActiveScriptParse

The following enumerations are specific to Windows Script Engines.

  • SCRIPTSTATE
  • SCRIPTTHREADSTATE


IActiveScript

Microsoft® Windows® Script Interfaces
IActiveScript 		Language Reference
Previous
Next

The IActiveScript interface provides the methods necessary to initialize the scripting engine. The scripting engine must implement the IActiveScript interface.

Methods in Vtable Order

Method | Description
SetScriptSite | Informs the scripting engine of the IActiveScriptSite site provided by the host.
GetScriptSite | Retrieves the site object associated with the Windows Script engine.
SetScriptState | Places the scripting engine into the specified state.
GetScriptState | Retrieves the current state of the scripting engine.
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.
AddNamedItem | Adds the name of a root-level item to the scripting engine's name space.
AddTypeLib | Adds a type library to the name space for the script.
GetScriptDispatch | Retrieves the IDispatch interface for the running script.
GetCurrentScriptThreadID | Retrieves a scripting-engine-defined identifier for the currently executing thread.
GetScriptThreadID | Retrieves a scripting-engine-defined identifier for the thread associated with the given Microsoft Win32® thread.
GetScriptThreadState | Retrieves the current state of a script thread.
InterruptScriptThread | Interrupts the execution of a running script thread.
Clone | Clones the current scripting engine (minus any current execution state), returning a loaded scripting engine that has no site in the current thread.


IActiveScript::AddNamedItem

Microsoft® Windows® Script Interfaces
IActiveScript::AddNamedItem 		Language Reference
Previous
Next

HRESULT AddNamedItem(
    LPCOLESTR pstrName,  // address of item name
    DWORD dwFlags        // item flags
);

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.

  • 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).

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.


IActiveScript::AddTypeLib

Microsoft® Windows® Script Interfaces
IActiveScript::AddTypeLib 		Language Reference
Previous
Next

HRESULT AddTypeLib(
    REFGUID guidTypeLib,  // CLSID of type library
    DWORD dwMaj,          // major version number
    DWORD dwMin,          // minor version number
    DWORD dwFlags         // option flags
);

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.

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

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.


IActiveScript::Clone

Microsoft® Windows® Script Interfaces
IActiveScript::Clone 		Language Reference
Previous
Next

HRESULT Clone(
    IActiveScript **ppscript  // receives pointer to IActiveScript
);

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.

  • 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).

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.

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.


IActiveScript::Close

Microsoft® Windows® Script Interfaces
IActiveScript::Close 		Language Reference
Previous
Next

HRESULT Close(void);

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.

  • Returns one of the following values:

    Return 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 hasn't changed yet. When the state changes, the site will be called back on the IActiveScriptSite::OnStateChange method.
    S_FALSE | The method succeeded, but the script was already closed.


IActiveScript::GetCurrentScriptThreadID

Microsoft® Windows® Script Interfaces
IActiveScript::GetCurrentScriptThreadID 		Language Reference
Previous
Next

HRESULT GetCurrentScriptThreadID(
    SCRIPTTHREADID *pstidThread  // receives scripting thread identifier
);

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.

  • Returns S_OK if successful, or E_POINTER if an invalid pointer was specified.
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.

This method can be called from non-base threads without resulting in a non-base callout to host objects or to the IActiveScriptSite interface.


IActiveScript::GetScriptDispatch

Microsoft® Windows® Script Interfaces
IActiveScript::GetScriptDispatch 		Language Reference
Previous
Next

HRESULT GetScriptDispatch(
    LPCOLESTR pstrItemName  // address of item name
    IDispatch **ppdisp      // receives IDispatch pointer
);

Retrieves the IDispatch interface for the methods and properties associated with the currently running script.

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

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.

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.


IActiveScript::GetScriptSite

Microsoft® Windows® Script Interfaces
IActiveScript::GetScriptSite 		Language Reference
Previous
Next

HRESULT GetScriptSite(
    REFIID iid,           // interface identifier
    void **ppvSiteObject  // address of host site interface
);

Retrieves the site object associated with the Windows Script engine.

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

iid
[in] Identifier of the requested interface.
ppvSiteObject
[out] Address of the location that receives the interface pointer to the host's site object.


IActiveScript::GetScriptState

Microsoft® Windows® Script Interfaces
IActiveScript::GetScriptState 		Language Reference
Previous
Next

HRESULT GetScriptState(
    SCRIPTSTATE *pss  // address of structure for state information
);

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.

  • Returns S_OK if successful, or E_POINTER if an invalid pointer was specified.
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.


IActiveScript::GetScriptThreadID

Microsoft® Windows® Script Interfaces
IActiveScript::GetScriptThreadID 		Language Reference
Previous
Next

HRESULT GetScriptThreadID(
    DWORD dwWin32ThreadID,       // Win32 thread identifier
    SCRIPTTHREADID *pstidThread  // receives scripting thread identifier
);

Retrieves a scripting-engine-defined identifier for the thread associated with the given Win32 thread.

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

dwWin32ThreadID
[in] Thread identifier of a running Win32 thread in the current process. Use the 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.

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 IActiveScriptSite interface.


IActiveScript::GetScriptThreadState

Microsoft® Windows® Script Interfaces
IActiveScript::GetScriptThreadState 		Language Reference
Previous
Next

HRESULT GetScriptThreadState(
    SCRIPTTHREADID stidThread,    // identifier of script thread
    SCRIPTTHREADSTATE *pstsState  // receives state flag
);

Retrieves the current state of a script thread.

  • 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).

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.

This method can be called from non-base threads without resulting in a non-base callout to host objects or to the IActiveScriptSite interface.


IActiveScript::InterruptScriptThread

Microsoft® Windows® Script Interfaces
IActiveScript::InterruptScriptThread 		Language Reference
Previous
Next

HRESULT InterruptScriptThread(
    SCRIPTTHREADID   stidThread,  // identifier of thread
    const EXCEPINFO *pexcepinfo,  // receives error information
    DWORD dwFlags
);

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 (in an infinite loop, for example). It can be called from non-base threads without resulting in a non-base callout to host objects or to the IActiveScriptSite method.

  • 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).

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, by calling the IActiveScript::SetScriptState method with the SCRIPTSTATE_DISCONNECTED or SCRIPTSTATE_INITIALIZED flag set, the next scripted event causes script code to run again.
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 that receives error information associated with the error condition.
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.


IActiveScript::SetScriptSite

Microsoft® Windows® Script Interfaces
IActiveScript::SetScriptSite 		Language Reference
Previous
Next

HRESULT SetScriptSite(
    IActiveScriptSite *pScriptSite  // address of host script site
);

Informs the scripting engine of the IActiveScriptSite interface site provided by the host. This method must be called before any other IActiveScript interface methods can be used.

  • 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).

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.


IActiveScript::SetScriptState

Microsoft® Windows® Script Interfaces
IActiveScript::SetScriptState 		Language Reference
Previous
Next

HRESULT SetScriptState(
    SCRIPTSTATE ss  // identifier of new state
);

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.

  • 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.
ss
[in] Sets the scripting engine to the given state. Can be one of the values defined in the SCRIPTSTATE enumeration.

For more information about scripting engine states, see Script Engine States.

See also IActiveScript::Clone, IActiveScript::GetScriptDispatch, IActiveScript::InterruptScriptThread, IActiveScriptParse::ParseScriptText, IActiveScriptSite::GetItemInfo


IActiveScriptError

Microsoft® Windows® Script Interfaces
IActiveScriptError 		Language Reference
Previous
Next

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
GetExceptionInfo | Retrieves information about an error.
GetSourcePosition | Retrieves the location in the source code where an error occurred.
GetSourceLineText | Retrieves the line in the source file where an error occurred.


IActiveScriptError::GetExceptionInfo

Microsoft® Windows® Script Interfaces
IActiveScriptError::GetExceptionInfo 		Language Reference
Previous
Next

HRESULT GetExceptionInfo(
    EXCEPINFO *pexcepinfo  // structure for exception information
);

Retrieves information about an error that occurred while the scripting engine was running a script.

  • Returns S_OK if successful, or E_FAIL if an error occurred.
pexcepinfo
[out] Address of an EXCEPINFO structure that receives error information.


IActiveScriptError::GetSourceLineText

Microsoft® Windows® Script Interfaces
IActiveScriptError::GetSourceLineText 		Language Reference
Previous
Next

HRESULT GetSourceLineText(
    BSTR *pbstrSourceLine  // address of buffer for source line
);

Retrieves the line in the source file where an error occurred while a scripting engine was running a script.

  • Returns S_OK if successful, or E_FAIL if the line in the source file was not retrieved.
pbstrSourceLine
[out] Address of a buffer that receives the line of source code in which the error occurred.


IActiveScriptError::GetSourcePosition

Microsoft® Windows® Script Interfaces
IActiveScriptError::GetSourcePosition 		Language Reference
Previous
Next

HRESULT GetSourcePosition(
    DWORD *pdwSourceContext,  // context cookie
    ULONG *pulLineNumber,     // line number of error
    LONG *pichCharPosition    // character position of error
);

Retrieves the location in the source code where an error occurred while the scripting engine was running a script.

  • Returns S_OK if successful, or E_FAIL if the location was not retrieved.
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.


IActiveScriptParse

Microsoft® Windows® Script Interfaces
IActiveScriptParse 		Language Reference
Previous
Next

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
InitNew | Initializes the scripting engine.
AddScriptlet | Adds a code scriptlet to the script.
ParseScriptText | Parses the given code scriptlet, adding declarations into the name space and evaluating code as appropriate.


IActiveScriptParse::AddScriptlet

Microsoft® Windows® Script Interfaces
IActiveScriptParse::AddScriptlet 		Language Reference
Previous
Next

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 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
);

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'").

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

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


IActiveScriptParse::InitNew

Microsoft® Windows® Script Interfaces
IActiveScriptParse::InitNew 		Language Reference
Previous
Next

HRESULT InitNew(void);

Initializes the scripting engine.

  • Returns S_OK if successful, or E_FAIL if an error occurred during initialization.

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.


IActiveScriptParse::ParseScriptText

Microsoft® Windows® Script Interfaces
IActiveScriptParse::ParseScriptText 		Language Reference
Previous
Next

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 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
);

Parses the given code scriptlet, adding declarations into the name space and evaluating code as appropriate.

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

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.

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 Script Engine States.


IActiveScriptSite

Microsoft® Windows® Script Interfaces
IActiveScriptSite 		Language Reference
Previous
Next

The host must create a site for the Windows Script engine by implementing the IActiveScriptSite interface. 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
GetLCID | Retrieves the locale identifier that the host uses for displaying user-interface elements.
GetItemInfo | Obtains information about an item that was added to an engine through a call to the IActiveScript::AddNamedItem method.
GetDocVersionString | Retrieves a host-defined string that uniquely identifies the current document version from the host's point of view.
OnScriptTerminate | Called when the script has completed execution.
OnStateChange | Informs the host that the scripting engine has changed states.
OnScriptError | Informs the host that an execution error occurred while the engine was running the script.
OnEnterScript | Informs the host that the scripting engine has begun executing the script code.
OnLeaveScript | Informs the host that the scripting engine has returned from executing script code.


IActiveScriptSite::GetDocVersionString

Microsoft® Windows® Script Interfaces
IActiveScriptSite::GetDocVersionString 		Language Reference
Previous
Next

HRESULT GetDocVersionString(
    BSTR *pbstrVersionString  // address of document version string
);

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.

  • Returns S_OK if successful, or E_NOTIMPL if this method is not supported.
pstrVersionString
[out] Address of the host-defined document version string.

If E_NOTIMPL is returned, the scripting engine should assume that the script is in sync with the document.


IActiveScriptSite::GetItemInfo

Microsoft® Windows® Script Interfaces
IActiveScriptSite::GetItemInfo 		Language Reference
Previous
Next

HRESULT IActiveScriptSite::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
);

Allows the scripting engine to obtain information about an item added with the IActiveScript::AddNamedItem method.

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

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 | Return the IUnknown interface for this item.
SCRIPTINFO_ITYPEINFO | Return 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.

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.


IActiveScriptSite::GetLCID

Microsoft® Windows® Script Interfaces
IActiveScriptSite::GetLCID 		Language Reference
Previous
Next

HRESULT GetLCID(
    LCID *plcid  // address of variable for language identifier
);

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.

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

plcid
[out] Address of a variable that receives the locale identifier for user-interface elements displayed by the scripting engine.

If this method returns E_NOTIMPL, the system-defined locale identifier should be used.


IActiveScriptSite::OnEnterScript

Microsoft® Windows® Script Interfaces
IActiveScriptSite::OnEnterScript 		Language Reference
Previous
Next

HRESULT OnEnterScript(void);

Informs the host that the scripting engine has begun executing the script code.

  • Returns S_OK if successful.

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.


IActiveScriptSite::OnLeaveScript

Microsoft® Windows® Script Interfaces
IActiveScriptSite::OnLeaveScript 		Language Reference
Previous
Next

HRESULT IActiveScriptSite::OnLeaveScript(void);

Informs the host that the scripting engine has returned from executing script code.

  • Returns S_OK if successful.

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.


IActiveScriptSite::OnScriptError

Microsoft® Windows® Script Interfaces
IActiveScriptSite::OnScriptError 		Language Reference
Previous
Next

HRESULT IActiveScriptSite::OnScriptError(
    IActiveScriptError *pase  // address of error interface
);

Informs the host that an execution error occurred while the engine was running the script.

  • Returns S_OK if the error was correctly handled, or an OLE defined error code otherwise.
pase
[in] Address of the error object's IActiveScriptError interface. A host can use this interface to obtain information about the execution error.


IActiveScriptSite::OnScriptTerminate

Microsoft® Windows® Script Interfaces
IActiveScriptSite::OnScriptTerminate 		Language Reference
Previous
Next

HRESULT OnScriptTerminate(
    VARIANT *pvarResult,   // address of script results
    EXCEPINFO *pexcepinfo  // address of structure with exception information
);

Informs the host that the script has completed execution.

  • Returns S_OK if successful.
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.

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.


IActiveScriptSite::OnStateChange

Microsoft® Windows® Script Interfaces
IActiveScriptSite::OnStateChange 		Language Reference
Previous
Next

HRESULT IActiveScriptSite::OnStateChange(
    SCRIPTSTATE ssScriptState  // new state of engine
);

Informs the host that the scripting engine has changed states.

  • Returns S_OK if successful.
ssScriptState
[in] Value that indicates the new script state. See the IActiveScript::GetScriptState method for a description of the states.


IActiveScriptSiteWindow

Microsoft® Windows® Script Interfaces
IActiveScriptSiteWindow 		Language Reference
Previous
Next

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
GetWindow | Retrieves the window handle that can act as the owner of a pop-up window that the scripting engine must display.
EnableModeless | Causes the host to enable or disable its main window as well as any modeless dialog boxes.


IActiveScriptSiteWindow::EnableModeless

Microsoft® Windows® Script Interfaces
IActiveScriptSiteWindow::EnableModeless 		Language Reference
Previous
Next

HRESULT IActiveScriptSite::EnableModeless(
    BOOL fEnable  // enable flag
);

Causes the host to enable or disable its main window as well as any modeless dialog boxes.

  • Returns S_OK if successful, or E_FAIL if an error occurred.
fEnable
[in] Flag that, if TRUE, enables the main window and modeless dialogs or, if FALSE, disables them.

This method is identical to the IOleInPlaceFrame::EnableModeless method.

Calls to this method can be nested.


IActiveScriptSiteWindow::GetWindow

Microsoft® Windows® Script Interfaces
IActiveScriptSiteWindow::GetWindow 		Language Reference
Previous
Next

HRESULT GetWindow(
    HWND *phwnd  // address of variable for window handle
);

Retrieves the handle to a window that can act as the owner of a pop-up window that the scripting engine must display.

  • Returns S_OK if successful, or E_FAIL if an error occurred.
phwnd
[out] Address of a variable that receives the window handle.

This method is similar to the IOleWindow::GetWindow method.


Enumerations

Microsoft® Windows® Script Interfaces
Enumerations 		Language Reference
Previous
Next

This section describes the enumerations used by Windows Script engines.

  • SCRIPTSTATE
  • SCRIPTTHREADSTATE


SCRIPTSTATE

Microsoft® Windows® Script Interfaces
SCRIPTSTATE 		Language Reference
Previous
Next

typedef enum tagSCRIPTSTATE {
    SCRIPTSTATE_UNINITIALIZED = 0,
    SCRIPTSTATE_INITIALIZED   = 5,
    SCRIPTSTATE_STARTED       = 1,
    SCRIPTSTATE_CONNECTED     = 2,
    SCRIPTSTATE_DISCONNECTED  = 3,
    SCRIPTSTATE_CLOSED        = 4
} SCRIPTSTATE;

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.

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.


SCRIPTTHREADSTATE

Microsoft® Windows® Script Interfaces
SCRIPTTHREADSTATE 		Language Reference
Previous

typedef enum tagSCRIPTTHREADSTATE {
    SCRIPTTHREADSTATE_NOTINSCRIPT  = 0,
    SCRIPTTHREADSTATE_RUNNING      = 1
} SCRIPTTHREADSTATE;

Contains named constant values that specify the state of a thread in a scripting engine. This enumeration is used by the IActiveScript::GetScriptThreadState method.

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.


IDispatchEx Interface

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

   <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():

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

   BOOL test(IDispatchEx *pdexScript)
   {
      HRESULT hr;
      VARIANT var;
      BSTR bstrName;
      DISPID dispid, putid;
      IDispatchEx *pdexObj;
      IDispatch   *pdispObj, *pdispCat;
      DISPPARAMS dispparams, dispparamsNoArgs = {NULL, NULL, 0, 0};

      // Get dispatch pointer for "cat"
      bstrName = SysAllocString(OLESTR("cat"));
      pdexScript->GetDispID(bstrName, 0, &dispid);
      SysFreeString(bstrName);
      pdexScript->InvokeEx(dispid, LOCALE_USER_DEFAULT,
         DISPATCH_PROPERTYGET, &dispparamsNoArgs,
         &var, NULL, NULL);
      pdispCat = var.pdispVal;

      // Create object by calling "Object" constructor
      bstrName = SysAllocString(OLESTR("Object"));
      pdexScript->GetDispID(bstrName, 0, &dispid);
      SysFreeString(bstrName);
      pdexScript->InvokeEx(dispid, LOCALE_USER_DEFAULT,
         DISPATCH_CONSTRUCT, &dispparamsNoArgs,
         &var, NULL, NULL);
      pdispObj = var.pdispVal;
      pdispObj->QueryInterface(IID_IDispatchEx, (void **)&pdexObj);

      // Create new element in object
      bstrName = SysAllocString(OLESTR("Elem"));
      pdexObj->GetDispID(bstrName, fdexNameEnsure, &dispid);
      SysFreeString(bstrName);

      // 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;
      pdexObj->InvokeEx(dispid, LOCALE_USER_DEFAULT,
         DISPATCH_PROPERTYPUTREF, &dispparams,
         NULL, NULL, NULL);

      // 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;
      pdexObj->InvokeEx(dispid, LOCALE_USER_DEFAULT,
         DISPATCH_METHOD, &dispparams,
      NULL, NULL, NULL);

      // Confirm that new element "Bar" is in object
      hr = pdexObj->GetNextDispID(fdexEnumAll, DISPID_STARTENUM, &dispid);
      while (hr != S_FALSE)
      {
         pdexObj->GetMemberName(dispid, &bstrName);
         if (!wcscmp(bstrName, OLESTR("Bar")))
            return TRUE;
         SysFreeString(bstrName);
         hr = pdexObj->GetNextDispID(fdexEnumAll, dispid, &dispid);
      }
      return FALSE;
   }

Methods

IDispatchEx Methods


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 Section

IDispatchEx Interface


IDispatchEx::DeleteMemberByDispID

Deletes a member by DISPID.

HRESULT DeleteMemberByDispID(
    DISPID id
);

Returns one of the following values:

S_OK | Success.
S_FALSE | Member exists but cannot be deleted.

Parameters

id
Member identifier. Uses GetDispID or GetNextDispID to obtain the dispatch identifier.

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

Example

BSTR bstrName;
DISPID dispid;
IDispatch *pdex;

// Assign to pdex and bstrName
pdex->GetDispID(bstrName, fdexNameCaseSensitive, &dispid);
pdex->DeleteMemberByDispID(dispid);

See Also

IDispatchEx Interface | IDispatchEx::GetDispID | IDispatchEx::GetNextDispID


IDispatchEx::DeleteMemberByName

Deletes a member by name.

HRESULT DeleteMemberByName(
   BSTR bstrName,
   DWORD grfdex
);

Returns one of the following values:

S_OK | Success.
S_FALSE | Member exists but cannot be deleted.

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.

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

Example

BSTR bstrName;
IDispatch *pdex;

// Assign to pdex and bstrName
pdex->DeleteMemberByName(bstrName, fdexNameCaseSensitive);

See Also

IDispatchEx Interface


IDispatchEx::GetDispID

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
);

Returns one of the following values:

S_OK | Success.
E_OUTOFMEMORY | Out of Memory.
DISP_E_UNKNOWNNAME | The name was not known.

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.

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.

Example

BSTR bstrName;
   DISPID dispid;
   IDispatch *pdex;

   // Assign to pdex and bstrName
   pdex->GetDispID(bstrName, fdexNameCaseSensitive, &dispid);
   // Use dispid

See Also

IDispatchEx Interface


IDispatchEx::GetMemberName

Retrieves the name of a member.

HRESULT GetMemberName(
   DISPID id,
   BSTR *pbstrName
);

Returns one of the following values:

S_OK | Success.
DISP_E_UNKNOWNNAME | The name was not known.

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.

Example

HRESULT hr;
   BSTR bstrName;
   DISPID dispid;
   IDispatch *pdex;

   // Assign to pdex
   hr = pdex->GetNextDispID(fdexEnumAll, DISPID_STARTENUM, &dispid);
   while (hr != S_FALSE)
   {
   pdex->GetMemberName(dispid, &bstrName);
   if (!wcscmp(bstrName, OLESTR("Bar")))
      return TRUE;
   SysFreeString(bstrName);
   hr = pdexObj->GetNextDispID(fdexEnumAll, dispid, &dispid);
}

See Also

IDispatchEx Interface | IDispatchEx::GetDispID | IDispatchEx::GetNextDispID


IDispatchEx::GetMemberProperties

Retrieves a member's properties.

HRESULT GetMemberProperties(
   DISPID id,
   DWORD grfdexFetch,
   DWORD *pgrfdex
);

Returns one of the following values:

S_OK | Success.
DISP_E_UNKNOWNNAME | The name was not known.

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.

Example

BSTR bstrName;
   DISPID dispid;
   IDispatch *pdex;
   DWORD dwProps;

   // Assign to pdex and bstrName
   pdex->GetDispID(bstrName, fdexNameCaseSensitive, &dispid);
   pdex->GetMemberProperties(dispid, grfdexPropAll, &dwProps);
   if (dwProps & fdexPropCanPut)
      // Assign to member

See Also

IDispatchEx Interface | IDispatchEx::GetDispID | IDispatchEx::GetNextDispID


IDispatchEx::GetNameSpaceParent

Retrieves the interface for the namespace parent of an object.

HRESULT GetNameSpaceParent(
   IUnknown **ppunk
);

Returns S_OK if successful or an OLE-defined error code otherwise.

Parameters

ppunk
Address of an IUnknown interface pointer that receives the namespace parent's interface.

See Also

IDispatchEx Interface


IDispatchEx::GetNextDispID

Enumerates the members of the object.

HRESULT GetNextDispID(
   DWORD grfdex,
   DISPID id,
   DISPID *pid
);

Returns one of the following values:

S_OK | Success.
S_FALSE | Enumeration is done.

Parameters

grfdex
Determines which set of items will 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 will retrieve 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.

Example

HRESULT hr;
   BSTR bstrName;
   DISPID dispid;
   IDispatch *pdex;

   // Assign to pdex
   hr = pdex->GetNextDispID(fdexEnumAll, DISPID_STARTENUM, &dispid);
   while (hr != S_FALSE)
   {
      pdex->GetMemberName(dispid, &bstrName);
      if (!wcscmp(bstrName, OLESTR("Bar")))
      return TRUE;
      SysFreeString(bstrName);

      hr = pdexObj->GetNextDispID(fdexEnumAll, dispid, &dispid);
   }

See Also

IDispatchEx Interface | IDispatchEx::GetDispID | IDispatchEx::GetNextDispID | IDispatchEx::DeleteMemberByName | IDispatchEx::DeleteMemberByDispID


IDispatchEx::InvokeEx

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
);

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.

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
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_PROPERTYGET
DISPATCH_METHOD
DISPATCH_PROPERTYPUT
DISPATCH_PROPERTYPUTREF
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"

Example

VARIANT var;
   BSTR bstrName;
   DISPID dispid;
   IDispatch *pdex;
   DISPPARAMS dispparamsNoArgs = {NULL, NULL, 0, 0};

   // Assign to pdex and bstrName
   pdex->GetDispID(bstrName, fdexNameCaseSensitive, &dispid);
   pdex->InvokeEx(dispid, LOCALE_USER_DEFAULT,
   DISPATCH_PROPERTYGET, &dispparamsNoArgs,
   &var, NULL, NULL);

See Also

IDispatchEx Interface | IDispatchEx::GetDispID | IDispatchEx::GetNextDispID


getFileVersion Method

Returns the version number of a specified file.

object.GetFileVersion(pathspec)

Arguments

object
Required. Always the name of a FileSystemObject.
pathspec
Required. The path (absolute or relative) to a specific file.

Remarks

The GetFileVersion method returns a zero-length string ("") if pathspec does not end with the named file or if the file does not contain version information.

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.

function ShowFileVersion(pathspec){
  var fso, s = "";
  fso = new ActiveXObject("Scripting.FileSystemObject");
  s += fso.GetFileVersion(pathspec);
  if (s == "")
    s = "No version information available.";
  return(s);
}

Requirements

Version 1


SerialNumber Property

Returns the decimal serial number used to uniquely identify a disk volume.

object.SerialNumber

The object is always a Drive object.

Remarks

You can use the SerialNumber property to ensure that the correct disk is inserted in a drive with removable media.

The following code illustrates the use of the SerialNumber property:

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);
}

Requirements

Version 1


Topic Not Found

The link you just clicked was not able to connect to the target page. Some possible reasons and remedies are as follows:

Reason | Remedy
The URL of the destination topic is incorrect or has changed. | Use the index or the search function instead.
Problems with the help installation. | Uninstall help and then rerun Setup.


Using Message Boxes

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.

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.

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.

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


Displaying Information in the Browser

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.

document.write("Pi is approximately equal to " + Math.PI);
document.write( );
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.
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.

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

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.

document.clear();


Copyright

Microsoft® JScript®

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, people and events depicted herein are fictitious and no association with any real company, organization, product, person 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.

© 1991-2000 Microsoft Corporation. All rights reserved.

Microsoft, MS, MS-DOS, ActiveX, JScript, Microsoft Press, MSDN, Visual Basic, Windows, Windows NT, Win32, and Win32s 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.


Array length must be assigned a finite positive number

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.
    var my_array = new Array();
my_array.length = 99;

See Also

Using Arrays


Array length must be a finite positive integer

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.
    var piArray = new Array(3.14159);

    The following example demonstrates the correct way to specify an array with a single numeric element.

    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

Using Arrays


Array or arguments object expected

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

Using Arrays | apply Method | JScript Functions


Boolean expected

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:

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

Boolean Object | JScript Data Types | Controlling Program Flow | Copying, Passing, and Comparing Data


Cannot assign to a function result

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.

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.
    myVar = myFunction(42);
  • Alternatively, you can assign the function itself (and not its return value) to a variable.
    myFunction = new Function("return 42;");

See Also

Function Object | Writing JScript Code | JScript Functions


Cannot assign to 'this'

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 You cannot name a user-created variable this; it is a JScript reserved word.

See Also

This | Troubleshooting Your Scripts


Can't have 'break' outside of loop

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.

Exception

A label can follow the break keyword.

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

Break | Controlling Program Flow | Troubleshooting Your Scripts


Can't have 'continue' outside of loop

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

Continue | Controlling Program Flow | Troubleshooting Your Scripts


Conditional compilation is turned off

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:

/*@cc_on @*/

To correct this error

Add the following statement to the beginning of your conditional code:

/*@cc_on @*/

See Also

Conditional Compilation | Conditional Compilation Variables | @cc_on | @if Statement | @set Statement


Date object expected

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:

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

Date Object | getDate Method | Intrinsic Objects


'default' can only appear once in a 'switch' statement

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

Switch | Controlling Program Flow | JScript Reserved Keywords


Enumerator object expected

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:

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:

if(x instanceof Enumerator)

See Also

Enumerator Object


Exception thrown and not caught

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

Error Object | throw Statement | try...catch Statement


Expected '('

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.

for (initialize; test; increment) {
statement;
}

To correct this error

  • Add the left parenthesis to the evaluation expression.


Expected ')'

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.

for (initialize; test; increment) {
statement;
}

To correct this error

  • Add the right parentheses to the evaluation expression.


Expected '/'

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

Regular Expression Object | Regular Expression Syntax


Expected ':'

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

Conditional (Ternary) Operator (?:) | JScript Operators


Expected ';'

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

Writing JScript Code


Expected '@'

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:

@set @myvar = 1

See Also

@set Statement | Conditional Compilation | Conditional Compilation Variables


Expected '}'

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

Function Object | Controlling Program Flow


Expected '='

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:

@set @myvar1 = 1

See Also

Conditional Compilation | Conditional Compilation Variables


Expected ']'

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

Using Arrays |js56 Array Object


Expected ']' in regular expression

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

Regular Expression Object | Regular Expression Syntax


Expected 'catch'

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

try...catch Statement | Error Object


Expected constant

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

Conditional Compilation | Conditional Compilation Variables


Expected '@end'

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

Conditional Compilation | Conditional Compilation Variables


Expected hexadecimal digit

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.

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

JScript Data Types


Expected identifier

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

Using Arrays


Expected identifier, string or number

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:

var point = {x:1.2, y:-3.4};

To correct this error

Ensure you use the proper literal syntax.

See Also

Comma Operator (,)


Expected ')' in regular expression

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

Regular Expression Object | Regular Expression Syntax


Expected 'while'

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

while Statement | Controlling Program Flow


Expected '{'

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

Function Object


Function does not have a valid prototype object

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

Function Object | prototype Property


Function expected

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.

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

Function Object | prototype Property


Illegal assignment

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

Assignment Operator (=)


Invalid character

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

JScript Variables | Special Characters | JScript Data Types


Invalid range in character set

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:

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

Regular Expression Object | Regular Expression Syntax


JScript object expected

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

JScript Objects | Using Arrays


Label not found

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

Labeled Statement | switch Statement | break Statement | continue Statement


Label redefined

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

Labeled Statement | switch Statement | break Statement | continue Statement


Number expected

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

Number Object | number Property


Object expected

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

Object Object | JScript Objects


Object member expected

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

Object Object | JScript Objects


Regular expression object expected

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

Regular Expression Object | Regular Expression Syntax


'return' statement outside of function

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:

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

return Statement | Function Object | caller Property


String expected

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

String Object | toString Method


Syntax error

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

Error Object


Syntax error in regular expression

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

Regular Expression Object | Regular Expression Object Properties | Regular Expression Object Methods | Regular Expression Syntax | compile Method


The number of fractional digits is out of range

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

toExponential Method


The precision is out of range

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

toPrecision Method


The URI to be decoded is not a valid encoding

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:

<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

decodeURI Method | decodeURIComponent Method


The URI to be encoded contains an invalid character

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

<Scheme>:<first>/<second>;<third>?<fourth>

The names in angle brackets represent components, and the ":", "/", ";" and "?" are reserved characters used as separators.

See Also

encodeURI Method | encodeURIComponent Method


Throw must be followed by an expression on the same source line

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:

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

Error Object | throw Statement | try...catch Statement


Undefined identifier

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

JScript Variables | Variable Scope


Unexpected quantifier

When composing your regular expression search pattern, you created a pattern element with an illegal repetition factor. For example, the pattern

/^+/

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

Regular Expression Object | Regular Expression Syntax


Unterminated comment

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:

/* 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

Comment Statements


Unterminated string constant

You did not end your string constant with a closing quotation mark. String constants must be enclosed within a pair of quotation marks.

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

String Object | toString Method


VBArray expected

You supplied an object that was not a Visual Basic safeArray, when one was expected.

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

VBArray Object | Using Arrays


Operator Summary

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


Jscript Language Features in the Technology Preview Release

Microsoft JScript 5.6 introduces several new language features.

Getting Started

The following documentation should help you get up to speed. Your suggestions and comments regarding the documentation are encouraged.

To learn about | See
in operator | in Operator
New Global object methods | decodeURIComponent Method decodeURI Method encodeURI Method encodeURIComponent Method
New Object object methods | hasOwnProperty Method isPrototypeOf Method
New Function object methods | apply Method call Method
New Array object methods | pop Method push Method shift Method splice Method unshift Method
New Number object methods | toFixed Method toExponential Method toPrecision Method
New Date object methods | toDateString Method toTimeString Method toLocaleDateString Method toLocaleTimeString Method
New RegExp object methods and properties | toString Method global Property ignoreCase Property multiline Property
New String object methods | localeCompare Method toLocaleLowerCase Method toLocaleUpperCase Method
New Error object properties | name Property message Property


Version Information

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

Language Element | 1.0 | 2.0 | 3.0 | 4.0 | 5.0 | 5.5
Microsoft Internet Explorer 3.0 | x |  |  |  |  |
Microsoft Internet Information Server 1.0 |  | x |  |  |  |
Microsoft Internet Explorer 4.0 |  |  | x |  |  |
Microsoft Internet Information Server 4.0 |  |  | x |  |  |
Microsoft Windows Scripting Host 1.0 |  |  | x |  |  |
Microsoft Visual Studio 6.0 |  |  |  | x |  |
Microsoft Internet Explorer 5.0 |  |  |  |  | x |
Microsoft Internet Information Services 5.0 |  |  |  |  |  | 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
0…n Property |  |  |  |  |  | x
$1...$9 Properties |  |  | x |  |  |
abs Method | x |  |  |  |  |
acos Method | x |  |  |  |  |
ActiveXObject Object |  |  | x |  |  |
Addition Operator (+) | x |  |  |  |  |
anchor Method | x |  |  |  |  |
apply method |  |  |  |  |  | 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 Operator (&) | x |  |  |  |  |
Bitwise Left Shift Operator (<<) | x |  |  |  |  |
Bitwise NOT Operator (~) | x |  |  |  |  |
Bitwise OR Operator (|) | x |  |  |  |  |
Bitwise Right Shift 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 |  |  |  |  |
decodeURI Method |  |  |  |  |  | x
decodeURIComponent |  |  |  |  |  | x
Decrement Operator ( — ) | x |  |  |  |  |
delete Operator |  |  | x |  |  |
description Property |  |  |  |  | x |
dimensions Method |  |  | x |  |  |
Division Operator (/) | x |  |  |  |  |
do...while Statement |  |  | x |  |  |
E Property | x |  |  |  |  |
encodeURI Method |  |  |  |  |  | x
encodeURI Component |  |  |  |  |  | x
Enumerator Object |  |  | x |  |  |
Equality Operator (==) | x |  |  |  |  |
Error Object |  |  |  |  | x |
escape Method | x |  |  |  |  |
eval Method | x |  |  |  |  |
exec Method |  |  | x |  |  |
exp Method | 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
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
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 Operator (%) | x |  |  |  |  |
moveFirst Method |  |  | x |  |  |
moveNext Method |  |  | x |  |  |
multiline Property |  |  |  |  |  | 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 |  |  |  |
propertyIsEnumeramble Poperty |  |  |  |  |  | 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
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 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 Operator (>>>) | x |  |  |  |  |
UTC Method | x |  |  |  |  |
valueOf Method |  | x |  |  |  |
var Statement | x |  |  |  |  |
VBArray Object |  |  | x |  |  |
void Operator |  | x |  |  |  |
while Statement | x |  |  |  |  |
with Statement | x |  |  |  |  |


Copyright

Microsoft® VBScript®

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, people and events depicted herein are fictitious and no association with any real company, organization, product, person 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.

© 1991-2000 Microsoft Corporation. All rights reserved.

Microsoft, MS, MS-DOS, ActiveX, JScript, Microsoft Press, MSDN, Visual Basic, Windows, Windows NT, Win32, and Win32s 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


ActiveX component can't create object

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

Using VBScript with Objects


An exception occurred

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

Raise Method | Err


Argument not optional

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

VBScript Procedures


This array is fixed or temporarily locked

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

Array Function | Dim Statement | ReDim Statement | Set Statement | Private Statement | Public Statement


Cannot have multiple default property/method in a Class

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

Function Statement


Cannot use parentheses when calling a Sub

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

Call Statement | Sub Statement


Can't perform requested operation

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.


Class doesn't support Automation

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 The object may have been created using CreateObject, but it also may have been introduced by way of the host object model.

See Also

CreateObject Function


Class initialize or terminate do not have arguments

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

Initialize Event | Terminate Event


Class not defined

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

Set Statement


'Default' specification can only be on Property Get

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

Property Let Statement | Property Set Statement | Property Get Statement


'Default' specification must also specify 'Public'

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

Function Statement


Division by zero

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.


Error in loading DLL

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 ']' in regular expression

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

Regular Expression (RegExp) Object


Expected 'Case'

You created a Select…End Select construct, but did not include any Case statements. The following demonstrates the correct usage of the Select…End Select construct.

Select Case testexpression
   [Case expressionlist-n
      [statements-n]] . . .
   [Case Else expressionlist-n
      [elsestatements-n]]
End Select

To correct this error

Make sure that the Select…End Select construct includes all the necessary parts.

See Also

Select Case Statement


Expected 'Class'

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

Class Statement


Expected 'End'

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

Sub Statement | Function Statement


Expected end of statement

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

VBScript Coding Conventions


Expected '='

You used the Set statement, but did not include the =.

To correct this error

Use the full syntax of the Set statement.

See Also

Set Statement


Expected expression

You created a Select…End 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 Select…End Select construct.

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

Select Case Statement


Expected 'Function'

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

Function Statement | Call Statement | Dim Statement | Exit Statement | Set Statement | Sub Statement


Expected identifier

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 [ ].


Expected 'If'

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.

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

If...Then...Else Statement


Expected 'In'

You created a For Each…Next block, but did not include the In keyword in the first line. The following demonstrates the correct structure of a For Each…Next block.

For Each element In group
   [statements]
   [Exit For]
   [statements]
Next [element]

To correct this error

Make sure that the For Each…Next block includes all the necessary parts.

See Also

For Each...Next Statement | Do...Loop Statement | Exit Statement | For...Next Statement | While...Wend Statement


Expected ')' in regular expression

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

Regular Expression (RegExp) Object


Expected integer constant

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,

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

Dim Statement | ReDim Statement


Expected '('

You did not include the opening parenthesis "(" when you created a procedure declaration,

Sub mysample x // x should be enclosed within parentheses.
End Sub

or used the redim statement.

Redim x // x should be enclosed within parentheses.

To correct this error

Add the left (opening) parenthesis "(".

See Also

Operator Precedence


Expected Let or Set or Get in property declaration

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

Property Let Statement | Property Set Statement | Property Get Statement


Expected literal constant

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

VBScript Constants | VBScript Constants | Const Statement


Expected 'Loop'

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.

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

Or, you can use this syntax:

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

Do...Loop Statement | Exit Statement | For...Next Statement | While...Wend Statement


Expected 'Next'

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.

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

For...Next Statement | Do...Loop Statement | Exit Statement | For Each...Next Statement | While...Wend Statement


Expected 'Property'

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

Property Let Statement | Property Set Statement | Property Get Statement


Expected ')'

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

Operator Precedence


Expected 'Select'

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.

Select Case testexpression
   [Case expressionlist-n
      [statements-n]] . . .
   [Case Else expressionlist-n
      [elsestatements-n]]
End Select

To correct this error

Make sure the Select…End Select construct includes all the necessary parts.

See Also

Select Case Statement | If...Then...Else Statement


Expected statement

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.

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,

<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

Execute Statement | Eval


Expected 'Sub'

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

Sub Statement | Call Statement | Dim Statement | Exit Statement | Function Statement


Expected 'Then'

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.

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

To correct this error

Make sure that the If...Then...Else construct includes all the necessary parts.

See Also

If...Then...Else Statement | Select Case Statement | Using Conditional Statements


Expected 'To'

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.

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

For...Next Statement | For Each...Next Statement | Do...Loop Statement | Exit Statement | For...Next Statement | While...Wend Statement


Expected 'Wend'

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.

While condition
   Version [statements]
Wend

To correct this error

Make sure that the While…Wend loop includes all the necessary parts.

See Also

Looping Through Code | While...Wend Statement | Do...Loop Statement | For...Next Statement | For Each...Next Statement | Exit Statement


Expected 'While' or 'Until'

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.

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

Or, you can use this syntax:

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

Looping Through Code | Do...Loop Statement | For...Next Statement | For...Next Statement | While...Wend Statement | Exit Statement


Expected 'While,' 'Until,' or end of statement

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.

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

Or, you can use this syntax:

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

Looping Through Code | Do...Loop Statement | For...Next Statement | For...Next Statement | While...Wend Statement | Exit Statement


Expected 'With'

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.

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

Using Conditional Statements | With Statement | Set Statement | If...Then...Else Statement | Select Case Statement


File name or class name not found during Automation operation

You used the GetObject 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.

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

GetObject Function | CreateObject Function


For loop not initialized

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.

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

Looping Through Code | For...Next Statement | Do...Loop Statement | Exit Statement | For Each...Next Statement | While...Wend Statement


Identifier too long

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

VBScript Variables | VBScript Data Types | Dim Statement | Public Statement | Private Statement


Illegal assignment

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

Assignment Operator (=) | Comparison Operators | Operator Precedence | Operator Summary | Set Statement


Internal error

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

Raise Method


Invalid character

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 [].


Invalid 'exit' statement

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

Exit Statement | Do...Loop Statement | For Each...Next Statement | For...Next Statement | Function Statement | Sub Statement


Invalid 'for' loop control variable

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.

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

Looping Through Code | For...Next Statement | Do...Loop Statement | Exit Statement | For Each...Next Statement | While...Wend Statement


Invalid number

A value in your expression is too large, or out of range.

To correct this error

Use a smaller value.

See Also

VBScript Data Types | VarType Function


Invalid or unqualified reference

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.

With object
   statements
End With

To correct this error

Specify an object for the With statement.

See Also

With Statement


Invalid picture

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

LoadPicture Function


Invalid range in character set

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

Regular Expression (RegExp) Object


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.


Invalid use of Null

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

IsNull Function


'loop' without 'do'

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.

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

Or, you can use this syntax:

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

Do...Loop Statement | Exit Statement | For...Next Statement | While...Wend Statement


Must be defined inside a Class

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

Property Let Statement | Property Set Statement | Property Get Statement


Must be first statement on the line

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

If...Then...Else Statement


Named argument not found

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

VBScript Coding Conventions


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.


Number of arguments must be consistent across properties specification

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

Property Let Statement | Property Set Statement | Property Get Statement


Object doesn't support current locale setting

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

CDate Function


Object doesn't support this action

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

Using VBScript with Objects | CreateObject Function | GetObject Function


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.


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.


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


Object not safe for initializing

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 FileScriptingObject 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

Initialize Event


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


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.


Object variable not set

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

Property Set Statement


Out of Memory

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

Erase Statement | Dim Statement | Nothing | ReDim Statement | CreateObject Function


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.


Out of string space

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

Erase Statement | Dim Statement | Nothing | ReDim Statement | CreateObject Function


Overflow

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

VBScript Variables | Err


Procedure call or argument is not valid

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

VBScript Variables | Function Statement | Sub Statement | Call Statement


Property Set or Let must have at least one argument

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

Property Let Statement | Property Set Statement | Property Get Statement | Class Statement


Sub or function not defined

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

Sub Statement | Function Statement


Subscript out of range

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

UBound Function | LBound Function | Dim Statement | ReDim Statement


Syntax error

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

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


Syntax error in regular expression

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

Regular Expression (RegExp) Object


Type mismatch

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

VBScript Variables


Unexpected 'Next'

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.

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

For...Next Statement | For Each...Next Statement | Looping Through Code | Exit Statement


Unexpected quantifier

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

Regular Expression (RegExp) Object


Unterminated string constant

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

VBScript Constants


Variable is undefined

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

Option Explicit Statement | VBScript Variables


Variable uses an Automation type not supported in VBScript

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

VBScript Variables | VarType Constants


Wrong number of arguments or invalid property assignment

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

Function Statement | Sub Statement | Call Statement


Assignment Operator

= Operator


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.


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.


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.


Microsoft Windows Script Technologies

In This Section

JScript
Microsoft's powerful scripting language targeted specifically at the Internet. JScript .NET is the next generation of Microsoft's implementation of the ECMA 262 language. Improvements in JScript .NET — which is being developed in conjunction with ECMAScript Edition 4 — include true compiled code, typed and typeless variables, classes (with inheritance, function overloading, property accessors, and more), packages, cross-language support, and access to the .NET Frameworks.
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 a 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.


Copyright

Microsoft® Windows Script Components®

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, people and events depicted herein are fictitious and no association with any real company, organization, product, person 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.

© 1991-2000 Microsoft Corporation. All rights reserved.

Microsoft, MS, MS-DOS, ActiveX, JScript, Microsoft Press, MSDN, Visual Basic, Windows, Windows NT, Win32, and Win32s 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


Simple Validation

Enter a value between 1 and 10:


A Simple First Page


Object Sample

This page requires installation of the Label control.