VBScript
Encyclopedia
VBScript is an Active Scripting
Active Scripting
Active Scripting is the technology used in Windows to implement component-based scripting support. It is based on COM and allows installation of additional scripting engines in the form of COM modules.-Uses and history:The Active Scripting technologies were first released in 1996, with the...

 language developed by Microsoft
Microsoft
Microsoft Corporation is an American public multinational corporation headquartered in Redmond, Washington, USA that develops, manufactures, licenses, and supports a wide range of products and services predominantly related to computing through its various product divisions...

 that is modeled on Visual Basic
Visual Basic
Visual Basic is the third-generation event-driven programming language and integrated development environment from Microsoft for its COM programming model...

. It is designed as a “lightweight” language with a fast interpreter for use in a wide variety of Microsoft environments. VBScript uses the Component Object Model
Component Object Model
Component Object Model is a binary-interface standard for software componentry introduced by Microsoft in 1993. It is used to enable interprocess communication and dynamic object creation in a large range of programming languages...

 to access elements of the environment within which it is running; for example, the FileSystemObject (FSO) is used to create, read, update and delete files
Computer file
A computer file is a block of arbitrary information, or resource for storing information, which is available to a computer program and is usually based on some kind of durable storage. A file is durable in the sense that it remains available for programs to use after the current program has finished...

.

VBScript has been installed by default in every desktop release of Microsoft Windows
Microsoft Windows
Microsoft Windows is a series of operating systems produced by Microsoft.Microsoft introduced an operating environment named Windows on November 20, 1985 as an add-on to MS-DOS in response to the growing interest in graphical user interfaces . Microsoft Windows came to dominate the world's personal...

 since Windows 98
Windows 98
Windows 98 is a graphical operating system by Microsoft. It is the second major release in the Windows 9x line of operating systems. It was released to manufacturing on 15 May 1998 and to retail on 25 June 1998. Windows 98 is the successor to Windows 95. Like its predecessor, it is a hybrid...

; in Windows Server
Windows Server
Windows Server is a brand name for a group of server operating systems released by Microsoft Corporation. All are part of Microsoft Servers.- Members :This brand includes the following software:* Windows 2000 Server* Windows Server 2003...

 since Windows NT 4.0 Option Pack; and optionally with Windows CE
Windows CE
Microsoft Windows CE is an operating system developed by Microsoft for embedded systems. Windows CE is a distinct operating system and kernel, rather than a trimmed-down version of desktop Windows...

 (depending on the device it is installed on).

A VBScript script must be executed within a host environment, of which there are several provided with Microsoft Windows, including: Windows Script Host
Windows Script Host
The Microsoft Windows Script Host is an automation technology for Microsoft Windows operating systems that provides scripting capabilities comparable to batch files, but with a greater range of supported features...

 (WSH), Internet Explorer
Internet Explorer
Windows Internet Explorer is a series of graphical web browsers developed by Microsoft and included as part of the Microsoft Windows line of operating systems, starting in 1995. It was first released as part of the add-on package Plus! for Windows 95 that year...

 (IE), and Internet Information Services
Internet Information Services
Internet Information Services – formerly called Internet Information Server – is a web server application and set of feature extension modules created by Microsoft for use with Microsoft Windows. It is the most used web server after Apache HTTP Server. IIS 7.5 supports HTTP, HTTPS,...

 (IIS). Additionally, the VBScript hosting environment is embeddable in other programs, through technologies such as the Microsoft Script Control (msscript.ocx).

History

VBScript began as part of the Microsoft Windows Script Technologies, launched in 1996. This technology (which also included JScript
JScript
JScript is a scripting language based on the ECMAScript standard that is used in Microsoft's Internet Explorer.JScript is implemented as a Windows Script engine. This means that it can be "plugged in" to any application that supports Windows Script, such as Internet Explorer, Active Server Pages,...

) was initially targeted at web developers. During a period of just over two years, VBScript advanced from version 1.0 to 2.0, and over that time it gained support from Windows system administrator
System administrator
A system administrator, IT systems administrator, systems administrator, or sysadmin is a person employed to maintain and operate a computer system and/or network...

