Misplaced Pages

VBScript: Difference between revisions

Article snapshot taken from Wikipedia with creative commons attribution-sharealike license. Give it a read and then ask your questions in the chat. We can research this topic together.
Browse history interactively← Previous editNext edit →Content deleted Content addedVisualWikitext
Revision as of 23:47, 20 February 2008 editDigita (talk | contribs)1,958 edits External links: ie← Previous edit Revision as of 07:45, 21 February 2008 edit undo82.198.10.88 (talk) External linksNext edit →
Line 201: Line 201:
| and link back to that category using the {{dmoz}} template. | | and link back to that category using the {{dmoz}} template. |
===========================({{NoMoreLinks}})===============================--> ===========================({{NoMoreLinks}})===============================-->
*, VBScript Developers Network
* in the Microsoft Developer Network * in the Microsoft Developer Network
* in the Microsoft Developer Network * in the Microsoft Developer Network

Revision as of 07:45, 21 February 2008

VBScript (short for Visual Basic Scripting Edition) is an Active Scripting language developed by Microsoft. The language's syntax reflects its pedigree as a limited variation of Microsoft's Visual Basic programming language. VBScript is installed as default in every desktop release of the Windows Operating System (OS) since Windows 98, and may or may not be included with Windows CE depending on the configuration and purpose of the device it is running on. It initially gained support from Windows administrators seeking an automation tool more powerful than the batch language first developed in the late 1970s. A VBScript script must be executed within a host environment, of which there are several provided on a standard install of Microsoft Windows (Windows Script Host, Windows Internet Explorer). 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, which were targeted at web developers initially and were launched in 1996. During a period of just over two years, the VBScript and JScript languages advanced from version 1.0 to 5.0 and over that time system administrators noticed it and began using it. In 5.0, VBScript received a large boost of power with new functionality such as Regular Expressions, Classes, the With statement, Eval/Execute/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 5.5, "Submatches" were added to the regular expression class in VBScript to finally allow VBScript script authors to capture the text within the expression's groups. That capability before was only possible through the JScript member of the Microsoft ActiveX Scripting family.

As of 2007, no new functionality will be added to the VBScript language. However, it will continue to be shipped with future releases of Microsoft Windows as will other components of the ActiveX Scripting Family (such as JScript). Additionally, support will continue due to the amount of code written in it and because it is still considered a useful tool for some tasks.

The language engine is currently being maintained by Microsoft's Sustaining Engineering Team, which is responsible for bug fixes and security enhancements.

Uses

When employed in Microsoft Internet Explorer, VBScript is similar in function to JavaScript, as a language to write 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. Other web browsers such as Firefox, and Opera do not have built-in support for VBScript. This means that where client-side script is required on a web site, developers almost always use JavaScript for cross-browser compatibility.

Besides client-side web development, VBScript is 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 military format (Note that an '=' sign occurring after a context switch (<%) is short-hand for a call to Write() method of the Response object).

 <% 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><% 
 		'Grab current time from Now() function.
 		Dim timeValue
 		timeValue = Now  %>
 		The time, in military format, is <%=Hour(timeValue)%>:<%=Minute(timeValue)%>:<%=Second(timeValue)%>.
 	</body>
 </html>

VBScript can also be used to create applications that run directly on a person's computer running Microsoft Windows. The simplest example of this 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 in through a GUI, such as dialog and input boxes. Cscript.exe is used in a command line environment.

VBScript .vbs files can be included in two other types of scripting files: .wsf files, which are styled after XML; and .hta files, which are styled after HTML. .wsf files can be executed using wscript.exe or cscript.exe, just like .vbs files, and .wsf files 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.

Another employment of VBScript is the HTML Application, or HTA (file extension .hta). In an HTA, HTML is used for the user interface, and a scripting language such as VBScript is used for the program logic. HTAs run inside of mshta.exe, which is a 'Trusted Application Environment' provided by Internet Explorer. The 'Trusted Application Environment', implies that HTAs do not suffer the restrictions applied to applications running in the web or intranet zone, such as accessing local files or network paths. Although HTAs run in this 'trusted' environment, querying Active Directory can be subject to Internet Explorer Zone logic and associated error messages.

Functionality

As-is, VBScript provides basic date/time, string manipulation, math, user interaction, error handling, and regular expressions. Additional functionality can be added through the use of ActiveX technologies. File system management, file modification, and streaming text operations can be achieved with the Scripting Runtime Library scrrun.dll. 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 (ADO), and the IIS Metabase can be manipulated using the GetObject() function with sufficient permissions (useful for creating and destroying sites and virtual directories). Additionally, 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").

