Day 6: Using Microsoft JScript with WSH Yesterday you learned about the VBScript scripting language and how it is used to create scripts that run under the Windows Scripting Host.. The J
Trang 1condition is true The While or Until condition can be set with the Do or Loop
command, but you normally see it used in conjunction with the Do command:
There are a large number of functions provided by VBScript They assist with
conversions, string manipulation, formatting expressions, date/time functions,
mathematical functions, and user input/output.
In this section, you will look at examples of the more common functions that you are
Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com
Trang 2likely to use in WSH scripts.
Probably the most commonly used conversion function is Chr(), which returns the
character for a given ANSI character code The ANSI code for printable characters
starts at 33 An example of using the Chr() function follows:
you would use this is when your source date is in a long format and you want to add x
In the preceding example, Cdate(strBirthDate) returns 20/09/62 This is based on
my OS system local settings Subtracting this from today’s date results in 13283 days Dividing this by 365 gives 36.3917808219178 years (approximately) Finally, Cint
If you want to find out how VBScript is storing your variable, there is a VarType
function, which returns an Integer indicating the variant sub type:
Trang 3End Select
There is also a simple test you can perform to detect if a variable is a number or text
If you were to tell a programmer that VBScript can do cool things with strings, they
would laugh and tell you to look at Perl because it has regular expression support If you have ever seen one of those expressions, it probably didn’t make any sense at first, and fortunately, this is the VBScript chapter so I don’t have to explain it to you VBScript has enough string manipulation functions to perform fairly complicated manipulations.
An example is checking to see if an entered Internet email address is valid If the @
symbol is not found in the string, the function returns 0 If there is an @, you check that there is at least one dot in the domain name as follows:
Trang 4To demonstrate how useful this function is, imagine you have to convert a UNC path
name to a URL Assuming you have removed the Drive: and added http:// to the string, here is how you change the \ to / for every occurrence of the backslash.
This is one of the more complex features that you will use extensively in scripts The
Set command assigns an object reference to a variable An object in this case is a
Component Object Model (COM) compliant DLL (or OCX) or a program that supports OLE automation, such as the Microsoft Office suite of applications.
functions have what are called methods and properties, which you can access (or
automate) after you have assigned your own variable to the object you want to
Trang 5Set WshNetwork = Wscript.CreateObject("Wscript.WshNetwork")
There are two ways of dealing with errors in VBScript You can either ignore them,
which will cause your script to terminate and display an error message when an error is encountered, or you can use the On Error statement.
places in your script to see if there has been an error Err.Number is 0 if there has not been an error If Err.Number is not 0, Err.Description might contain a useful
description of the error for display or logging purposes.
Trang 6
You can consider a task to be sequential, starting at the top and ending at the bottom, or you can think of it as modular For simple scripts, the sequential method is okay, but for more complicated scripts, you will want to design reusable pieces of code that you can call when required.
Trang 8using the find function You say to yourself, "This is hopeless, there must be a better
way," and you are right.
’ DESC: search all log files for a string and output to a report
Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com
Trang 9file the number of
Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com
Trang 10WSH provides the capability to access the command-line arguments that might be
present when the script is run The following script is a skeleton that you can use in your
Trang 12In this chapter, you’ve learned the basics of the VBScript language and have seen how
to use some of the built-in functions If you do choose VBScript as your primary scripting language, there are many resources for sample scripts on the Web You can learn a lot from looking at existing script files.
Trang 13This usually means you are trying to reference an item in an array that does not
exist An example of this is when you have a collection of Outlook Items and try to refer to item(0), as Outlook collections start from 1
A If you omit the Call command and just use the sub procedure name, you must drop
Trang 14Day 6: Using Microsoft JScript with WSH
Yesterday you learned about the VBScript scripting language and how it is used to
create scripts that run under the Windows Scripting Host Today you’ll learn about
JScript, the other scripting language supported by WSH The JScript scripting language
is based on the popular Java programming language JScript is functionally equivalent
to VBScript, which means that you can write scripts in JScript that perform the same
tasks as scripts written in VBScript Using JScript or VBScript with WSH is primarily a personal preference that relates to your prior programming experience and whether
you’re more comfortable with a scripting language based on BASIC or one based on
JScript is Microsoft's implementation of the JavaScript scripting language that was
originally developed by Netscape Communications Although JScript is similar in many ways to JavaScript, JScript includes Microsoft extensions, a broader object model, and integration with Microsoft technologies Like VBScript, JScript is an interpreted, object-based language that is very useful for developing programs where a full-blown
programming language such as Java or C++ is overkill.
Because the origin of JScript lies in JavaScript, let's first examine how JavaScript came
to be JavaScript began at Netscape Communications as a scripting language named LiveScript When the Java programming language took off, Netscape and Sun
Microsystems combined their efforts to revamp LiveScript The end result was
JavaScript, which used some elements of Java in the context of a scripting environment The main purpose of JavaScript was to provide Web developers with a means of
injecting interactivity into Web pages without having to build full-blown Java applets.
Although Java and JavaScript are similar in terms of their syntax, they were
originally developed independently of each other They also continue to
Explorer Thus, JScript was born At its core, JScript is still the same scripting language
as JavaScript However, newer technologies, such as WSH, have widened the scope of JScript to encompass general scripting solutions, not just Web-based solutions.
Trang 15European Computer Manufacturers Association (ECMA) created a scripting language specification based on joint submissions from Microsoft and Netscape ECMA-262 is the name of the specification, which now forms the foundation for both JScript and
and differences between JScript and Java in the next section The JScript language
syntax can be broken down into the following major elements:
JScript statements are interpreted on a line by line basis A statement typically consists
of a combination of JScript language keywords, immediate data, variables, and
operators Although a new line indicates a new statement, it's generally considered a
good JScript programming style to explicitly terminate statements with a semicolon (;) Following is an example:
Variables are used in JScript to store data In the previous line of code, the var keyword
is used to declare a variable named myName that contains my first name JScript
supports a variety of data types such as text strings, numbers, and Boolean true/false values JScript is a loosely typed language, which means that you don't have to explicitly declare the data type of a variable before using the variable JScript enables you to use different data types with variables and takes on the task of automatically converting
between different types when necessary.
Trang 16by the contents of the variable width The result is stored in the variable area The
multiplication operator (*) is used to multiply the numbers, whereas the assignment
operator (=) indicates that the result is to be stored in the area variable Following is an example of an expression that adds strings together to form a message:
Using the myName variable from earlier, the resulting value of the msg variable in this
example is "Hello, Michael!" Notice that the addition operator (+) is used to add the strings together.
You can include notes and descriptions in JScript code by using comments, which help
to explain how a section of code works There are two types of comments supported by JScript: single-line and multiline A single-line comment begins with a pair of forward
slashes (//) and indicates that the remainder of the line is a comment Following is an example of a single-line comment:
A function is a group of JScript statements organized together separately from the rest
of a JScript program A function performs a certain action and often returns a result
JScript programs call functions to delegate work, which has the beneficial side effect of better program organization JScript provides a few standard functions that you can call You can also create functions of your own to perform common tasks An example of a standard JScript function is eval(), which evaluates a string expression You pass the
closing parantheses (()) Following is an example of how to use the eval() function:
In this example, the string expression stored in the expression variable is evaluated
by passing it to the eval() function The result of the expression is stored in the areavariable.
Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com
Trang 17calling methods on the object The following example gets the year associated with a
Date object that holds the current date and time:
objects In this case, the new Date object represents the current date and time The
Before digging any further into JScript, it’s worth addressing its relationship to Java
There has been a lot of confusion among those new to both Java and JScript regarding the proper role of each language The primary difference between the two languages is that Java is a full-blown object-oriented programming language that is designed to
create standalone programs Although some JScript programs could be considered
standalone, they aren’t really comparable to Java applets and applications.
example, you might use JScript to reorganize the data in a Microsoft Excel spreadsheet
or create a shortcut on the Windows desktop You could use Java to create a
spreadsheet application of your own or to create an object that graphs spreadsheet
JScript programs are entered as text files with a js filename extension and then
interpreted directly using the WSH Java programs are entered as text files with a javafilename extension and must be compiled using a Java compiler before they can be
executed Compiled Java programs are stored in a special format called bytecode that must be executed within a Java interpreter such as the one provided with the Java
Development Kit (JDK) In the case of Java applets, an interpreter is integrated with enabled Web browsers WSH serves as the interpreter for JScript programs.
Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com
Trang 18do so You learned how to declare variables using the var keyword a little earlier in the lesson Variable declaration is only required for variables that are local to a function
Following are some examples of variable declarations:
Although I’ve defined a variable representing the value of PI, 3.14, JScript
includes this value as a property of the Math object To use the value in an
expression, you refer to it as Math.PI.
The JScript language uses certain reserved words that you aren't enabled to
use as variable names These reserved words are used as names for
standard parts of the JScript language, such as object and function names
Reserved words also include JScript language keywords, such as true,
false, and var.
Trang 19
documentation for a complete list of JScript keywords).
Speaking of data types, it is sometimes necessary to convert data from one type to
another Fortunately, JScript handles most data type conversion automatically Check
This example shows how the numeric data type stored in the circumference variable
is automatically converted to a string when concatenated into the results string data type Although this conversion is automatic when going from numbers to strings, the
opposite isn't true Converting strings to numbers requires you to manually make the
conversion To accomplish this conversion, you use the standard parseInt() and
Trang 20
As exciting as variables might be, they aren’t incredibly useful in and of themselves
JScript programming gets much more interesting when you inject logic into your scripts Program logic is what enables a script to take different actions based on the value of a variable or expression For example, you might input the name of a user and display
different information based on the user’s identification.
JScript program logic is based on Boolean tests, which always evaluate to either true
Although the result of a Boolean test is a Boolean value, you can use any data type as a part of the test The main Boolean test used in JScript is the if-else statement The
if-else statement is used to conditionally execute one section of code or another
Following is the syntax for the if-else statement, which helps you understand how it works:
If the Boolean variable hungry is true, the first statement is executed, and
If you have only a single statement that you want to execute conditionally, you can leave off the
else part of the if-else statement, like this:
On the other hand, what happens if you have more than two branches you want to
conditionally choose between? In situations like this, you can string together a series of
if-else statements to get the net effect of multiple conditions Check out the following code:
This code can take one of a number of different conditions based on the value of the
age variable Keep in mind that the conditional evaluations are performed in order, so if you arrive at the test age < 65, you already know that age is at least 18 or greater
Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com
Trang 21Otherwise, the previous if conditional would have evaluated to true Also, remember that only one of the conditional statements is executed.
if-else statement as a single statement The following sample code demonstrates:
This example shows how multiple statements can be executed within a single if
statement by enclosing them in curly braces Placing the opening curly brace ({) at the end of the line with the if conditional is a pretty standard JScript convention, along with placing the closing curly (}) brace on a new line following the compound statements.
In addition to demonstrating the usefulness of conditional and compound
statements, the previous example also shows how comments can be used to clarify the meaning of numbers This is a good habit to develop when using
numbers in situations where something about their meaning might not be
totally apparent It is beneficial if someone else ever needs to modify or
reference your code or if you ever come back to the code and can’t
immediately remember all the details.
expression and conditionally evaluates another expression based on the test Look at an example to help clarify:
evaluated In this example, the test (maybe) is true, so the line of code effectively
becomes the following:
Although it illustrates how the conditional operator works, this example really doesn’t
demonstrate the power of the conditional operator Look at an example that’s a little
In this example, a less-than operator (<) is used to see if the age variable is less than
30 If so, the nickname variable is set to "young fella"; otherwise nickname is set
to "oldtimer" In this case the age variable is set to 17, so the conditional operator results in the nickname variable being set to "young fella".
Trang 22the if-else branch Consider the following if-else sample code you looked at a little earlier:
I mentioned that the conditional operator is somewhat of a shorthand version
of the if-else statement I used the word "somewhat" because the two
things aren’t always equivalent The conditional operator can only be used to
conditionally execute one expression or another The if-else statement, on the other hand, is capable of executing entire sections of code that can
include multiple expressions So the conditional operator is only a shorthand
version of the if-else statement in the most simple of examples.
Boolean operators available for use in JScript:
The AND operator (&&) compares two values and only returns true if they are both
true The OR (||) operator compares two values and returns true if either of the
values is true The negation operator (!) flips the state of a value; if a value is true, it becomes false, and if it is false, it becomes true The equal-to (==) and not-equal-
to (!=) operators check to see if two values are equal or not equal, respectively.
a section of code a fixed number of times Following is the syntax for the for loop:
Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com
Trang 23The for loop repeats the Statement a number of times as determined by the
InitializationExpression, LoopCondition, and StepExpression:
executed, which in this case prints the current value of i After each iteration, the
StepExpression is evaluated, which is i This serves to decrement i after each iteration and ultimately provides the countdown.
The loop continues to iterate and print numbers as i counts down to 0 When i reaches
0, the LoopCondition test fails (i > 0), so the loop bails out To help you visualize the looping process, take a look at Figure 6.1.
Notice in the figure that Statement1 and Statement2 are repeatedly executed as
long as the loop condition is true When the loop condition is false, the program falls out of the loop and executes Statement3.
The previous figure alludes to the fact that a loop can execute multiple statements
Loops can execute as many statements as they want, provided that curly braces ({}) enclose the statements If you recall, this grouping of statements is known as a
compound statement and was used earlier in the day with the if-else statement
Following is an example of a for loop with a compound statement:
Trang 24var nums = new Array[10];
the array contains.
JScript also supports a variation of the for loop called the for-in loop This loop is
specifically designed for iterating through the properties of an object This illuminates an interesting fact about JScript arrays: Elements of a JScript array are really just
properties of an Array object Following is a different version of the previous example implemented with a for-in loop:
which should make its usage a little more clear:
expression, it is important to make sure that the Statement somehow impacts the
LoopCondition Otherwise, it is possible for the loop to infinitely repeat, which is
usually a bad thing Following is a simple example of an infinite while loop:
of the while loop as a more general for loop To understand what I mean by this,
check out the following example:
Trang 25expression i has to be performed within the Statement part of the loop Regardless
of the structural differences, this while loop is functionally equivalent to the for loop you saw earlier in the day.
There is one last topic to cover before you’re finished with looping constructs I’m
referring to the break and continue statements, which are used to exit and short
circuit loops The break statement immediately quits a loop regardless of the loop
condition The continue statement, on the other hand, immediately goes to the next iteration of a loop Following is an example of circumventing an infinite loop with a
Without the assistance of the break statement, this while loop would continue on
forever thanks to the permanent true loop condition The break statement sidesteps this problem by breaking out of the loop after one hundred iterations (0-99) Of course, it
is rare that you purposely create an infinite loop and then use a break statement to bail out of it However, the break statement can be very useful in some tricky loops when you need to exit at an otherwise inconvenient time.
example shows how a continue statement can be used to determine only the even
numbers between 1 and 100:
numbers using the modulus operator The sample code exploits this characteristic of
even and odd numbers to skip to the next iteration of the loop when it encounters an
odd number The resulting value of evenNums is of the form "2 4 6 8 ".
keyword Following is an example of a function that calculates the square of a number and returns the result:
Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com