s seeking an automation tool more powerful than the batch language
Batch file
In DOS, OS/2, and Microsoft Windows, batch file is the name given to a type of script file, a text file containing a series of commands to be executed by the command interpreter....

 first developed in the early 1980s.

On March 6, 1988 Alan Cooper
Alan Cooper
Alan Cooper is known for his role in humanizing technology through his groundbreaking work in software design. Widely recognized as the “Father of Visual Basic," Cooper is the author of the books, About Face 3: The Essentials of Interaction Design and The Inmates Are Running the Asylum: Why...

 showed Bill Gates
Bill Gates
William Henry "Bill" Gates III is an American business magnate, investor, philanthropist, and author. Gates is the former CEO and current chairman of Microsoft, the software company he founded with Paul Allen...

 his shell prototype that allowed widgets to be added dynamically. March 20, 1991, Microsoft
Microsoft
Microsoft Corporation is an American public multinational corporation headquartered in Redmond, Washington, USA that develops, manufactures, licenses, and supports a wide range of products and services predominantly related to computing through its various product divisions...

 adopted "Quick Basic" to Ruby Shell. This allowed users to create Windows apps quickly and easily with a GUI
Gui
Gui or guee is a generic term to refer to grilled dishes in Korean cuisine. These most commonly have meat or fish as their primary ingredient, but may in some cases also comprise grilled vegetables or other vegetarian ingredients. The term derives from the verb, "gupda" in Korean, which literally...

. In September 1992, the programming language was not quite compatible with the Windows OS; Windows was DOS
DOS
DOS, short for "Disk Operating System", is an acronym for several closely related operating systems that dominated the IBM PC compatible market between 1981 and 1995, or until about 2000 if one includes the partially DOS-based Microsoft Windows versions 95, 98, and Millennium Edition.Related...

 based using BASIC
BASIC
BASIC is a family of general-purpose, high-level programming languages whose design philosophy emphasizes ease of use - the name is an acronym from Beginner's All-purpose Symbolic Instruction Code....

 compilers and could not read the language. Finally in the fall of 1996, Internet Explorer
Internet Explorer
Windows Internet Explorer is a series of graphical web browsers developed by Microsoft and included as part of the Microsoft Windows line of operating systems, starting in 1995. It was first released as part of the add-on package Plus! for Windows 95 that year...

 is made with features that include VBScript.

In version 5.0, the functionality of VBScript was increased with new features such as: regular expression
Regular expression
In computing, a regular expression provides a concise and flexible means for "matching" strings of text, such as particular characters, words, or patterns of characters. Abbreviations for "regular expression" include "regex" and "regexp"...

s; classes
Class (computer science)
In object-oriented programming, a class is a construct that is used as a blueprint to create instances of itself – referred to as class instances, class objects, instance objects or simply objects. A class defines constituent members which enable these class instances to have state and behavior...

; the With statement; the Eval, Execute, and ExecuteGlobal functions to evaluate and execute script commands built during the execution of another script; a function-pointer system via GetRef, and Distributed COM (DCOM) support.

In version 5.5, SubMatches were added to the regular expression class in VBScript, to finally allow script authors to capture the text within the expression's groups. That capability had already been available in JScript.

With the advent of the .NET framework
.NET Framework
The .NET Framework is a software framework that runs primarily on Microsoft Windows. It includes a large library and supports several programming languages which allows language interoperability...

, the scripting team took the decision to implement future support for VBScript within ASP.NET
ASP.NET
ASP.NET is a Web application framework developed and marketed by Microsoft to allow programmers to build dynamic Web sites, Web applications and Web services. It was first released in January 2002 with version 1.0 of the .NET Framework, and is the successor to Microsoft's Active Server Pages ...

 for web development, and therefore no new versions of the VBScript engine would be developed and it moved over to being supported by Microsoft's Sustaining Engineering Team, who are responsible for bug fixes and security enhancements. For Windows system administrators, Microsoft suggests that they migrate to Windows PowerShell
Windows PowerShell
Windows PowerShell is Microsoft's task automation framework, consisting of a command-line shell and associated scripting language built on top of, and integrated with the .NET Framework...

. However, the scripting engine will continue to be shipped with future releases of Microsoft Windows and IIS..

