VBScript

VBScript
Developer Microsoft
First appeared 1996 (1996)
Stable release
5.8
OS Windows
Filename extensions .vbs, .vbe, .wsf, .wsc (.hta, .htm, .html, .asp)
Website msdn.microsoft.com/en-us/library/t0aew7h6.aspx
Major implementations
Windows Script Host, Active Server Pages
Influenced by
Visual Basic
Influenced
Windows PowerShell

VBScript ("Microsoft Visual Basic Scripting Edition") is an Active Scripting language developed by Microsoft that is modeled on Visual Basic. It allows Microsoft Windows system administrators to generate powerful tools for managing computers with error handling, subroutines, and other advanced programming constructs. It can give you complete control over many aspects of your computing environment.

VBScript uses the Component Object Model 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. VBScript has been installed by default in every desktop release of Microsoft Windows since Windows 98;[1] in Windows Server since Windows NT 4.0 Option Pack;[2] and optionally with Windows CE (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 (WSH), Internet Explorer (IE), and Internet Information Services (IIS).[3] 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) 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 administrators seeking an automation tool more powerful than the batch language first developed in the early 1980s.[4]

On March 6, 1988, Alan Cooper showed Bill Gates his shell prototype that allowed widgets to be added dynamically. On March 20, 1991, Microsoft adopted "Quick Basic". This allowed users to create Windows apps quickly and easily with a GUI. Finally, on August 1, 1996, Internet Explorer was made with features that included VBScript.[5]

In version 5.0, the functionality of VBScript was increased with new features including regular expressions; classes; the With statement;[6] 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,[7] and Distributed COM (DCOM) support.

In version 5.5, SubMatches[8] 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, the scripting team took the decision to implement future support for VBScript within ASP.NET for web development,[9] and therefore no new versions of the VBScript engine would be developed. It would henceforth be supported by Microsoft's Sustaining Engineering Team, who are responsible for bug fixes and security enhancements. For Windows system administrators, Microsoft suggests migrating to Windows PowerShell. However, the scripting engine will continue to be shipped with future releases of Microsoft Windows and IIS.

Environments

