Date post: | 09-Apr-2018 |
Category: |
Documents |
Upload: | singaravelan-senthilkarasu |
View: | 229 times |
Download: | 0 times |
of 52
8/8/2019 SEG4530 VBScript Tutorial
1/52
VBScript Tutorial
What Is VBScript?Microsoft Visual Basic Scripting Edition, the newest member of the Visual Basicfamily of programming languages, brings active scripting to a wide variety of
environments, including Web client scripting in Microsoft Internet Explorer and Webserver scripting in Microsoft Internet Information Server.
Since VBScript is interpreted, there must be another program that provides the
interpretation service for it. With VBScript, this program is called the 'host'. So,technically, VBScript is three different languages because what it can do depends
entirely on what the host supports. (Microsoft makes sure that they are virtually
identical, however.) WSH is the host for VBScript that works directly in Windows.
VBScript "Hosts"if you're just learning about VBScript, it can be kind of confusing to figure out where
it "fits in" in the Microsoft world. For one thing, Microsoft currently offers threedifferent 'host' for VBScript.
Microsoft provides three 'host' environments for VBScript:
IE (Internet Explorer) - Microsoft's web browser software
IIS (Internet Information Server) - Microsoft's web server software
WSH (Windows Script Host) - A 'host' environment in the Windows
operating system
Another point of confusion is that there are three versions of WSH and twoimplementations. Windows 98 and Windows NT 4 implemented version 1.0. Version
2.0 was released with Windows 2000 and the current version is numbered 5.6.The two implementations are one that works from a DOS command line (called"CScript" for Command Script) and one that works in Windows (called "WScript").
You can use CScript only in a DOS command window, but it's interesting to note thatmuch of the real world computer systems administration still works that way. It
might also be confusing to discover that the WScript object is essential to a lot ofcode that is normally run in CScript. The example shown later uses the WScript
object, but you can run it with CScript. Just accept it as maybe being slightly odd,but that's the way it works.
If WSH is installed, you can run a VBScript program by simply double-clicking on any
file that has the vbs extension and that file will be executed by WSH. Or, for evenmore convenience, you can schedule when a script will run with Windows Task
Scheduler. In partnership with Task Scheduler, Windows can run WSH and a scriptautomatically. For example, when Windows starts, or every day at a particular time.
8/8/2019 SEG4530 VBScript Tutorial
2/52
Introducing WSH
The WSH Environment
Features of WSH
Types of Script Files
WSH is not a single file it is a set of components that you can use to run scripts.
These components are present whether you use the Windows Script Hostenvironment or other script environments, such as Microsoft Windows 2000 Internet
Information Services (IIS). Script files can be run in the WSH environment, whetherthe script is written in Visual Basic Scripting Edition or Microsoft JScript. WSH is
supported on all of the Windows 32-bit operating systems, such as MicrosoftWindows 95, Microsoft Windows 98, Microsoft Windows Millennium Edition (Me),
Microsoft Windows NT version 4.0, and Windows 2000. WSH version 1.0 shippedwith Windows 98 (Version 1.0). You can download version 2.0 of WSH, and you can
install it on any of these operating systems.
WSH has several components. These components work together to provide the
operating system with the ability to run and interoperate with scripts.
Script EnginesThe WSH environment natively supports two scripting languages: Visual Basic
Scripting Edition and JScript. After the scripting host determines the language usedin your scripts, it loads the appropriate script engine and passes your script to it for
execution. WSH includes two different script engines, one for VBScript and one for
JScript, to run scripts that you write in these languages.
Features of WSH
Small Memory Footprint Language-Independent
can extend it to other script engines
Script Reuse
Command-Line Reference
WSH is ideal for non-interactive scripting needs, such as batch, logon, and
administrative scripting. In addition to non-interactive processing, WSH scripts can
involve some degree of user interaction, such as confirming prompts and enteringvariable information.
Small Memory FootprintThe low system overhead of running scripts with WSH makes it ideal for your
administrative scripts.Language-IndependentAlthough WSH natively supports the Visual Basic Scripting Edition and Jscriptlanguages, you can extend the environment so that it can run scripts written in other
languages, such as PerlScript.
Script ReuseBy using WSH, you can save your scripts as operating system files. The content of
your script files is plain text. Therefore, you can write and save your script files by
8/8/2019 SEG4530 VBScript Tutorial
3/52
using a simple text editor such as Notepad. After you save the script files, you canrun your scripts many times; you do not need to rewrite code every time you want
to run a certain set of actions. This is a useful feature if you have scripts that mustbe run on a regular basis.
Command-Line ReferencePrior to WSH, the only native script language that the Windows operating systemsupported was the command language supported though Cmd.exe.
Administrators often construct batch files (.bat) that contain multiple commands.
These commands are still supported and are an important part of the administratorstoolset.
An example for how to write a html page using vbscriptExercise 1
Working With VBScript
MsgBox "Welcome to my Web page!"
Exercise 2
Test Button Events
MsgBox "Button Pressed!"
Exercise 3
Working With VBScript: Exercise 1
8/8/2019 SEG4530 VBScript Tutorial
4/52
Your First VBScript Exercise
By utilizing VBScript you can give your web pages actions.
Click on the button below to see what we mean.
An example for how to write a VBS FileStep 1:-create a file with .vbs extensionMsgBox "Welcome to my Web page!"
VBScript Variables
Data and Logic Literals
Constants
Variables
Explicit and Implicit Declaration
Operators
Logical Comparison
What is a Literal? Any Static (unchanged) Value thats typed directly into a script.
String values go in double-quotes.
Hexadecimal values start with &H.
What is a Variable?A variable is a "container" for information you want to store. A variable's value canchange during the script.
You can refer to a variable by name to see its value or to change its value. InVBScript, all variables are of type variant, which can store different types of data.Rules for Variable Names:
Must begin with a letter
Cannot contain a period (.)
Cannot exceed 255 characters
Declaring VariablesYou can declare variables with the Dim, Public or the Private statement. Like this:
Dim name
Name = some value
8/8/2019 SEG4530 VBScript Tutorial
5/52
Sub cmdVariables_OnClick
Dim Name
Name = InputBox("Enter your name: ")
MsgBox "The name you entered was " & Name
End Sub
Now you have created a variable. The name of the variable is "name". You can also
declare variables by using its name in your script. Like this:
Name = some value
Now you have also created a variable. The name of the variable is "name".However, the last method is not a good practice, because you can misspell the
variable name later in your script, and that can cause strange results when your
script is running. This is because when you misspell for example the "name" variableto "nime" the script will automatically create a new variable called "nime". To
prevent your script from doing this you can use the Option Explicit statement. When
you use this statement you will have to declare all your variables with the dim, publicor private statement. Put the Option Explicit statement on the top of your script. Like
this:
Option explicit
Dim name
Name = some value
Assigning Values to Variables
You assign a value to a variable like this:Name=Hege
i=200
The variable name is on the left side of the expression and the value you want toassign to the variable is on the right. Now the variable "name" has the value "Hege".
Example using HTML
Working With VBScript: Exercise 1
Your First VBScript Exercise
8/8/2019 SEG4530 VBScript Tutorial
6/52
By utilizing VBScript you can give your web pages actions.
Click on the button below to see what we mean.
Example using Application(.VBS)
Dim Name
Name = InputBox("Enter your name: ")
MsgBox "The name you entered was " & Name
Example to calculate unit price using HTML
Working With VBScript: Exercise 2
8/8/2019 SEG4530 VBScript Tutorial
7/52
Your Second VBScript Exercise
Variables can be used to store and manipulate values. To see a demonstration
of this enter a quantity and unit price in the fields below and click the
"Calculate Cost" button.
Quantity:
Unit price:
Example to calculate unit price using Application(.VBS)
Dim AmountofTax
Dim CRLF
Dim Message
Dim Subtotal
Dim TABSPACE
Dim TAX_RATEDim txtQuantity
Dim txtUnitPrice
Dim TotalCost
Sub cmdCalculate
' Define our constant values.
TAX_RATE = 0.06
CRLF = Chr(13) & Chr(10)
TABSPACE = Chr(9)
' Perform order calculations.Subtotal = txtQuantity * txtUnitPrice
AmountofTax = Subtotal * TAX_RATE
TotalCost = Subtotal + AmountofTax
' Display the results.
Message = "The total for your order is:"
Message = Message & CRLF & CRLF
Message = Message & "Subtotal:" & TABSPACE & "Rs " & Subtotal & CRLF
Message = Message & "Tax:" & TABSPACE & "Rs " & AmountofTax & CRLF
8/8/2019 SEG4530 VBScript Tutorial
8/52
Message = Message & "Total:" & TABSPACE & "Rs " & TotalCost
MsgBox Message,,"Your Total"
End Sub
txtQuantity= InputBox("Enter quantity: ")
txtUnitPrice= InputBox("Enter quantity: ")
cmdCalculate
Lifetime of VariablesHow long a variable exists is its lifetime.When you declare a variable within a procedure, the variable can only be accessed
within that procedure. When the procedure exits, the variable is destroyed. Thesevariables are called local variables. You can have local variables with the same name
in different procedures, because each is recognized only by the procedure in which itis declared.If you declare a variable outside a procedure, all the procedures on your
page can access it.
The lifetime of these variables starts when they are declared, and ends when the
page is closed.
Array VariablesSometimes you want to assign more than one value to a single variable. Then you
can create a variable that can contain a series of values. This is called an arrayvariable. The declaration of an array variable uses parentheses ( ) following the
variable name. In the following example, an array containing 3 elements is declared:Dim names(2)
The number shown in the parentheses is 2. We start at zero so this array contains 3
elements. This is a fixed-size array. You assign data to each of the elements of thearray like this:
names(0)=Tove
names(1)=Jani
names(2)=Stale
Similarly, the data can be retrieved from any element using the index of theparticular array element you want. Like this:
Mother=names(0)
You can have up to 60 dimensions in an array. Multiple dimensions are declared by
separating the numbers in the parentheses with commas. Here we have a two-
dimensional array consisting of 5 rows and 7 columns:Dim table(4,6)
Example of how to use arrays using HTML
Working With VBScript
8/8/2019 SEG4530 VBScript Tutorial
9/52
Dim famname(5)
famname(0) = "Jan Egil"
famname(1) = "Tove"
famname(2) = "Hege"
famname(3) = "Stave"
famname(4) = "Kai Jim"
famname(5) = 99+2
for i = 0 to 5
document.write(famname(i) & "
")
next
document.write( "
")
dim v(1,1)
v(0,0) = "Daniel"
v(0,1) = "Ben"
v(1,0) = "Roger"
v(1,1) = 25
document.write(v(0,0) & "
")
document.write(v(0,1) & "
")
document.write(v(1,0) & "
")
document.write(v(1,1) +1 & "
")
Creating Dynamic Arrays
*************************************************************
**********Script Name: cre_dyn_arrays.vbs
Author: BitCreated: 01/17/2003
Description: A demonstration of how to resize an array
*************************************************************
**********Initialization Section
Option Explicit
Dim strMessage, astrCustomerList, i
strMessage = Dynamic Array Demonstration & vbCrLf & vbCrLf
Main Processing Section
DimTheArray()
ReDimTheArray()
DisplayResults()Procedure Section
Function DimTheArray()
ReDim astrCustomerList(2)
astrCustomerList(0) = XYZ Corp.
astrCustomerList(1) = ABC Co.
astrCustomerList(2) = Acme Inc.
End Function
Function ReDimTheArray()
8/8/2019 SEG4530 VBScript Tutorial
10/52
8/8/2019 SEG4530 VBScript Tutorial
11/52
some statement
end sub
A Function procedure: is a series of statements, enclosed by the Function and End Function
statements
can perform actions and can return a value
can take arguments that are passed to it by a calling procedure
without arguments, must include an empty set of parentheses ()
returns a value by assigning a value to its name
Function myfunction()
Some statements
Myfunction=some value
End function
Or
Function myfunction(argument1,argument2)
Some statements
Myfunction=some value
End function
Call a Sub or Function ProcedureWhen you call a Function in your code, you do like this:name=findname()
Here you call a Function called "findname", the Function returns a value that will be
stored in the variable "name".Or, you can do like this: Here you also call a Function called "findname", the
Function returns a value that will be displayed in the message box.Msgbox your name is & findname()
When you call a Sub procedure you can use the Call statement, like this:Call myproc(argument)
Or, you can omit the Call statement, like this:Myproc argument
8/8/2019 SEG4530 VBScript Tutorial
12/52
VBScript Conditional Statements
Conditional StatementsVery often when you write code, you want to perform different actions for differentdecisions. You can use conditional statements in your code to do this.
In VBScript we have three conditional statements: if...then...else statement - use this statement if you want to selectone of two sets of lines to execute
if...then...elseif statement - use this statement if you want to selectone of many sets of lines to execute
select case statement - use this statement if you want to select one of
many sets of lines to execute
If....Then.....ElseYou should use the If...Then...Else statement if you want to
execute some code if a condition is true
select one of two blocks of code to execute If you want to execute
only one statement when a condition is true, you can write the codeon one line:If 1=10 Then msgbox Hello
There is no ..else.. in this syntax. You just tell the code to perform one action if the
condition is true (in this case if i=10).If you want to execute more than one statement when a condition is true, you must
put each statement on separate lines and end the statement with the keyword "EndIf":If 1=10 Then
msgbox Hello
i=i+1
end if
There is no ..else.. in this syntax either. You just tell the code to perform multiple
actions if the condition is true.If you want to execute a statement if a condition is true and execute another
statement if the condition is not true, you must add the "Else" keyword:If 1=10 Then
msgbox Hello
else
msgbox Good bye
end if
The first block of code will be executed if the condition is true, and the other blockwill be executed otherwise (if i is not equal to 10).
A Web page that uses the IfThen control structure.
Bharathi Info Tech-VBScript - If-Then Sample
8/8/2019 SEG4530 VBScript Tutorial
13/52
If....Then.....ElseifYou can use the if...then...elseif statement if you want to select one of many blocks
of code to execute:If payment=cash Then
Msgbox You are going to pay cash
else If payment=visa Then
Msgbox You are going to pay with visa
else If payment=Amex Then
Msgbox You are going to pay with American express
else
Msgbox Unknown method of payment
end if
8/8/2019 SEG4530 VBScript Tutorial
14/52
Select CaseYou can also use the SELECT statement if you want to select one of many blocks ofcode to execute:Select case payment
case cash
msgbox You are going to pay by Cashcase visa
msgbox You are going to pay with Visa
case Amex
msgbox You are going to pay with American Express
case else
msgbox Unknown method of payment
end select
This is how it works: First we have a single expression (most often a variable), thatis evaluated once. The value of the expression is then compared with the values for
each Case in the structure. If there is a match, the block of code associated with thatCase is executed.
A Web page that uses the Select control structure.
Select Case Sample
8/8/2019 SEG4530 VBScript Tutorial
15/52
8/8/2019 SEG4530 VBScript Tutorial
16/52
VBScript Looping Statements
Looping StatementsVery often when you write code, you want to allow the same block of code to run a
number of times. You can use looping statements in your code to do this.
In VBScript we have four looping statements: For...Next statement - runs statements a specified number of times.
For Each...Next statement - runs statements for each item in acollection or each element of an array
Do...Loop statement - loops while or until a condition is true
While...Wend statement - Do not use it -use the Do...Loop statement
instead
For...NextYou can use a For... Next statement to run a block of code, when you know how
many repetitions you want.You can use a counter variable that increases or decreases with each repetition of
the loop, like this:
for i=1 to 10
Some code
Next
The For statement specifies the counter variable (i) and its start and end values. TheNext statement increases the counter variable (i) by one. Step Keyword Using the
Step keyword, you can increase or decrease the counter variable by the value youspecify.
In the example below, the counter variable (i) is increased by two each time the looprepeats.for i=1 to 10 step 2
Some code
Next
To decrease the counter variable, you must use a negative Step value. You mustspecify an end value that is less than the start value.
In the example below, the counter variable (i) is decreased by two each time the
loop repeats.for i=10 to 2 step -2
Some code
Next
Using the ForNext statement in a Web page.
8/8/2019 SEG4530 VBScript Tutorial
17/52
Exit a For...NextYou can exit a For...Next statement with the Exit For keyword.
Using the ForNext statement in a Web page with additional error-checking to
prevent a divide-by-zero error.
8/8/2019 SEG4530 VBScript Tutorial
18/52
Dim Score
Dim i
Score = CSng(txtScore.Value)
If Count > 9 Then
MsgBox "You can only enter up to 10 scores. Click the Finished
button to calculate the average."
Else
Scores(Count) = Score
Count = Count + 1
txtScore.Value = ""
End If
End Sub
Sub cmdFinished_OnClick()
Dim Average
Dim Sum
Dim i
If Count = 0 Then
MsgBox "You must enter some scores before they can be averaged."
Exit Sub
End If
For i = 0 to Count-1
Sum = Sum + Scores(i)
Next
Average = Sum / CounttxtAverage.Value = Average
Count = 0
End Sub
-->
For Each...NextA For Each...Next loop repeats a block of code for each item in a collection, or for
each element of an array.The For Each...Next statement looks almost identical to the For...Next statement.
The difference is that you do not have to specify the number of items you want to
loop through.Dim names(2)
names(0)=Tove
names(1)=Jani
names(2)=Stale
for each x in names
8/8/2019 SEG4530 VBScript Tutorial
19/52
document.write(x &
)
next
Do...LoopYou can use Do...Loop statements to run a block of code when you do not know how
many repetitions you want. The block of code is repeated while a condition is true or
until a condition becomes true.
Repeating Code While a Condition is TrueYou use the While keyword to check a condition in a Do...Loop statement.
Do while i>10
Some code
Loop
If i equals 9, the code inside the loop above will never be executed.
Do
Some codeLoop while i>10
The code inside this loop will be executed at least one time, even if i is less than 10.
Repeating
A Web page that uses the Do WhileLoop structure.
8/8/2019 SEG4530 VBScript Tutorial
20/52
txtAverage.Value = Average
Count = 0
End Sub
-->
A Web page that uses the DoLoop While structure.
Code Until a Condition Becomes True
You use the Until keyword to check a condition in a Do...Loop statement.Do until i=10Some code
Loop
If i equals 10, the code inside the loop will never be executed.Do
Some code
8/8/2019 SEG4530 VBScript Tutorial
21/52
Loop until i=10
The code inside this loop will be executed at least one time, even if i is equal to 10.
Exit a Do...LoopYou can exit a Do...Loop statement with the Exit Do keyword.Do until i=10
i=i-1
if i
8/8/2019 SEG4530 VBScript Tutorial
22/52
A Web page that uses the DoLoop Until structure.
WhileWendThe While...Wend statement can be used to create a loop that executes as long as acondition remains true. The syntax for this statement is outlined below.
While condition
statements
Wend
condition is an expression that is being tested, and statements represents VBScript
statements that will be executed during each iteration of the loop. The While...Wendstatement is provided for backward compatibility purposes. Its continued use is
discouraged. Its functionality is duplicated by the Do...While and Do...Untilstatements, which are more flexible in their application.
A Web page that uses the WhileWend Until structure.
Script 3.3 - A While...Wend example
8/8/2019 SEG4530 VBScript Tutorial
23/52
Dim intCounter, strDisplayString
intCounter = 1
strDisplayString = Watch me count to 10 & vbCrLf & vbCrLf
While intCounter
8/8/2019 SEG4530 VBScript Tutorial
24/52
Oct Returns the octal value of a specified number
Example of CInt function:
The CInt function converts an expression to a variant of subtype Integer.
Note: The value must be a number between -32768 and 32767. Syntax
Cint(expression)Parameter Description
Expression Required. Any valid expression
Example 1Dim a
A=134.345
Document.write(Cint (a))
Output:
134
Example 2Dim a
A=-30000.24
Document.write(Cint (a))
Output:
-30000
Math FunctionsFunction Description
Abs Returns the absolute value of a specified number
Atn Returns the arctangent of a specified number
Cos Returns the cosine of a specified number (angle)Exp Returns e raised to a power
Hex Returns the hexadecimal value of a specified number
Int Returns the integer part of a specified number
Fix Returns the integer part of a specified number
Log Returns the natural logarithm of a specified number
Oct Returns the octal value of a specified number
RndReturns a random number less than 1 but greater or equal
to 0
SgnReturns an integer that indicates the sign of a specified
number
Sin Returns the sine of a specified number (angle)
Sqr Returns the square root of a specified numberTan Returns the tangent of a specified number (angle)
8/8/2019 SEG4530 VBScript Tutorial
25/52
Example of Rnd function:The Rnd function returns a random number. The number is always less than 1 butgreater or equal to 0.
SyntaxRnd[(number)]
Parameter Description
Number Optional. A valid numeric expression
If number is:0 Rnd returns the next number in the sequence
=0 Rnd returns the most recently generated numberNot supplied Rnd returns next random number in the sequence
Example 1Document.write(Rnd)
Output:
0.7055475
Example 2Randomize
Document.write(Rnd)
Output:
0.4758112
Example 3Here is how to produce random integers in a
given numder
Dim max,min
Max=100
Min=1
Document.write(Int((max-min+1)*Rnd+min))
Output:
71
String FunctionsFunction Description
InStrReturns the position of the first occurrence of one string
within another.
The search begins at the first character of the string
InStrRevReturns the position of the first occurrence of one stringwithin another.
The search begins at the last character of the string
LCase Converts a specified string to lowercase
LeftReturns a specified number of characters from the left sideof a string
Len Returns the number of characters in a stringLTrim Removes spaces on the left side of a string
RTrim Removes spaces on the right side of a string
TrimRemoves spaces on both the left and the right side of a
stringMid Returns a specified number of characters from a string
8/8/2019 SEG4530 VBScript Tutorial
26/52
ReplaceReplaces a specified part of a string with another string aspecified
number of times
RightReturns a specified number of characters from the right
side of a string
SpaceReturns a string that consists of a specified number of
spaces
StrCompCompares two strings and returns a value that represents
the result of
the comparison
StringReturns a string that contains a repeating character of aspecified length
StrReverse Reverses a stringUCase Converts a specified string to uppercase
Example of StrComp function:The StrComp function compares two strings and returns a value that represents theresult of the comparison.
The StrComp function can return the following values: If string1 < string2 - StrComp returns -1
If string1 = string2 - StrComp returns 0
If string1 > string2 - StrComp returns 1
If string1 or string2 is Null - StrComp returns Null
Syntax Example 1Strcomp(String1,string2[,compare])
Parameter Description
string1 Required. A string expression
string2 Required. A string expression
compare Optional. Specifies the string comparison to use. Default is 0
Can have one of the following values:
0 = vbBinaryCompare - Perform a binary comparison
1 = vbTextCompare - Perform a textual comparison
Example 1Document.write(strcomp(VBScript, VBScript))
Output: 0
Example 2Document.write(strcomp(VBScript, vbscript))
Output: -1
Example 3Document.write(strcomp(VBScript, vbscript,1))
Output: 0
8/8/2019 SEG4530 VBScript Tutorial
27/52
Controlling Variable Scope*************************************************************************
Script Name: Script 4.1.vbs
Author: Bit
Created: 01/04/2003
Description: This script demonstrates global and local variable scopes
*************************************************************************Initialization Section
Option Explicit
Dim X, Y
Main Processing Section
X = 10
GetNewNumber()
MsgBox X = & X & Y = & Y
Procedure Section
Function GetNewNumber()
Dim Y
Y = 20
End Function
*************************************************************************
Script Name: Script 5.5.vbs
Author: Bit
Created: 01/17/2003
Description: Resizing a dynamic array based on user input
*************************************************************************
Initialization Section
Option Explicit
Dim strUserInput, strMessage
ReDim astrCustomerList(0)
Main Processing Section
CollectInputData()
ProcessInputData()
Procedure Section
Function CollectInputData()
Dim i
i = 0
Do While UCase(strUserInput) QUIT
strUserInput = InputBox(Type a customer name)
If UCase(strUserInput) QUIT Then
astrCustomerList(i) = strUserInput
Else
Exit Do
End Ifi = i + 1
ReDim Preserve astrCustomerList(i)
Loop
End Function
Function ProcessInputData()
Dim i
i = 0
For Each i In astrCustomerList
8/8/2019 SEG4530 VBScript Tutorial
28/52
8/8/2019 SEG4530 VBScript Tutorial
29/52
character name.
Size. Retrieves a files or folders byte size.
SubFolders. Establishes a Folders collection consisting of all the folderslocated inside a specified folder.
TotalSize. Returns the total number of bytes left on a drive.
Type. Retrieves information about a files or folders type.
VolumeName. Retrieves or sets a drives volume name.
VBScript Runtime MethodsThe methods that belong to the VBScript runtime objects are listed here.
VBScript Run-time Methods
Add (Dictionary). Adds a key and item pair to a Dictionary object.
Add (Folders). Adds a Folder to a collection.
BuildPath. Appends a name to the path.
Close. Closes an open TextStream file.
Copy. Copies a file or folder.
CopyFile. Copies one or more files. CopyFolder. Recursively copies a folder.
CreateFolder. Creates a new folder.
CreateTextFile. Creates a file and a TextStream object that can be used to
read and write to the file.
Delete. Deletes a file or folder.
DeleteFile. Deletes a file.
DeleteFolder. Deletes a folders contents.
DriveExists. Returns either true or false depending on the existence of a
drive.
Exists. Returns either true or false depending on whether a key exists in
a Dictionary object.
FileExists. Returns either true or false depending on whether a file can be
found.
FolderExists. Returns a value of true or false depending on whether a folder
can be found.
GetAbsolutePathName. Returns a complete path name.
GetBaseName. Retrieves a filename less its file extension.
GetDrive. Returns the Drive object associated with the drive in the specified
path.
GetDriveName. Retrieves the name of a drive.
GetExtensionName. Retrieves a files extension.
GetFile. Retrieves a File object.
GetFileName. Retrieves the last filename or folder of the specified path.
GetFileVersion. Retrieves a files version number.
GetFolder. Retrieves the Folder object associated with the folder in the
specified path.
GetParentFolderName. Retrieves the name of the parent folder.
GetSpecialFolder. Retrieves a special folders name.
8/8/2019 SEG4530 VBScript Tutorial
30/52
GetTempName. Retrieves the name of a temporary file or folder.
Items. Returns an array containing the items in a Dictionary object.
Keys. Returns an array containing the keys in a Dictionary object.
Move. Moves a file or folder.
MoveFile. Moves one or more files.
MoveFolder. Moves one or more folders.
OpenAsTextStream. Opens a file and returns a TextStream object that can be
used to reference the file.
OpenTextFile. Opens a file and returns a TextStream object that can be used
to reference the file.
Read. Returns a string containing x number of characters from
a TextStream file.
ReadAll. Reads the whole TextStream file and returns its contents.
ReadLine. Reads a line in a TextStream file.
Remove. Deletes a Dictionary objects key, item pair.
Skip. Skips x number of character positions when processing
a TextStream file. SkipLine. Skips a line when processing a TextStream file.
Write. Places a string in the TextStream file.
WriteBlankLines. Writes x number of newline characters to
the TextStream file.
WriteLine. Writes a string in the TextStream file
Scripting related to File systemWorking with File SystemThe main runtime object is the FileSystemObject from which all other runtime
objects are derived (except for the dictionary object, which is independent of
the FileSystemObject). lists of VBScript runtime objects.FileSystemObject
Object Access Provided
Drive Disk drive properties
Drives Collection System drive information
File File properties
Files Collection All files contained in the
specified folder
Folder Folder properties
Folders Collection All folders contained in thespecified folder
To use the FileSystemObject within your VBScripts you must first establish aninstance of it. You can do this using the WScript objects CreateObject() method and
by referencing it as Scripting. FileSystemObject. This is demonstrated in thefollowing example.Set fsoObject = WScript.CreateObject ("Scripting.FileSystemObject")
Here fsoObject is just the name that I assigned to a variable that can now be used
by the rest of the script to reference the properties and methods ofthe FileSystemObject. With this instance of the FileSystemObject now established the
script is read to interact with the Windows file system.Lets put this
8/8/2019 SEG4530 VBScript Tutorial
31/52
previous FileSystemObject example to work in a few quick examples to see how itreally works.
Displaying Drive Free SpaceThis first example demonstrates how to use a number of methods and properties of
the VBScript runtime objects to access drive information. Specifically the exampleshown here displays the amount of free space on a computers C: and D: drives.
' * Script Name: Script 5.vbs *Option Explicit
On Error Resume Nextdim fsoObject, drive1, drive2
set fsoObject = WScript.CreateObject("Scripting.FileSystemObject")
set drive1 = fsoObject.GetDrive(fsoObject.GetDriveName("c:"))
set drive2 = fsoObject.GetDrive(fsoObject.GetDriveName("d:"))
' ********* Main processing section **********' Call a function that displays drive information
Free_Space()
' *********** Procedures go here *************' This function displays the amount of free space on drive 1 and drive 2
Function Free_Space()
WScript.Echo( "Free Space on drive 1 is: " _
& FormatNumber(drive1.FreeSpace / 1024 , 0) & " KB")
WScript.Echo( "Free Space on drive 2 is: " _
& FormatNumber(drive2.FreeSpace / 1024 , 0) & " KB")
End Function
The script begins by defining three variables. The first variable is fsoObject. It will beused to create an instance of the FileSystemObject as discussed earlier. The next two
variables will be used to set up references to the computers C: and D: drives. Thetwo statements that set up the values of these two variables for the computers
drives probably look a little complex to you at first. So lets take a moment andbreak them down. First, the GetDriveName() method of the FileSystemObject is used
by appending it to the variable fsoObject (for example, fsoObject.GetDriveName()).Remember that the fsoObject variable provides the script with a reference to
the FileSystemObject and its properties and methods. The GetDriveName() methodreturns the name of the drive associated with the specified driver letter (that
is, C: or D:).Next, the FileSystemObject objects GetDrive() method is used to retrieve
the Drive object associated with the specified drive name. The reason that we need
to establish a reference to the Drive object is because we are going to want to useitsFreespace property a little later in the script. After executing the statements in the
scripts initialization section, the VBScript statement in the main processing section
executes. There is only one VBScript statement in this section and it calls a function
named Display_Msg(). The function then executes. Its job is to display the amount offree space on each drive. This is accomplished by taking the amount of free spaceleft on a given drive as contained by the Drive objects FreeSpaceproperty and
dividing it by 1024 (1 kilobyte or 1 KB). The results are then formatted usingthe Driveobjects FormatNumber() method, which in this case formats the number
with zero trailing decimal spaces (that is, as whole number).When I ran this script onmy computer, I got the following results.C:\>CScript "Script 5.vbs"
8/8/2019 SEG4530 VBScript Tutorial
32/52
Microsoft (R) Windows Script Host Version 5.6
Copyright (C) Microsoft Corporation 1996-2001. All rights reserved.
Free Space on drive 1 is: 11,116 KB
Free Space on drive 2 is: 15,784 KB
C:\>
Examining File System Types
Lets look at another example of how to work with the methods and properties of the
VBScript runtime objects. This time well write a VBScript example that displays thetype of file system that the computers C: and D: drives have been formatted with.' * Script Name: Script 6.vbs*
Option Explicit
On Error Resume Next
dim fsoObject, drive1, drive2
set fsoObject = WScript.CreateObject("Scripting.FileSystemObject")
set drive1 = fsoObject.GetDrive("C:")
set drive2 = fsoObject.GetDrive("D:")
' ********* Main processing section **********
' Call a function that displays drive information
Used_Disk()
' *********** Procedures go here *************
' This function displays the file system used to format drive 1 and drive 2
Function Used_Disk()
WScript.Echo("The file system used on drive 1 is: " & drive1.FileSystem)
WScript.Echo("The file system used on drive 2 is: " & drive2.FileSystem)
End Function
As you can see this VBScript is similar to the previous example. The same variables
are defined in the initialization section. In addition, the same instance ofthe FileSystemObject is set up and once again its GetDrive() method is used toretrieve Drive object references to each drive on the computer.Next, a single
VBScript statement in the main processing section calls a function that displays a filesystem type for each drive.
This is accomplished by using Drive objects FileSystemproperty.When I ran thisscript on my computer I received the following results.C:\>CScript "Script 6.vbs"
8/8/2019 SEG4530 VBScript Tutorial
33/52
Microsoft (R) Windows Script Host Version 5.6
Copyright (C) Microsoft Corporation 1996-2001. All rights reserved.
The file system used on drive 1 is: NTFS
The file system used on drive 2 is: NTFS
C:\>
Examining File PropertiesLets look at one final example before we rush off and begin to master the art ofreading from and writing to text files. This example starts off like the previous two
examples by defining its variables and instantiating an instance of
the FileSystemObject. This time the FileSystemObject objectsGetFile() method isused. This method is used to retrieve the File object associated with the specified
file, which in this example is c:\winzip.log.Again, a VBScript statement in the mainprocessing section calls on a function named Display_Msg(). The function contains a
number ofWScript.Echo statements each of which displays a different propertyassociated with the Fileobject.
' ********************************************
' * Script Name: Script 7.vbs *
' * Author: Bit*
' * Created: 03/02/08 *
' ********************************************
' **** Perform script initialization here ****
Option Explicit
On Error Resume Next
dim fsoObject, targetFile
set fsoObject = WScript.CreateObject("Scripting.FileSystemObject")
set targetFile = fsoObject.GetFile("d:\Test.vbs")
' ********* Main processing section **********
' Call a function that displays drive information
Details()
' *********** Procedures go here *************
' This function displays file properties
Function Details()
WScript.Echo("File properties of d:\Test.vbs")
8/8/2019 SEG4530 VBScript Tutorial
34/52
WScript.Echo("-----------------------------------")
WScript.Echo("Created on: " & targetFile.DateCreated)
WScript.Echo("Last Modified: " & targetFile.DateLastModified)
WScript.Echo("Last Accessed: " & targetFile.DateLastAccessed)
WScript.Echo("File Name: " & targetFile.Name)
WScript.Echo("File Path: " & targetFile.Path)
WScript.Echo("File Type: " & targetFile.Type)
WScript.Echo("File Size: " & targetFile.Size)
End Function
The following output was displayed when I ran this script.C:\>CScript "Script 7.vbs"
Microsoft (R) Windows Script Host Version 5.6
Copyright (C) Microsoft Corporation 1996-2001. All rights reserved.
File properties of d:\Test.vbs
-----------------------------------
Created on: 2/4/2008 11:23:36 PM
Last Modified: 2/4/2008 10:38:52 AM
Last Accessed: 2/4/2008
File Name: Test.vbs
File Path: D:\Test.vbs
File Type: VBScript Script File
File Size: 1081
C:\>
Creating Documents, Reports, and LogsBy this point you should have a fairly good
understanding of what the VBScript runtime objects are and what they can do. Nowlets look at how you can use them to generate reports, logs, and other types of text
documents.To work with files and their contents you must first establish an instanceof the FileSystemObject within your VBScript as shown here.set fsoObject = WScript.CreateObject("Scripting.FileSystemObject")
Next, you should always check to see if the file that you want to work with already
exists. If it does, you can open it. If it does not already exist, you can create it andthen open it. You can check to see if a file exists using
the FileSystemObject objects FileExists property as shown here.If (fsoObject.FileExists("C:\displayText.txt" ) ) Then
8/8/2019 SEG4530 VBScript Tutorial
35/52
You must open a file before you can work with it. You can usethe FileSystemObject objectsOpenTextFile() method to open files. To use this
method you need to supply a few pieces of information including the following.
The name and path of the file to be opened
Whether you want the file to be opened for reading, writing, orappending
Whether to create the file if it does not existTable defines constantsthat are used to tell the OpenTextFile() method what you want to do
once the file is opened.
OpenTextFile() Constants
Constant Description Value
ForReading Opens a file for reading1
ForWriting Opens a file for writing 2
ForAppending Opens a file for appending
8
Table defines two options that govern what the OpenTextFile() method should do
when the file to be opened does and does not exist.
Table : OpenTextFile() File Creation Options
Value Description
True Open the file if it exists,otherwise create and open it
False Open the file if it exists,
otherwise do not create it
Opening and Closing FilesIt is very important that you correctly specify the type of operation that you are
opening a file for (reading, writing, or appending). If you open a file to write to it andthe file exists, then the file will be reinitialized. In other words, any data that is
already in the file is lost and the file pointer is placed at the beginning of the new file
(in the first row and column of the file).By appending to a file, you are able topreserve its contents and add to it. In other words, the file is opened and the file
pointer is placed at the end of the file in the last row and column position.The filepointer is used to identify where the next character of data will be placed with a file.
In a newly initialized file, the pointer would automatically be positioned in the upper-left corner (row 0, column 0). If one new character of information were added, the
pointer would be moved over one position to column 1 in row 0. If a carriage returnwere added (indicating an end-of-line marker), then the file pointer would move to
column 0 row 1. Knowing the location of the file pointer and how it is moved aroundis important, especially if you will be writing to or reading from files that have fixed
record formats with data fields starting and ending in specified columnpositions. Okay, enough about the file pointer. Lets look at an example that ties
together everything that we have talked about. In this example, Ive written aVBScript that opens a file named myFile.txt, which resides in the root directory of
myC: drive. If the file already exists, then the script opens it but if it does notalready exist it will be created and opened.' * Script Name: Script 8.vbs *
Option Explicit
On Error Resume Next
8/8/2019 SEG4530 VBScript Tutorial
36/52
Dim fsoObject, open_File, target_File
Set fsoObject = WScript.CreateObject("Scripting.FileSystemObject")
target_File = "D:\ displayText.txt"
' ********* Main processing section **********
' Call a function that displays drive information
Open_File()
open_File.WriteLine "This line of data should be written to the text file."
Close_File()
' *********** Procedures go here *************
' This function opens a file
Function Open_File()
If (fsoObject.FileExists(target_File ) ) Then
Set open_File = fsoObject.OpenTextFile(target_File, 8 )
Else
Set open_File = fsoObject.OpenTextFile(target_File, 2, "True" )
End If
End Function
' This function closes a file
Function Close_File()
open_File.Close()
End Function
The file is opened using the forWriting constant ( with a value of 2 ) if it alreadyexists. If the file does not exist, then the forAppending constant (with a value of 8 )
is specified to open the file and place the file pointer at the end of the file.If you take
at look at the scripts main processing section you will see the following statementbetween a pair of function calls, which open and close the file.
open_File.WriteLine "This line of data should be written to the text file."This statement writes one line of data to the file and executes a carriage return
placing the file pointer in the first column of the following line. Ill talk more aboutthe use of this and other methods that are used to write data to files in just a
bit. The last statement in the main processing section calls a function that executesthe following statement.open_File.Close()
This statement executed the FileSystemObject objects close() method i to close the
opened file. You must remember to close any file that you open before allowing your
8/8/2019 SEG4530 VBScript Tutorial
37/52
script to end. Failing to do so may cause an error the next time that you open the filebecause the end-of-file marker will not have been created.Run this script and open
the myFile.txt file and youll see the following line of data.This line of data should be written to the text file.
8/8/2019 SEG4530 VBScript Tutorial
38/52
Writing to Files
As you just learned, you should always check for the existence of a file before
creating it. Once opened, you have several different ways in which you can write textdata to your files.One option is to write a specific number of characters at a time.
This technique is best used when you need to write carefully formatted data to your
files such as when you write reports with data that appears in columns. Anotheroption for writing to a file is to write an entire line of data at a time. This technique isbest used when your documents are more free-formed and is probably the option
that youll use most often, especially if you plan to create log files in which yourecord error messages and other types of event information as your scripts
execute.Finally, you might want to add blank lines to your files. Blank lines areespecially useful for formatting your documents to improve their presentation and
make them easier to read.
Adding Characters to a FileYou can write a specific number of characters to a file at a time using
the FileSystemObject objectsWrite() method. This method does not automaticallyappend a carriage return at the end of each write operation. Therefore, the next time
a write operation occurs additional text is inserted immediately following the textwritten by the previous write operation.The following example demonstrates how you
can use the Write() method to append text to an existing file.Set fsoObject = WScript.CreateObject("Scripting.FileSystemObject")
Set open_file = fsoObject.OpenTextFile("d:\ displayText.txt", 8 )
open_file.Write("Welcome to ")
open_file.Write("KR Testing Solutions!")
open_file.Close()
As you can see even though two separate write operations occurred, the text for
both write operations was placed on the same line.Adding a Line to a FileBy replacing the Write() method with
the FileSystemObject objects WriteLine() method in the previous example, you can
change the previous script to write data to the file a line at a time.Set fsoObject = WScript.CreateObject("Scripting.FileSystemObject")
Set open_file = fsoObject.OpenTextFile("d:\ displayText.txt", 8 )
open_file.WriteLine("Welcome to KR Testing Solutions!")
open_file.Close()
The WriteLine() method automatically adds a carriage return to the end of each line
returning the file pointer to the first column of the next line.Adding Blank Lines to a FileIf you want to format your text files with blank lines to create better looking reports
or make them easier to read you can usethe FileSystemObject objects WriteBlankLines() method. When executed, this
method writes a blank line to the file and executes a carriage return.The followingexample demonstrates how to use the WriteBlankLines() method to format the data
in a small report.Set fsoObject = WScript.CreateObject("Scripting.FileSystemObject")
8/8/2019 SEG4530 VBScript Tutorial
39/52
Set myCDrive = fsoObject.GetDrive("d:")
Set open_file = fsoObject.OpenTextFile("d:\ displayText.txt", 8 )
open_file.WriteLine("------------------------------")
open_file.WriteBlankLines(1)
open_file.WriteLine(" My d: Drive Report ")
open_file.WriteBlankLines(1)
open_file.WriteLine("------------------------------")
open_file.WriteBlankLines(2)
open_file.WriteLine("File System - " & myCDrive.FileSystem)
open_file.WriteLine("Total Size - " & myCDrive.TotalSize)
open_file.WriteLine("Free Space - " & myCDrive.AvailableSpace)
open_file.Close()Reading from Files
Reading the contents of a file is handled in much the same way as writing to it. First,be sure that the file exists. If it does, then your script may open it. The next thing
your script should do is use the TextStream objects AtEndOfStream property to findout if the file has any data in it. After all, there is no point to trying to read an empty
file. In fact, you should check the value of theAtEndOfStream property just beforeeach read operation to be sure that your script has not reached the end of file
marker (e.g., the end of the file). The first thing that you need to do to begin readinga text file is create an instance of the FileSystemObject and then use
theFileSystemObject objects OpenTextFile() method as shown here.Set fsoObject = CreateObject("Scripting.FileSystemObject")
Set open_file = fsoObject.OpenTextFile("d:\ displayText.txt", 1 )
As you can see the forReading constant has been specified. Next you could set up aloop that runs until the AtEndOfStream property has a value of true (the end of the
file is reached). During each iteration of the loop your script should read a line of textusing the FileSystemObject objectsReadLine() method as shown here.Do while False = open_file.AtEndOfStream
WScript.Echo(open_file.ReadLine())
Loop
The preceding VBScript statements will process every line in the file, terminating
when the end of file marker is reached. After your script is done reading the file, itcan close it as shown here.open_file.Close
If you put these lines of code together and ran them as a script using the CScriptexecution host youd see output similar to the following.C:\>CScript test.vbs
8/8/2019 SEG4530 VBScript Tutorial
40/52
Microsoft (R) Windows Script Host Version 5.6
Copyright (C) Microsoft Corporation 1996-2001. All rights reserved.
------------------------------
My d: Drive Report
------------------------------
File System - NTFS
Total Size - 2146631554
Free Space - 234554452
C:\>
In this example we read an entire file by reading it one line at a time. There are anumber of other techniques for reading files. These include
Skipping lines when reading a file
Reading a specified number of characters from a file
Reading an entire file in one operation
Skipping Portions of a FileIf a file has headers or other information that you are not interested in reading you
can always skip them and read only the portion of the file that interests you. Forexample, the file that we have been working with contains a five-line header followed
by two blank lines after which the data in the report begins.You can use either of thefollowing methods, both of which belong to theFileSystemObject, to skip text in a
file.
Skip(). Skip a specific number of characters SkipLine(). Skips a lineThe Skip() method lets you supply a number
indicating how many characters should be skipped.
For example, the following statement would skip 25 characters in a file referencedas open_file.open_file.Skip(25)
Unfortunately, the SkipLine() method does not allow you to pass it a number,
indicating how many lines to skip. If you want to skip more than one line, you canwrap the method up inside a loop as demonstrated here.For i = 1 to 7open_file.SkipLine()Next
Here the first seven lines of the file referenced as open_file would be skipped.
Reading Formatted Data
If your file has been formatted to contain fixed length data, then you have the optionof reading it by character instead of by line. To do so you will use
the FileSystemObject objects Read()method.The following example demonstrateshow to use this method. Here a reference is set up for a file named myfile.txt. Then
a For loop is set up to skip the first seven lines of the file using
theSkipLine() method. Next the Skip() method is used to skip the first fourteencharacters on the eighth line. Finally the next four characters, beginning with the
twenty-third character are read and then displayed. Then the file is closed.Set fsoObject = CreateObject("Scripting.FileSystemObject")
8/8/2019 SEG4530 VBScript Tutorial
41/52
Set open_file = fsoObject.OpenTextFile("d:\ displayText.txt", 1 )
For i = 1 to 7
open_file.SkipLine()
Next
open_file.Skip(14)
WScript.Echo("The file system in use on this drive is: "
& open_file.Read(4))open_file.Close
Reading Entire FilesAnother way in which you can read files is to read the entire file all at once using
theFileSystemObject objects ReadAll() method as demonstrated in the following
example.Set fsoObject = CreateObject("Scripting.FileSystemObject")
Set open_file = fsoObject.OpenTextFile("d:\ displayText.txt", 1 )
read_rpt = open_file.ReadAll()open_file.Close()MsgBox(read_rpt)
In this example, the entire file is read using a single statement, which assigns thedata read by theReadAll() method to a variable named read_rpt. The file is then
closed and the value of read_rptdisplayed using the VBScript MsgBox() function.
Performing File and Folder AdministrationManaging your files and folders can involve a lot of work. Using VBScript and the
WSH you can automate much of this work. For example, typical file and folder tasksinvolve copying or moving files and folders from one location to another in order to
create backups or better organize them. Administration may also include deletingfiles once they have been processed or after they have reached a certain age.You
can use methods belonging to the FileSystemObject to manage one or more files orfolders at a time. FileSystemObject methods for handling files include
CopyFile(). Copies one or more files.
MoveFile(). Moves one or more files to a different location.
DeleteFile(). Delete one or more files.
FileExists(). Provides verification of whether a file contains data.
The FileSystemObject also provides a number of methods that youcan use to manage Windows folders, including
CopyFolder(). Copies one or more folders.
MoveFolder(). Moves one or more folders to a different location.
DeleteFolder(). Deletes one or more folders.
FolderExists(). Provides verification of whether a folder exists.
CreateFolder(). Creates a new folder.Alternatively, you can also use
the File and Folderobjects to manage your files and folders instead of
the FileSystemObject. These two objects share many of the samemethods, including
Copy(). Copies a file or folder to the specified location.
Delete(). Removes the specified file or folder.
Move(). Moves a file or folder to the specified location.
8/8/2019 SEG4530 VBScript Tutorial
42/52
FileSystemObject
Managing Files and FoldersAs you have already seen this afternoon the FileSystemObject is actually fairly easyto work with. All that you have to do is establish an instance of it and you can start
using its properties and methods. In the sections that follow youll see examples ofhow to use this object to create, copy, move, and delete files and folders.
Copying FilesUsing the FileSystemObject objects CopyFile() method you can copy one or more
files. For example, you might want to copy all the files in the folder on yourcomputer to a network drive at the end of each day. Ill show you how to work with
network drives this evening. For now lets just focus on how the CopyFile() method
works.The first step in copying a file is to set up an instance of theFileSystemObject.Then you can execute its CopyFile() method as shown here.Set fsoObject = CreateObject("Scripting.FileSystemObject")fsoObject.CopyFile("d:\ displayText.txt", "d:\myDocs\ displayText.txt")
In this example, a file named myFile.txt is copied from the root folder on the C: driveto a folder named myDocs located on the computers D: drive. You can modify this
example to copy more than one file using wildcard characters as shown in the next
example. Here all files in the root directly with a filename of myFile are copied to thedestination folder regardless of their file extension.Set fsoObject = CreateObject("Scripting.FileSystemObject")
fsoObject.CopyFile("d:\ displayText.*", "d:\Docs")
Moving FilesMoving files is similar to copying them except that instead of leaving the original file
in place and placing a duplicate copy in the destination location, the original file ismoved leaving only one copy of the file. You can move one or more files using
the FileSystemObject objects MoveFile()method.For example, you can move all fileswith a .txt file extension found in the root of the C:drive to a myDocs folder on
the D: drive using the following VBScript statements.Set fsoObject = CreateObject("Scripting.FileSystemObject")
fsoObject.MoveFile("c:\*.txt", "c:\Docs")
Deleting FilesYou can use the FileSystemObject objects DeleteFile() method to delete one or more
files. For example, you might want to write a script that cleans out a folder at theend of each day or that deletes files after reading and processing them. You can
delete one or more files as demonstrated here.Set fsoObject = CreateObject("Scripting.FileSystemObject")
fsoObject.DeleteFile("d:\*.txt")
Here all files that have a .txt file extension located in the root of the C: drive will be
deleted.
Creating a FolderWorking with folders is similar to working with files. You can use the FolderExists()
method of theFileSystemObject to determine if a folder exists. If the folder does not
exist, you can create it using the FileSystemObject objects CreateFolder() method asdemonstrated here.Set fsoObject = CreateObject("Scripting.FileSystemObject")
If (fsoObject.FolderExists("d:\Docs") = false) Then
Set myFolder = fsoObject.CreateFolder("d:\Docs")
End IfThe first thing that this example does is check to see if a foldernamed myDocs already exists on the computers D: drive. If it does not exist, then
8/8/2019 SEG4530 VBScript Tutorial
43/52
the folder is created. Otherwise nothing happens.
8/8/2019 SEG4530 VBScript Tutorial
44/52
Copying FoldersCopying a folder is pretty much the same as copying a file. The folder and all itscontents are copied to a new location leaving the original copy still in place. You can
copy folders using theFileSystemObject objects CopyFolder() method.Take a look atthe following example. It copies a folder named myDocs located on the
computers D: drive to its C: drive.
Set fsoObject = CreateObject("Scripting.FileSystemObject")fsoObject.CopyFolder("c:\Docs", "d:\Docs")
As you can see the CopyFolder() methods requires two arguments, the source and
destination folder names, including their complete paths. By changing the nameassigned to the destination folder, you can rename the folder as part of the copy
operation as demonstrated here.Set fsoObject = CreateObject("Scripting.FileSystemObject")
fsoObject.CopyFolder("c:\Docs", "d:\NewDocs")
If the destination folder already exists, then the contents of the source folder are
copied into it alongside its current contents. The CopyFolder() method supports anadditional third parameter that allows you to tell it what to do if the destination
folder contains files with duplicate filenames of those found in the source folder. Thisparameter is set to either a value of true or false. Setting it to true causes any
matching files to be overridden. Setting it to false prevents this from happening.Lets look at a couple examples. The first example prevents files with duplicate
filenames from being overridden.Set fsoObject = CreateObject("Scripting.FileSystemObject")
fsoObject.CopyFolder("c:\Docs", "d:\Docs", "False")
The second example allows files with duplicate names to be overridden in the
destination folder.Set fsoObject = CreateObject("Scripting.FileSystemObject")
fsoObject.CopyFolder("c:\Docs", "d:\Docs", "True")
Moving FoldersMoving a folder works pretty much the same as copying one except that moving the
folder leaves you with only the one copy. You can move folders using
the FileSystemObject objects MoveFolder()method. This method moves a folder andall its contents, including subfolders, to a new destination.For example, the followingVBScript statements move a folder called myDocs from the computers D: drive to
its C: drive.Set fsoObject = CreateObject("Scripting.FileSystemObject")
fsoObject.MoveFolder("c:\Docs", "d:\Docs")
If a folder with the same name already exists at the root of the computers D: drive,
then the contents of the source folder will be copied into the existing destinationalong side its current contents.
Deleting FoldersYou can delete one or more folders using
the FileSystemObject objects DeleteFolder() method. This method deletes a folder
and all its contents, including subfolders. For example, the following VBScript
statements can be used to delete a folder named myDocs located on acomputers D:drive.Set fsoObject = CreateObject("Scripting.FileSystemObject")
fsoObject.DeleteFolder("d:\Docs")
Managing Files with the File ObjectThe File Object allows you to work with one file at a time as opposed to
the FileSystemObject, which lets you manage multiple files. Using the File objectinstead of the FileSystemObject requires a little more work. You still have to create
an instance of the FileSystemObject to interact with the file system. You also need to
8/8/2019 SEG4530 VBScript Tutorial
45/52
use the FileSystemObject objects GetFile() method to retrieve a Fileobject thatrepresents the file that your script will be managing. Once these two things are set
up you can execute any of the File objects methods.
Copying a FileUsing the File objects Copy() method you can copy a file from one location to
another. This method does not support the use of wildcard characters and cannot
therefore be used to copy multiple files.The following example demonstrates how touse the File objects Copy() method to copy a file named myFile.txt fromthe myDocs folder on the computers D: drive to the root of the C: drive.Set fsoObject = CreateObject("Scripting.FileSystemObject")
Set source_file = fsoObject.GetFile("c:\Docs\ displayText.txt")
source_file.Copy("d:\")
In this example, the FileSystemObject objects GetFile() method is used to establish
a reference to the file that is to be copied. Then the Copy() method is used to set thedestination where the file is to be copied.
Moving a FileAs you probably expect by now, moving a file using the File objects Move() methodworks almost exactly like copying it using the Copy() method. For example, the
following VBScript statements demonstrate how to move a file from one location toanother.Set fsoObject = CreateObject("Scripting.FileSystemObject")
Set source_file = fsoObject.GetFile("c:\Docs\ displayText.txt")
source_file.Move("d:\")
Deleting a FileYou can delete an individual file using the File Objects Delete() method. Like
the File objects other methods, the Delete() method does not support wildcardcharacters limiting it to being able to delete just one file at a time.Take a look at the
following example. Here a file named myFile.txt is deleted from a foldernamed myDocs located on the computers D: drive.Set fsoObject = CreateObject("Scripting.FileSystemObject")Set source_file = fsoObject.GetFile("c:\Docs\ displayText.txt ")
source_file.Delete()Managing Folders with the Folder ObjectThe Folder object is similar to the File object only it works with one folder at a time
instead of one file at a time. Like the File object, it requires a little more work to setup than does simply using theFileSystemObject. First, youll need to instantiate
the FileSystemObject.
Then you must use theFileSystemObject objects GetFolder() method to retrievea Folder object that represents the folder that your script will be working with. Once
these two things are set up you can execute any of theFolder objects methods.
Copying a FolderLike the File object, the Folder object supports the Copy() method. Because itdoesnt support wildcard characters it is useful only when you want to work with a
single folder at a time. TheCopy() method copies the folder and all its contents,including any subfolders, to a new location.For example, the following VBScript
statements demonstrate how to use the Copy() method. In this case a foldernamed myDocs is copied from the root of the computers D: drive to the root of the
computers C: drive.Set fsoObject = CreateObject("Scripting.FileSystemObject")
Set source_folder = fsoObject.GetFolder("d:\Docs")
source_folder.Copy("c:\")
8/8/2019 SEG4530 VBScript Tutorial
46/52
Moving a FolderThe Folder objects Move() method lets you move a folder from one location toanother. This method recursively copies a folder and all its contents. Because it does
not support wildcard characters, this method can only move one folder at a time, asopposed to the FileSystemObjectobjects MoveFolder() method, which can move any
number of folders in a single operation.The following example demonstrates how touse this method to move a folder. In this case the folder is named myDocs and it is
moved from the computers D: drive to its C: drive.Set fsoObject = CreateObject("Scripting.FileSystemObject")
Set source_folder = fsoObject.GetFolder("d:\Docs")
source_folder.Move("c:\")
Deleting a FolderYou can delete a folder using the Folder objects Delete() method. Wildcard character
matching is not supported so it only works with one folder at a time.If you need to delete more than one folder you can use
he FileSystemObject objects DeleteFolder() method, discussed earlier in this
chapter.This method deletes the specified folder and all its contents, including
subfolders.Its use is demonstrated here.Set fsoObject = CreateObject("Scripting.FileSystemObject")
Set source_folder = fsoObject.GetFolder("d:\Docs")
source_folder.Delete()
QTP Scripts examples
1. Script for sending a mail using outlook express.Dim objOutlookMsg,objOutlook
Set objOutlook = CreateObject(Outlook.Application)
Set objOutlookMsg = objOutlook.CreateItem(olMailItem)
objOutlookMsg.To = objOutlookMsg.CC =
objOutlookMsg.BCC =
objOutlookMsg.Subject = testobjOutlookMsg.Body =
objOutlookMsg.Attachments.Add C:\Documents and Settings\Desktop\testreport.txt
objOutlookMsg.Send
2. Script for opening a Notepad file.In Expert view write a builtin funtion
invokeapplicationc:/whatever the path
Run
Dim a
Set a = WScript.CreateObject (WSCript.shell)a.run notepad.exeDim oShell
Set oShell = CreateObject (WSCript.shell)
oShell.run cmd/notepad.exe
Set oShell = Nothing
DsystemUtil.Run Notepad.exe
3. Script for connecting the oracle database
8/8/2019 SEG4530 VBScript Tutorial
47/52
8/8/2019 SEG4530 VBScript Tutorial
48/52
Excelone.Saveas E:\tests.xls
Excelone.quit
Set ExcelSheet=Nothing
6. Some more stuff related to QTP Script.Set Word = CreateObject(Word.Application)
oWord.DisplayAlerts = FalseoWord.Visible = False
oWord.documents.open testWordDoc.doc
Set Doc = oWord.ActiveDocument
Set Range = oDoc.content
oRange.ParagraphFormat.Alignment = 0
oRange.insertafter vbcrlf & & vbcrlf
oRange.collapse(0)
oRange.InlineShapes.AddPicture ImagePath.bmp, False, True
oWord.ActiveDocument.Save
oWord.Application.Quit True
Set Range = Nothing
Set Doc = Nothing
Set Word = Nothing
Cmd.activeconnection=Provider=SQLOLEDB.1;Password=;Persist Security Info=True;User
ID=sa;Initial Catalog=pubs;
Dim res,cmd,sql
Set Res=createobject(adodb.recordset)
Set Cmd=createobject(adodb.command)
Cmd.activeconnection=Provider=SQLOLEDB.1;Password=;Persist Security Info=True;User
ID=sa;Initial Catalog=pubs;Data Source=192.168.0.69
Cmd.CommandType = 1
sql=select emp_id,fname from dbo.employee
Cmd.CommandText = sql
Set res = Cmd.Execute()
i=1
While not res.eoflogid = res(emp_id).value
logname=res(fname).value
print logid
print logname
i=i+1
res.movenext
wend
Set res = nothing
Set cmd.ActiveConnection = nothing
Set Cmd= nothing
Set ExcelObj = CreateObject(Excel.Application)
aatype=F:\templet.xlsExcelObj.Workbooks.Open(aatype)
Set NewSheet = ExcelObj.Sheets.Item(2)
Dim rs,sq,pkey
set conn=createobject(adodb.connection)
set rs=createobject(adodb.recordset)
set rs1=createobject(adodb.recordset)
conn.open= Provider=OraOLEDB.Oracle.1;Password=*;Persist Security Info=True;User
ID=*;SERVER=*;Data Source=*;DBQ=*;
8/8/2019 SEG4530 VBScript Tutorial
49/52
sql=select * from table
rs.open sql,conn
i=1
do while not rs.eof
values1=rs(pkey)
values2=rs(name)
NewSheet.Cells(i+1,1).Value =values1
NewSheet.Cells(i+1,2).Value =values2
i=i+1
rs.movenext
Loop
ExcelObj.ActiveWorkbook.Saveas F:\data.xls
ExcelObj.Quit
Set ExcelObj = Nothing
rs.close
set rs=nothing
conn.close
set conn=nothing
Dim Excel,ExcelSheet
Set Excelone=CreateObject(Excel.Application)
Set ExcelSheet=CreateObject(Excel.Sheet)
ExcelSheet.Application.visible=true
ExcelSheet.ActiveSheet.Cells(1,1).value=1
ExcelSheet.ActiveSheet.Cells(1,2).value=2
ExcelSheet.ActiveSheet.Cells(1,3).value=3
Excelone.Saveas E:\tests.xls
Excelone.quit
Set ExcelSheet=Nothing
Set fs=CreateObject(excel.application)
fs.Visible=True
Set excelbook=fs.Workbooks.AddSet excelsheet=excelbook.worksheets(1)
excelsheet.cells(1,1)=??
excelsheet.saveas e:\1.xls
excelsheet.application.quit
fs.Quit
set fs=createobject(excel.application)
fs.visible=true
set excbook=fs.workbooks.open(f:\1.xls)
set excsheet=excbook.worksheet(1)
excsheet.cells(1,1).value=Test
excbook.save
fs.quit
Dim qtApp ,pDefColl,pDef ,rtParams,rtParam
Set qtApp = CreateObject(QuickTest.Application)
qtApp.Launch
qtApp.Visible = True
qtApp.Open C:\Test1
Set pDefColl = qtApp.Test.ParameterDefinitions
cnt = pDefColl.Count
Indx = 1
8/8/2019 SEG4530 VBScript Tutorial
50/52
While Indx
8/8/2019 SEG4530 VBScript Tutorial
51/52
8/8/2019 SEG4530 VBScript Tutorial
52/52
objexcel.ActiveSheet.Cells(1,1).Value = test is pass
Reporter.ReportEvent micPass,Calculation, result
Else
objexcel.ActiveSheet.Cells(1,1).Value = test is Fail
Reporter.ReportEvent micFail,Calculation, Expected Result is 15 +Acutal is +result
End If
What is the use of function GetROProperty()?GetROProperty is used to retrieve properties listed in Object Spy.
Example: hWnd=Browser(browser_name).GetROProperty(hwnd)
Window(hwnd:= & hWnd).Minimize