Uses

Although VBScript is a general-purpose scripting language, several particular areas of use are noteworthy. First, it is widely used among system administrators in the Microsoft environment.
This situation may change with the promotion and increased use of Windows PowerShell
Windows PowerShell
Windows PowerShell is Microsoft's task automation framework, consisting of a command-line shell and associated scripting language built on top of, and integrated with the .NET Framework...

. Second, VBScript is the scripting language for Quick Test Professional
HP QuickTest Professional
HP QuickTest Professional software provides functional and regression test automation for software applications and environments. Part of the HP Quality Center tool suite, HP QuickTest Professional can be used for enterprise quality assurance....

, a test automation tool.
A third area to note is the adoption of VBScript as the internal scripting language for some embedded applications, such as industrial operator interfaces and human machine interfaces. The hierarchical DBMS InterSystems Cache (which has its roots in the language MUMPS
MUMPS
MUMPS , or alternatively M, is a programming language created in the late 1960s, originally for use in the healthcare industry. It was designed for the production of multi-user database-driven applications...

) also supports an implementation of VBScript, Cache BASIC, for programming stored code. .

This relatively widespread use of VBScript is not because of many special merits of VBScript - several useful features of the full Visual Basic, such as strong typing, extended error trapping and the ability to pass a variable number of parameters to a subroutine have been removed - but mainly because, apart from being easy to learn, royalties need not be paid to Microsoft by implementers as long as the VBScript trade mark is acknowledged. By contrast, when an organization licenses Visual Basic for Applications (VBA) from Microsoft - as companies such as Autodesk, StatSoft, Great Plains Accounting and Visio (subsequently acquired by Microsoft) have done - it is allowed to redistribute the full VBA code-writing and debugging environment with its product.

Environments

When employed for client-side web development in Microsoft Internet Explorer
Internet Explorer
Windows Internet Explorer is a series of graphical web browsers developed by Microsoft and included as part of the Microsoft Windows line of operating systems, starting in 1995. It was first released as part of the add-on package Plus! for Windows 95 that year...

, VBScript is similar in function to JavaScript
JavaScript
JavaScript is a prototype-based scripting language that is dynamic, weakly typed and has first-class functions. It is a multi-paradigm language, supporting object-oriented, imperative, and functional programming styles....

. It is used to write executable functions that are embedded in or included from HTML pages and interact with the Document Object Model
Document Object Model
The Document Object Model is a cross-platform and language-independent convention for representing and interacting with objects in HTML, XHTML and XML documents. Aspects of the DOM may be addressed and manipulated within the syntax of the programming language in use...

 (DOM) of the page, to perform tasks not possible in HTML alone. However, other web browsers such as Firefox and Opera
Opera (web browser)
Opera is a web browser and Internet suite developed by Opera Software with over 200 million users worldwide. The browser handles common Internet-related tasks such as displaying web sites, sending and receiving e-mail messages, managing contacts, chatting on IRC, downloading files via BitTorrent,...

 do not have built-in support for VBScript. This means that where client-side scripting and cross-browser compatibility are required, developers usually choose JavaScript over VBScript.

VBScript is also used for server-side processing of web pages, most notably with Microsoft Active Server Pages
Active Server Pages
Active Server Pages , also known as Classic ASP or ASP Classic, was Microsoft's first server-side script engine for dynamically-generated Web pages. Initially released as an add-on to Internet Information Services via the Windows NT 4.0 Option Pack Active Server Pages (ASP), also known as Classic...

 (ASP). The ASP engine and type library, asp.dll, invokes vbscript.dll to run VBScript scripts. VBScript that is embedded in an ASP page is contained within <% and %> context switches. The following example of an ASP page with VBScript displays the current time in 24-hour format (Note that an '=' sign occurring after a context switch (<%) is short-hand for a call to Write method of the Response object), but it is also used as the default script for error messages with the windows operating systems.


<% Option Explicit
%> "http://www.w3.org/TR/html4/loose.dtd">


VBScript Example