When employed for client-side web development in Microsoft Internet Explorer, VBScript is similar in function to JavaScript. It is used to write executable functions that are embedded in or included from HTML pages and interact with the Document Object Model (DOM) of the page, to perform tasks not possible in HTML alone. However, other web browsers such as Firefox and Opera 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 (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, but it is also used as the default script for error messages with the Windows operating systems.

 <% Option Explicit
 %><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" 
     "http://www.w3.org/TR/html4/loose.dtd">
 <html>
 	<head>
 		<title>VBScript Example</title>
 	</head>
 	<body>
        <div><% 
 		' Grab current time from Now() function.
                ' An '=' sign occurring after a context switch (<%) is shorthand 
                ' for a call to the Write() method of the Response object.
 		Dim timeValue = Now %>
 		The time, in 24-hour format, is 
                <%=Hour(timeValue)%>:<%=Minute(timeValue)%>:<%=Second(timeValue)%>.
        </div>
 	</body>
 </html>

VBScript can also be used to create applications that run directly on a workstation running Microsoft Windows. The simplest example is a script that makes use of the Windows Script Host (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 Files, and HTML Applications.

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: a library of classes or functions can be stored in one or more .vbs files, which can be included in .wsf files, so the functionality can be reused in a modular way. The files have extension .wsf and can be executed using wscript.exe or cscript.exe, just as a .vbs file can.

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-enabled applications.[10] These files have extension .wsc.

VBScript is simple to create and can be coded using an easy to use text editor like Notepad. A simple VBScript saved by the ".vbs" extension can be run on a Windows system by double clicking it.

Functionality

Language features

The language of VBScript is modeled 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.[11]

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 have "Variant" type by default, 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. Event-driven forms are not supported as in Visual Basic or Visual Basic for Applications.

Names are not case-sensitive. However, it is considered a best practice of VBScript style to be consistent and to capitalize judiciously.

VBScript functionalities

When hosted by the Windows Script Host, VBScript provides numerous features which are common to scripting languages, but not available from Visual Basic 6.0. These features include direct or easy access to:

CScript, the command line runner, provides options for:

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 are provided by the "ADODB.Stream" class, which can also be used for string builders (to avoid excessive string concatenation, which can be costly), and to interconvert byte arrays and strings. Database access is made possible through ActiveX Data Objects (ADO), and the IIS Metabase 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 Application Programming Interfaces (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 via monthly Windows security updates to disable vulnerable Microsoft and third party code.[12][13]

Development tools

Microsoft does not routinely make available an IDE (Integrated Development Environment) for VBScript, although the Microsoft Script Editor has been bundled with certain versions of Microsoft Office.

For debugging purposes the Microsoft Script Debugger can still be used in current Windows versions, even though the tool has not been updated in years. It allows the user to set break points in the VBScript code but the user interface is more than clumsy.

There are VBScript debuggers available from third-party sources,[14][15] and many text editors offer syntax highlighting for the language.

During execution, when an error occurs, the script host issues a message stating the type of error and the number of the offending line.

Examples

Hello, World

The simplest way to output "Hello World":

MsgBox "Hello, World" 'If Visual Basic version is higher than 6.0 you can also write it like this : MsgBox("Hello, World")

This would be saved as a .vbs file or .vbe and executed 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
' These three produce the same result. However, the use of constants as in the third line 
' is considered best practice.
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")
' Tip:MsgBox(Prompt,[Icon + Button],[Title],[Helpfile,Context])
' Presents the number corresponding to the button pressed. Different constants will produce 
' different behaviours. For example, vbOKCancel specifies two buttons in the dialogue box, 
' whereas vbYesNoCancel specifies three.
x = MsgBox("Hello World:Text", vbYesNoCancel+vbInformation,"Hello World:Title")
MsgBox "The result is " & x

Make your computer talk

VBScript can make your computer talk and say any text. It uses SAPI (Speech Application Interface ). Let's say "Hello World". Copy and Try this code:

Set Sapi=Wscript.CreateObject("SAPI.spVoice")
Sapi.speak "Hello world"

It's not always necessary to use SAPI as an object

Terminate a task

VBScript can access Windows Management Instrumentation (WMI), such as the Windows Task Manager. The code below, when executed, would terminate ("kill") any process involving notepad.exe.

'Terminate all processes involving the name <strProcessToKill>
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 for VBScript.[16][17]

Creating ten files with unique names

This example demonstrates how to create a new file and add content to it. It also demonstrates String concatenation.

For i = 1 to 10
	createFile( i )
Next

Public Sub createFile(a)

	Dim fso,MyFile
	filePath = "C:\file_name" & a & ".txt"
	Set fso = CreateObject("Scripting.FileSystemObject")
	Set MyFile = fso.CreateTextFile(filePath)
	MyFile.WriteLine("This is a separate file")
	MyFile.close

End Sub

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). SendKeys may not work with all programs, as some of them (e.g. license key input in software installations) check for a real key stroke rather than a virtual one.

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 a file with a .VBS extension, 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 whether 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.

VBScript's Assistant

VBScript can create you an assistant for you. Enable Windows Speech Recognition for voice activation, and once done type the code:

´author: Nirjal Paudel
Dim question
Set shell=Wscript.CreateObject("Wscript.Shell")
sapi=CreateObject("SAPI.spVoice")
do 
question =Inputbox ("Type a command [type exit to quit]")
Select Case Ucase(question)
Case "NIRTECH"
sapi.Speak "Going to Nirtech"
shell.Run "http://www.nirtech.tk"
Case "Cmd"
sapi.Speak "Going to Cmd"
shell.Run "cmd.exe"
End Select

You can add command here by this method.

The method
Case Ucase ("<your command>")
sapi.speak ("<What will computer say")
shell.Run ("<web site link  or file path >")

Send an email

Using MS Outlook.

Sub Email_Sender()
	mailTO="XYZ@ABC.com"
	mailCC="PQR@ABC.com"
	olSubject="Test Email"
	allKeys=""
	Set objOL = CreateObject("Outlook.Application")
	Set objMail = objOL.CreateItem(0)

	objMail.to = mailTO
	objMail.cc=mailCC
	olFormatHTML=2

	With objMail
		.Subject = olSubject
		.BodyFormat = olFormatHTML
		.Attachments.Add attachMent
		.HTMLBody = "<HTML><BODY><p>Hi All,</p><P> This is a test email</p></BODY></HTML>"
		.Send 
	End With
End Sub

Wscript.echo("Calling the email function now")
call Email_Sender
Wscript.echo("Email is sent")

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.[18] This situation may change with the promotion and increased use of Windows PowerShell. Second, VBScript is the scripting language for Quick Test Professional, a test automation tool.[19] 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 Caché (which has its roots in the language MUMPS) also supports an implementation of VBScript, Cache BASIC, for programming stored code.[20]

VBScript omits 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. However, its use is relatively widespread because it is easy to learn and because those who implement code in the language need not pay royalties to Microsoft as long as the VBScript trade mark is acknowledged. 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.

VBScript is used in place of VBA as the macro language of Outlook 97.

VBScript can be effectively used for automating day to day office tasks as well as monitoring in the Windows-based environment. It's a first choice tool for server administrators, MS Office users and other tech contributors. It can also be used in collaboration with ADODB ActiveX Data Objects (ADODB) for effective database connectivity.

See also

Wikimedia Commons has media related to VBScript.

References

External links

This article is issued from Wikipedia - version of the 11/28/2016. The text is available under the Creative Commons Attribution/Share Alike but additional terms may apply for the media files.