VB Script
VB Script
Page 1 of 16
Page 2 of 16
Fig 2 Enclose the File name in quotes to retain the .VBS extension
You can script anything! Fig 4 Output showing the current Script version
Page 3 of 16
Introduction to Objects:
Object Oriented Programming (OOP) allows you to encapsulate data (fields) and behaviors (properties and methods) using a class. The relationship between a class and an object is similar to the relationship between a blueprint and the home that is built from the blueprint. The class just defines how the object will be built. A full implementation of OOP allows existing classes to be extended by inheritance to create sub-classes. To actually build an object we need to declare a reference of the class and then call the classs constructor. Each object that is created from a class has its own protected set of variables, properties, and methods. In the example above, we referenced an implicit object named Wscript and a property of that object named Version. Note: We did not have to construct an instance (instantiate) of the Wscript object because the script engine had already made this object available to our script. VBSCRIPT has limited (no inheritance) Object Oriented Programming support, which allows you to: create your own classes using the CLASS statement provide constructors (initializers) for your class using the SUB CLASS_INITIALIZE event provide destructors (clean up) for your classes using the SUB CLASS_TERMINATE event hide or expose data or behaviors using the PRIVATE and PUBLIC access modifiers provide methods within the class using the FUNCTION and SUB keywords expose access to hidden variables using the PROPERTY LET and GET statements create (instantiate) objects that reference your own classes using the NEW keyword In addition to creating objects from your own classes, you can also create references to COM objects using the SET statement and the CreateObject method of the Wscript object.
You can script anything! Fig 5 A Sample VBSCRIPT Class Definition: DemoClass.vbs
class DemoClass public sub class_initialize msgbox "Construction in progress",vbOkOnly,"class_initialize" end sub public sub class_terminate msgbox "Destruction in progress",vbOkOnly,"class_terminate" end sub public sub showTime() msgbox Now(),vbOkOnly,"showTime" end sub public function getTime() getTime = Now() end function end class
Page 4 of 16
Next we need to declare a reference. This is just a placeholder that we can use to later address the objects members (methods and properties). Fig 6 Declaring an object reference
dim objRef
Finally, lets call the constructor to create the object and tie it to our reference. If this were a COM object we could also have used the CreateObject method instead of the NEW keyword. Note that Visual Basic Script uses the SET keyword to assign a value to an object reference. The class_initialize is invoked each time the class is instantiated into an object. Fig 7 Calling the DemoClass Initializer (Constructor)
set objRef = new DemoClass
Finally we can use the reference to call our objects methods and properties using the dot notation. Each public member of the object is available by following the object reference with a period followed by the member name. Fig 8 Calling an objects public methods
objRef.showTime msgbox objRef.getTime(),vbOkOnly,"Calling getTime"
Page 5 of 16
The WScript object allows you to: create objects, connect to objects, disconnect from objects, sync events, stop a script's execution programmatically, output information to the default output device (either a Windows dialog box or the command console). You create a WshShell object whenever you want to run a program locally, manipulate the contents of the registry, create a shortcut, or access a system folder. The WshShell object provides the Environment collection. This collection allows you to handle environmental variables (such as WINDIR, PATH, or PROMPT). You create a WshNetwork object when you want to connect to network shares and network printers, disconnect from network shares and network printers, map or remove network shares, or access information about a user on the network. The FileSystemObject is used to provide access to a computers file system.
Limited Input and Output to the Windows Desktop Inputbox, Msgbox, and wshShell.PopUp:
For returning input text from the user, VBSCRIPT provides an INPUTBOX function that accepts three string values as input parameters: a prompt, a title for the window caption, and a default value. If the OK button is clicked, the value entered by the user is returned as a string. If the CANCEL button is clicked a zero length string is returned. Fig 9 InputBox Dialog
Page 6 of 16
The MSGBOX also accepts three input parameters: a message to be displayed, a button and icon value, and a title for the caption of the dialog window. It displays a dialog box that waits for the user to click a button before returning to the script. Unlike INPUTBOX the response that is returned is not text, but the numeric value corresponding to the button that was clicked. These numeric values are represented by mnemonic constants. Fig 10 MsgBox Dialog
dim response dim msg dim title msg = "Continue?" title = "Confirm" response=msgbox(msg,vbYesNo+vbInformation,title) If response = vbYes then Else ' No was clicked! End if
dim btnReturn dim waitSeconds dim buttons dim icon dim wshShell Set wshShell = CreateObject("Wscript.Shell") buttons = vbOkOnly icon = vbInformation waitSeconds = 10 btnReturn = wshShell.Popup(msg, waitSeconds, title, buttons + icon)
Page 7 of 16
The following constants are used with the MsgBox function to identify which button a user has selected. Fig 13 MsgBox Constant Value vbOK 1 vbCancel 2 vbAbort 3 vbRetry 4 vbIgnore 5 vbYes 6 vbNo 7 Constants returned by the MsgBox Dialog Description OK button was clicked. Cancel button was clicked. Abort button was clicked. Retry button was clicked. Ignore button was clicked. Yes button was clicked. No button was clicked.
Page 8 of 16
The DesktopIO class simply provides an encapsulation around the MSGBOX and INPUTBOX functions. While this was definitely not necessary it provides a simple example of the CLASS statement and the use of both a SUB and FUNCTION as methods of the class. In VBSCRIPT, a method created using the SUB keyword cannot return a value, while a method created as a FUNCTION returns a value by setting the name of the FUNCTION equal to the return value before exiting. Fig 15 DesktopIO Class encapsulates MsgBox and InputBox
' ' Class DesktopIO ' Class DesktopIO public sub alert(msg,title) msgbox msg,vbOkOnly+vbInformation,title end sub public function prompt(msg,title,defaultValue) prompt=inputbox(msg,title,defaultValue) end function End Class
The UserInfo class is an example of encapsulating both data and behavior together. All data items are hidden from direct access outside of the class by using the PRIVATE access modifier. The SUBs CLASS_INITIALIZE and CLASS_TERMINATE are used to instantiate and then release the object references that are used by the class. This class also provides examples of: a READ/WRITE property, currentDirectory. a public method, showDir, which is used to display the directory contents. a private method, show, which acts as a wrapper around the wshShell.PopUp method.
Page 9 of 16
public sub class_initialize set wshShell = CreateObject("Wscript.Shell") set wshNetwork = CreateObject("Wscript.Network") set fso = CreateObject("Scripting.FileSystemObject") set io = new DesktopIO strDomainName = WshNetwork.UserDomain strComputerName = WshNetwork.ComputerName strUserName = WshNetwork.UserName strCurrentDirectory = WshShell.CurrentDirectory call show("Hello " & strUserName & vbCrLf & _ "Logged in at: " & _ "\\" & strDomainName & "\" & strComputerName & vbCrLf & _ "Current folder: " & _ strCurrentDirectory & _ "","UserInfo") end sub public sub class_terminate call show("Goodbye " & strUserName,"UserInfo") set wshShell = Nothing set wshNetwork = Nothing set fso = Nothing set io = Nothing end sub public property GET currentDirectory() currentDirectory = strCurrentDirectory end property public property LET currentDirectory(value) WshShell.CurrentDirectory = value strCurrentDirectory = WshShell.CurrentDirectory call show("Current folder: " & _ strCurrentDirectory & _ "","UserInfo") end property public sub showDir() dim folder dim file dim fileList set folder = fso.GetFolder(strCurrentDirectory) fileList = "" for each file in folder.Files fileList = fileList & file.name & vbCrLf next call io.alert(fileList,"Dir for " & strCurrentDirectory) end sub private function show(msg,title) dim btnReturn dim waitSeconds dim buttons dim icon buttons = vbOkOnly icon = vbInformation waitSeconds = 10 btnReturn = wshShell.Popup(msg, waitSeconds, title, buttons + icon) show = btnReturn end function End Class
Page 10 of 16
Creating and Reading ASCII files FileSystemObject and the TextStream Object:
The FileSystemObject is used to provide access to a computers file system. Two of its methods will allow us to create a TextStream object. The TextStream object is used to provide sequential access to a file. You can create a new file or overwrite an existing file by using the FileSystemObject.CreateTextFile method. You can open both a new and existing file by using the FileSystemObject.OpenTextFile method. Fig 17 TextStream Object (created by FileSystemObject methods) Methods: Properties:
Close Method (FileSystemObject object) Read Method ReadAll Method ReadLine Method Skip Method SkipLine Method Write Method WriteBlankLines Method WriteLine Method
Page 11 of 16
private sub Class_Initialize ForReading = 1 ForWriting = 2 ForAppending = 8 Set fso = CreateObject("Scripting.FileSystemObject") End sub private sub Class_Terminate end sub public function openInput(s) Set ts = fso.OpenTextFile(s, ForReading, True) end function public function openOutput(s) Set ts = fso.OpenTextFile(s, ForWriting, True) end function public function openAppend(s) Set ts = fso.OpenTextFile(s, ForAppending, True) end function public function getLine() Dim s s = ts.readLine() getLine = s end function public function putLine(s) ts.WriteLIne(s) end function public function close() ts.Close end function public Property GET EOF() EOF = ts.AtendOfStream End property end Class
You can script anything! Fig 20 ReadFile.html using an HTML page for presentation
<html>
Page 12 of 16
<head><title>Read File</title></head> <script language="vbscript" src="TextIO.vbs"> </script> <script language="vbscript"> option explicit sub readFile() dim io dim s dim f f = InputFile.value set io = new TextIO io.openInput(f) s = "" do s = s & io.getLine() & vbCrlf loop until io.EOF io.close contentName.innerText = f content.innerText = s end sub </script> <body> <font face='Arial' size=4> Click BROWSE to select a file: <input type=file id=InputFile /> <br clear=all /> Click READ/SHOW to view the selected file: <input type=button id=btnRead value='Read/Show' onClick='readFile()' /> <br clear=all /> <table border=1 align=center cellspacing=0 cellpadding=10> <tr> <td> <font face='Arial' size=4> <div id=contentName></div> </font> </td> </tr> <tr> <td> <font face='Courier New'> <div id=content></div> </font> </td> </tr> </table> </font> </body> </html>
You can script anything! Fig 21 SystemReboot.vbs Using the WMI API
Option Explicit '-----------------' ' SystemReboot.vbs ' Written by John Papproth ' Reboots after 10 seconds ' '-----------------Dim obj Set obj = new SysCmd Call obj.Reboot
Page 13 of 16
' ' SysCmd Class ' Methods: Logoff,Shutdown,Reboot,Poweroff,Confirm,Notify,Shell ' Class SysCmd '--------------------------------------------------------------' ' private: ' wshNetwork ' wshShell ' ' Private Sub Class_Initialize ' Private Sub Class_Terminate ' Private Sub Win32Shutdown(opt) ' Private Function popup(Prompt,Title,SecondsToWait,Buttons,Icons) ' ' public: ' Public Sub Logoff() ' Public Sub Shutdown() ' Public Sub Reboot() ' Public Sub Poweroff() ' Public Function Confirm(Prompt,Title,SecondsToWait) ' Public Sub Notify(Prompt,Title,SecondsToWait) ' Public Sub Shell(cmdString) ' '--------------------------------------------------------------private wshNetwork private wshShell Private Sub Class_Initialize set wshNetwork = CreateObject("Wscript.Network") Set wshShell = CreateObject("Wscript.Shell") End Sub Private Sub Class_Terminate ' Nothing to do here! End Sub Private Sub Win32Shutdown(opt) if Confirm("Continue?","Shutting down...",10) then dim objWMIService dim strComputer dim colItems dim objOperatingSystem strComputer = "." Set objWMIService = GetObject("winmgmts:" & _ "{impersonationLevel=impersonate,(Shutdown)}!\\" & _ strComputer & _ "\root\cimv2") set colItems = objWMIService.ExecQuery( _ "Select * from Win32_OperatingSystem" _ ) for each objOperatingSystem in colItems objOperatingSystem.Win32Shutdown(opt) next end if End Sub Public Sub Logoff() const LOGOFF = 0 Win32Shutdown(LOGOFF) End Sub Public Sub Shutdown() const SHUTDOWN = 1 Win32Shutdown(SHUTDOWN)
Page 14 of 16
End Sub Public Sub Reboot() const REBOOT = 2 Win32Shutdown(REBOOT) End Sub Public Sub Poweroff() const POWEROFF = 8 Win32Shutdown(POWEROFF) End Sub Private Function popup(Prompt,Title,SecondsToWait,Buttons,Icons) dim btnReturn btnReturn = wshShell.Popup( _ Prompt, _ SecondsToWait, _ Title, _ Buttons + Icons) popup = btnReturn End Function Public Function Confirm(Prompt,Title,SecondsToWait) if popup(Prompt,Title, SecondsToWait, vbYesNo, vbQuestion) = vbNo then Confirm=false else Confirm=true end if End Function Public Sub Notify(Prompt,Title,SecondsToWait) Call popup(Prompt, Title, SecondsToWait, vbOkOnly, vbInformation) End Sub Public Sub Shell(cmdString) wshShell.run(cmdString) End Sub End Class
Page 15 of 16
Each office application has a macro recording facility that creates VBA as you are manually performing the steps (such as changing fonts, saving files, etc). See the Tools/Macro menu under your office application to try this. After recording a macro in VBA you can then view the recorded VBA statements and change them into a stand alone VBSCRIPT by qualifying the object references with your script application object name (objExcel in my example above).
milliseconds = 500
Set System = CreateObject("Extra.System") if System is Nothing Then Msgbox "Could not create the System Object", _ vbOkOnly+vbCritical,"Get Screen" Exit Sub End If Set Session = System.ActiveSession if Session is Nothing Then Msgbox "Could not create the Session Object", _ vbOkOnly+vbCritical,"Get Screen" Exit Sub End If Set Screen = Session.Screen Call Screen.SendKeys("TIME<Enter>") ' Can be any HOST command Call Screen.WaitHostQuiet(milliseconds) Rows = Screen.Rows() Cols = Screen.Cols() Buffer = Screen.GetString(1,1,Rows*Cols) Lines = "" For Row = 1 to Rows Line = Mid(Buffer, ((Row-1)*Cols) + 1, Cols) Lines = Lines & Line & vbCrlf Next Msgbox Lines,vbOkOnly+vbInformation,"Screen" End Sub
Page 16 of 16
Resources:
http://msdn.microsoft.com/scripting http://msdn.microsoft.com/library/default.asp?url=/library/en-us/dnanchor/html/anch_wmi.asp http://www.activestate.com/perl