VBScript can also be used to create applications that run directly on a workstation running Microsoft Windows
Microsoft Windows
Microsoft Windows is a series of operating systems produced by Microsoft.Microsoft introduced an operating environment named Windows on November 20, 1985 as an add-on to MS-DOS in response to the growing interest in graphical user interfaces . Microsoft Windows came to dominate the world's personal...

. The simplest example is a script that makes use of the Windows Script Host
Windows Script Host
The Microsoft Windows Script Host is an automation technology for Microsoft Windows operating systems that provides scripting capabilities comparable to batch files, but with a greater range of supported features...

 (WSH) environment. Such a script is usually in a stand-alone file with the file extension .vbs. The script can be invoked in two ways. Wscript.exe is used to display output and receive input through a GUI, such as dialog and input boxes. Cscript.exe is used in a command line environment.

VBScript can be included in two other types of scripting files: Windows Script File
Windows Script File
A Windows Script File is a file type used by the Microsoft Windows Script Host. It allows mixing the scripting languages JScript and VBScript within a single file, or other scripting languages such as Perl, Object REXX, Python, or Kixtart if installed by the user...

s, and HTML Application
HTML Application
An HTML Application is a Microsoft Windows program whose source code consists of HTML, Dynamic HTML, and one or more scripting languages supported by Internet Explorer, such as VBScript or JScript. The HTML is used to generate the user interface, and the scripting language is used for the program...

s.

A Windows Script File (WSF) is styled after XML. A WSF file can include multiple VBS files. As a result WSF files provide a means for code reuse: one can write a library of classes or functions in one or more .vbs files, and include those files in one or more WSF files to use and reuse that functionality in a modular way. The files have extension .wsf and can be executed using wscript.exe or cscript.exe, just like a .vbs file.

An HTML Application (HTA) is styled after HTML. The HTML in the file is used to generate the user interface, and a scripting language such as VBScript is used for the program logic. The files have extension .hta and can be executed using mshta.exe.

VBScript (and JScript) can also be used in a Windows Script Component - an ActiveX-enabled script class that can be invoked by other COM
Component Object Model
Component Object Model is a binary-interface standard for software componentry introduced by Microsoft in 1993. It is used to enable interprocess communication and dynamic object creation in a large range of programming languages...

-enabled applications. These files have extension .wsc.

Language features

The language of VBScript is modelled on Visual Basic, and therefore can be reviewed using similar categories: procedures, control structures, constants, variables, user interaction, array handling, date/time functions, error handling, mathematical functions, objects, regular expressions, string manipulation, and so on.

The following are some key points of introduction to the VBScript language.

A “procedure” is the main construct in VBScript for separating code into smaller modules. VBScript distinguishes between a function, which can return a result in an assignment statement, and a subroutine, which cannot. Parameters are positional, and can be passed by value or by reference.

Control structures include the usual iterative and conditional Do Loops, If-Then-Else statements, and Case statements, with some more complex variants, such as ElseIf and nested control structures.

As a memory aid in coding, and certainly for readability, there are a large number of constants, such as True and False for logical values, vbOKCancel and vbYesNo for MsgBox codes, vbBlack and vbYellow for color values, vbCR for the carriage return character, and many others.

Variables by default have “Variant” type, but it is possible (and sometimes necessary) to force a particular type (integer, date, etc.) using conversion functions (Cint, CDate, etc.)

User interaction is provided through the functions MsgBox and InputBox which provide a simple dialogue box format for messages and input. Both functions display prompting messages, with the former returning a standard response, and the latter returning one user-supplied text or numeric value. For more elaborate GUI interaction with controls, VBScript can be used in combination with HTML, for example, in an HTML Application
HTML Application
An HTML Application is a Microsoft Windows program whose source code consists of HTML, Dynamic HTML, and one or more scripting languages supported by Internet Explorer, such as VBScript or JScript. The HTML is used to generate the user interface, and the scripting language is used for the program...

. Event-driven forms are not supported as in Visual Basic or Visual Basic for Applications.

Names are not case-sensitive; therefore, for example, MsgBox and msgbox, or FileSystemObject and filesystemobject, are treated as the same name. However, as usual, it is considered a best practice of VBScript style to be consistent and to capitalize judiciously.

Additional Functionality