Examples

Try out these examples with a text editor, by copying them into it and saving the contents with a filename ending with the .vbs file extension.

Notes: Variable declarations are not required (unless Option Explicit is placed at the top of the file), nor is freeing objects when you are done with them, but they are considered good practices. Variables are in camel case notation.

  • Display a message that the user will see regardless of whether they use the CScript (Console) or WScript (Non-Console) host.
 Option Explicit
 WScript.Echo "Hello World!"
  • Display a Message Box to the user with a Question icon and Yes/No buttons. This example additionally demonstrates how to perform line continuation (note: VBScript lacks a conditional operator, and writing a function to perform the task of that operator would execute slower than the code below).
 Option Explicit
 MsgBox "Text displayed inside a message box!", vbInformation, "Optional Title For Message Box"
 If MsgBox("Make a Choice", vbQuestion + vbYesNo, "Title") = vbYes Then
 	MsgBox "You chose Yes!", vbInformation
 Else
 	MsgBox "You chose No!", vbInformation
 End If
  • Display an "Input Box", that requests the user to enter a value.
 Option Explicit
 Dim userInput
 userInput = InputBox("Write something:", "Title")
 If userInput = "" Then
 	Msgbox "You did not write anything or you pressed cancel!"
 Else
 	MsgBox "You wrote " & userInput & ".", vbInformation
 End If
  • Run programs and write something in to the Windows Registry.
 Option Explicit
 Dim ws
 Set ws = CreateObject("WScript.Shell")
 'Open (execute) ].
 ws.Exec "C:\Program Files\Windows Media Player\wmplayer.exe"
 'Write "Hello Microsoft!" string on the Registry.
 ws.RegWrite "HKLM\Software\Microsoft\", "Hello Microsoft!"
 'Run the ].
 ws.Run "regedit"
 'Free the created WScript.Shell object.
 set ws = nothing
  • A series of file system operations
 Option Explicit
 ' Constants for GetSpecialFolder(), derived from the scrrun.dll type library where the Scripting.FileSystemObject 
 ' class is defined.
 Const SystemFolder = 1
 Const TemporaryFolder = 2
 Const WindowsFolder = 0
 Dim fso
 Dim fileToCopy
 Dim destinationPath
 Dim dontDelete
 Set fso = CreateObject("Scripting.FileSystemObject")
 fileToCopy = "C:\hello.txt"
 destinationPath = fso.GetSpecialFolder(WindowsFolder).Path & "\newname.123"
 'Create file to copy if it does not exist.
 If Not fso.FileExists(fileToCopy) Then
 	Dim textStream
 	Set textStream = fso.CreateTextFile("C:\hello.txt")
 	textStream.WriteLine "I am a file."
 	textStream.Close
 	Set textStream = nothing
 Else
 	dontDelete = True
 End If
 'Copy file to Windows directory with a new file name and extension.
 'This will destroy any file called "newname.123" in the Windows directory.
 fso.CopyFile fileToCopy, destinationPath, True
 'Delete copy.
 fso.DeleteFile destinationPath, True
 'Only delete original if it was not created by this script.
 If Not dontDelete Then fso.DeleteFile destinationPath
 'Some house cleaning...
 Set fso = Nothing

For and while cycles:

 'A basic 'for' loop
 For i = 1 To 9
 	MsgBox "This is message number " + Chr(i+48)
 Next i
 'A more advanced for loop 
 For i = 100 To -100 Step -20		'step determines the step by which i advances.
 	MsgBox "This is message number " + Chr(i+48)
 	MsgBox "Entering next loop..."
 Next i
 'Finally, pre-test while loop
 Dim text
 While text <> "exit"			' <> is the boolean inequality operator.
 	text = InputBox("Write 'exit' to exit:", "Waiting to end.")
 Wend
 'Another pre-test do/while loop
 do until text = "exit"
 	text = InputBox("Write 'exit' to exit:", "Waiting to end.")
 loop
 'A post-test do/while loop
 do
 	text = InputBox("Write 'exit' to exit:", "Waiting to end.")
 loop while text <> "exit"

See also

External links

Microsoft Windows components
Management
tools
Apps
Shell
Services
File systems
Server
Architecture
Security
Compatibility
API
Games
Discontinued
Games
Apps
Others
Spun off to
Microsoft Store
Internet Explorer
Versions
Main
Other
Overview
Technologies
Software and engines
Implementations
Events
People
Categories:
VBScript: Difference between revisions Add topic