File system management, file modification, and streaming text operations are implemented with the Scripting Runtime Library scrrun.dll. This provides objects such as FileSystemObject, File, and TextStream, which expose the Windows File System to the programmer.

Binary file and memory I/O is provided by the "ADODB.Stream" class, which can also be used as a string builder (since a high amount of VBScript string concatenation is costly due to constant memory re-allocation), and can be used to convert an array of bytes to a string and vice versa. Database access is made possible through ActiveX Data Objects
ActiveX Data Objects
Microsoft's ActiveX Data Objects is a set of Component Object Model objects for accessing data sources. A part of MDAC, it provides a middleware layer between programming languages and OLE DB...

 (ADO), and the IIS Metabase
Metabase
Microsoft's Internet Information Services stores its information in an internal database called the MetaBase. The metabase is an inheritable, hierarchical database that allows for configuration of HTTP/HTTPS, FTP, SMTP, and NNTP at the server, the site, or the folder or file level...

 can be manipulated using the GetObject function with sufficient permissions (useful for creating and destroying sites and virtual directories). XML files and schemas can be manipulated with the Microsoft XML Library
MSXML
Microsoft XML Core Services is a set of services that allow applications written in JScript, VBScript, and Microsoft development tools to build Windows-native XML-based applications...

 Application Programming Interface
Application programming interface
An application programming interface is a source code based specification intended to be used as an interface by software components to communicate with each other...

s (msxml6.dll, msxml3.dll), which also can be used to retrieve content from the World Wide Web via the XMLHTTP and ServerXMLHTTP objects (class strings "MSXML2.XMLHTTP.6.0" and "MSXML2.ServerXMLHTTP.6.0", respectively).

Functionality can also be added through ActiveX technologies. Security concerns have led to many ActiveX controls being blacklisted in the Internet Explorer process by Microsoft, which deploys the killbit
Killbit
Killbit is a security feature in web browsers based on Microsoft's Trident engine and other ActiveX containers that respect the killbit...

 via monthly Windows security updates to disable vulnerable Microsoft and third party code.

Development Tools

Microsoft does not routinely make available an IDE (Integrated Development Environment
Integrated development environment
An integrated development environment is a software application that provides comprehensive facilities to computer programmers for software development...

) for VBScript, although the Microsoft Script Editor
Microsoft Script Editor
The Microsoft Script Editor is an optional tool included in Microsoft Office 2000 through Office 2003 as well newer versions of office and is found in "C:\Program Files\common files" directory.It allows one to work with HTML code, DHTML objects, and script in an Office document from within an...

 has been reported. However, there are VBScript debuggers available from third-party sources, and there is syntax high-lighting either for VBScript or languages with similar syntax in many editors in the list of text editors. Apart from this, any text editor can be used to create a VBScript program; the important thing is to give the text file the desired file extension.

During execution, when an error occurs, the script host reports an error message stating the error type (e.g. “syntax error”) together with the line number and position within the line where the error occurred.

Hello World

The “simplest” example:


MsgBox "Hello World"


Save it as a .vbs file. Then execute using cscript.exe or wscript.exe.

A more elaborate example, showing the use of MsgBox as a function (returning a result), and the use of three parameters, including the use of constants in the second parameter.


dim x
x = MsgBox("Hello World:Text",1+64+4096,"Hello World:Title")
x = MsgBox("Hello World:Text",4161,"Hello World:Title")
x = MsgBox("Hello World:Text", vbOKCancel+vbInformation+vbSystemModal, _
"Hello World:Title")
x = MsgBox("Hello World:Text", vbYesNoCancel+vbInformation,"Hello World:Title")
MsgBox "The result is " & x


The first three lines all produce the same result. For clarity, the numbers in the second parameter are written as an explicit summation (that is, with a "+"), rather than presented as a single number (in this example, 4161). However, the use of constants as in the third line is considered best practice. Different constants will produce different behaviours; for example, vbOKCancel specifies two buttons in the dialogue box, whereas vbYesNoCancel would specify three buttons (Yes, No, and Cancel).

Terminate a task

VBScript can access the Windows Task Manager
Windows Task Manager
Windows Task Manager is a task manager application included with the Microsoft Windows NT family of operating systems that provides detailed information about computer performance and running applications, processes and CPU usage, commit charge and memory information, network activity and...

. The code below, when executed, would terminate (“kill”) any process involving ’’notepad.exe’’.

'Terminate all processes involving the name
Option Explicit
Dim strComputer, strProcessToKill, objWMIService, colProcess, objProcess

strComputer = "."
strProcessToKill = "notepad.exe"
Set objWMIService = GetObject("winmgmts:" _
& "{impersonationLevel=impersonate}!\\" _
& strComputer _
& "\root\cimv2")
Set colProcess = objWMIService.ExecQuery _
("Select * from Win32_Process Where Name = '" & strProcessToKill & "'")
For Each objProcess in colProcess
msgbox "... terminating " & objProcess.Name
objProcess.Terminate
Next
The use of Option Explicit is not required, but is considered a best practice
Best practice
A best practice is a method or technique that has consistently shown results superior to those achieved with other means, and that is used as a benchmark...

 for VBScript.

SendKeys

The SendKeys method sends one or more keystrokes to the active window (as if typed on the keyboard). In this example the script sends the characters “Hello World!” three times, each time pausing for 2 seconds (2000 milliseconds).

set shl = createobject("wscript.shell")
shl.sendkeys "Hello World!"
wscript.sleep 2000
shl.sendkeys "Hello World!"
wscript.sleep 2000
shl.sendkeys "Hello World!"
wscript.sleep 2000

The code should be saved as whatever.vbs, then executed using cscript.exe or wscript.exe in a command window. During execution, the characters “Hello World!” will be displayed after the command prompt.

Windows file operations

Example of using the supplied object FileSystemObject for some file operations (such as testing if a file exists), and also creating a text file (a TextStream object, one of whose methods is WriteLine).
The name of the file is passed as a parameter by reference (which is the default, although this does not matter in this example).


myfilename = "C:\Wikipedia - VBScript - Example - Hello World.txt"
MakeHelloWorldFile myfilename

Sub MakeHelloWorldFile (FileName)
'Create a new file in C: drive or overwrite existing file
Set FSO = CreateObject("Scripting.FileSystemObject")
If FSO.FileExists(FileName) Then
Answer = MsgBox ("File " & FileName & " exists ... OK to overwrite?", vbOKCancel)
'If button selected is not OK, then quit now
'vbOK is a language constant
If Answer <> vbOK Then Exit Sub
Else
'Confirm OK to create
Answer = MsgBox ("File " & FileName & " ... OK to create?", vbOKCancel)
If Answer <> vbOK Then Exit Sub
End If
'Create new file (or replace an existing file)
Set FileObject = FSO.CreateTextFile (FileName)
FileObject.WriteLine "Time ... " & Now
FileObject.WriteLine "Hello World"
FileObject.Close
MsgBox "File " & FileName & " ... updated."
End Sub

The subroutine MakeHelloWorldFile will create (or update, if it exists) a small text file in the root directory of the C:\ drive, upon selecting “OK” in the MsgBox dialogue box.

Other scripting languages

  • JavaScript
    JavaScript
    JavaScript is a prototype-based scripting language that is dynamic, weakly typed and has first-class functions. It is a multi-paradigm language, supporting object-oriented, imperative, and functional programming styles....

  • JScript
    JScript
    JScript is a scripting language based on the ECMAScript standard that is used in Microsoft's Internet Explorer.JScript is implemented as a Windows Script engine. This means that it can be "plugged in" to any application that supports Windows Script, such as Internet Explorer, Active Server Pages,...

  • JScript.NET
  • PerlScript
    PerlScript
    PerlScript was initially solely an ActiveX Scripting Engine produced by the company ActiveState for use with Microsoft's Internet Information Services that allows for programmers to use Perl-based code in addition to, or in place of, VBScript or JScript in the context of web servers running the...

  • Applescript
    AppleScript
    AppleScript is a scripting language created by Apple Inc. and built into Macintosh operating systems since System 7. The term "AppleScript" may refer to the scripting system itself, or to particular scripts that are written in the AppleScript language....


External links

The source of this article is wikipedia, the free encyclopedia.  The text of this article is licensed under the GFDL.
 
x
OK