Visual Basic Notes

Must Watch!



VBScript Scripting Techniques Creating Scripts that Can Be Used by WSH VBScript Reference access C function from Visual Basic Call Statement calling JavaScript from VB from Web Forms page VB Form Running Python script call external Python script from Visual Scripting VBreference ASPTutorial VBScriptSamples VBScript Tutorial VBScript forum free vbs code vbsedit Visual Basic Getting Started . vbtutor . vbcode


VBScript is being deprecated

VBScript commands VBScript is being deprecated (Oct 2023). In future releases of Windows client, VBScript will be available as a feature on demand before its eventual removal from the operating system. It has not yet been deprecated from Windows Server. VBScript How-to guides and examples

wscript

windows commands wscript A-Z Index of Windows VBScript commands Windows Commands Syntax wscript [<scriptname>] [/b] [/d] [/e:<engine>] [{/h:cscript|/h:wscript}] [/i] [/job:<identifier>] [{/logo|/nologo}] [/s] [/t:<number>] [/x] [/?] [<ScriptArguments>] PARAMETERS Parameter Description scriptname Specifies the path and file name of the script file. /b Specifies batch mode, which does not display alerts, scripting errors, or input prompts. This is the opposite of /i. /d Starts the debugger. /e Specifies the engine that is used to run the script. This lets you run scripts that use a custom file name extension. Without the /e parameter, you can only run scripts that use registered file name extensions. For example, if you try to run this command: cscript test.admin You will receive this error message: Input Error: There is no script engine for file extension .admin. One advantage of using nonstandard file name extensions is that it guards against accidentally double-clicking a script and running something you really did not want to run. This does not create a permanent association between the .admin file name extension and VBScript. Each time you run a script that uses a .admin file name extension, you will need to use the /e parameter. /h:cscript Registers cscript.exe as the default script host for running scripts. /h:wscript Registers wscript.exe as the default script host for running scripts. This is the default when the /h option is omitted. /i Specifies interactive mode, which displays alerts, scripting errors, and input prompts. This is the default and the opposite of /b. /job:<identifier> Runs the job identified by identifier in a .wsf script file. /logo Specifies that the Windows Script Host banner is displayed in the console before the script runs. This is the default and the opposite of /nologo. /nologo Specifies that the Windows Script Host banner is not displayed before the script runs. This is the opposite of /logo. /s Saves the current command prompt options for the current user. /t:<number> Specifies the maximum time the script can run (in seconds). You can specify up to 32,767 seconds. The default is no time limit. /x Starts the script in the debugger. ScriptArguments Specifies the arguments passed to the script. Each script argument must be preceded by a slash (/). /? Displays Help at the command prompt. Remarks Performing this task does not require you to have administrative credentials. Therefore, as a security best practice, consider performing this task as a user without administrative credentials. To open a command prompt, on the Start screen, type cmd, and then click command prompt. Each parameter is optional; however, you cannot specify script arguments without specifying a script. If you do not specify a script or any script arguments, wscript.exe displays the Windows Script Host Settings dialog box, which you can use to set global scripting properties for all scripts that wscript.exe runs on the local computer. The /t parameter prevents excessive running of scripts by setting a timer. When the time exceeds the specified value, wscript interrupts the script engine and ends the process. Windows script files usually have one of the following file name extensions: .wsf, .vbs, .js. If you double-click a script file with an extension that has no association, the Open With dialog box appears. Select wscript or cscript, and then select Always use this program to open this file type. This registers wscript.exe or cscript.exe as the default script host for files of this file type. You can set properties for individual scripts. See Windows Script Host overview for more information. Windows Script Host can use .wsf script files. Each .wsf file can use multiple scripting engines and perform multiple jobs.

The Windows Scripting Host

What you need to get started
What is the Windows Scripting Host (WSH)?
Scripting Files
A quick word about debugging and handling errors
The scripting host objects
Wscript Methods
Shell Object Properties and Methods
Network Object Properties and Methods
EnumNetworkDrives
EnumPrinterConnections
Summary
https://www.codemag.com/article/0001061/The-Windows-Scripting-Host Remember batch files? They were simple, easy to program, and very productive since many tasks could be automated. Windows still allows batch files, but batch files don't allow any control over the Windows shell and Windows environment. By introducing the Windows Scripting Host, Microsoft has introduced a script and COM based engine that can access the Windows Shell, the computer's environment and network settings using simple VBScript or JScript code. In addition you can even access any COM component, including your own. This column will introduce you to the basics of how the scripting host works and how you can incorporate its features into your Visual FoxPro Applications.

What you need to get started

The Windows Scripting Host ships with Windows 2000 and Windows 98, and is also available as part of the NT Option Pack when installed on Windows NT 4.0. Older Windows NT and 95 can download the Windows Scripting Host files from the Microsoft Website at: http://msdn.microsoft.com/scripting/. In addition to the core scripting engine, a series of whitepapers, code samples, and technical articles can be downloaded as well.

What is the Windows Scripting Host (WSH)?

The Windows Scripting Host is a language independent scripting engine. Scripting languages such as VBScript and JScript can be used to drive many processes. The same language that is used in client-side scripts in Internet Explorer (IE) or server-side scripts in Internet Information Server (IIS) can now be hosted by the Windows Operating System itself. Prior to the release of the WSH, the only scripting language that existed for Windows was MS-DOS batch files. Although powerful, batch files lacked the control over the Windows Operating System that is truly required. The WSH provides this capability.

Scripting Files

Unlike scripting in Active Server Pages, where the language can be specified with tags, the same is not true for script files used by the Windows Scripting Host. Instead, the WSH relies on the file extension to determine which language to use. If the script file ends in VBS, VBScript is used. If the script file ends in JS, JScript is used. The following files are simple hello world examples the point out the differences between VBScript and JScript: VBSscript: 'hello world.vbs Dim WSHShell Set WSHShell = WScript.CreateObject("WScript.Shell") WSHShell.Popup "Hello World" JScript: // hello world.js var WSHShell = WScript.CreateObject("WScript.Shell"); WSHShell.Popup("Hello World") The following is a more complex example that uses scripting to open and control Microsoft Excel: 'This VBScript File opens Excel and creates a workbook Dim objXL,oWorkbook Set objXL = WScript.CreateObject("Excel.Application") objXL.Visible = TRUE Set oWorkbook = objXL.WorkBooks.Add With objXL .Cells(1,1) = oWorkbook.Sheets.Count End With Running these script files is a very simple task. In Explorer, you can click the right mouse key over the file, and select Open. Alternatively, you can double-click the item in Explorer as well. Yet another alternative is to use the Run Method of the Windows Scripting Shell Object. This technique will be illustrated when the Shell Object is discussed in more detail. Furthermore, you can execute these script files directly from your applications using the ShellExecute() API simply by specifying the filename.

A quick word about debugging and handling errors

No programming environment is complete with a full-featured debugging environment and the Windows Scripting Host is no exception. As far as error handling is concerned, VBScript does not have a global error handler. Instead, errors need to be handled on an in-line basis. The following code demonstrates how to deal with errors on an in-line basis: On Error Resume Next dim objxl Set objXL = WScript.CreateObject("Excel.Application") objxl.foo ' reference a non-existent Excel Method If Err.Number > 0 Then Call ErrorProc End If Sub ErrorProc msgbox err.description End Sub If no error trapping exists, you will be prompted with a dialog asking if you wish to debug the application. Figure 1 illustrates how the code will appear in the script debugger. Figure 1 - The Microsoft Script Debugger uses the same IDE as Visual InterDev and Visual J++ 6.0

The scripting host objects

There are two primary objects contained within the Windows Scripting Host. The following code illustrates how these objects can be created: WSHshell = CreateObject("Wscript.Shell") WSHNetwork = CreateObject("Wscript.Network") Both the shell and network objects are hosted by the wshom.ocx ActiveX Control. Complete documentation for the WSHShell and WSHNetwork Objects can be found by navigating to the following URLS: For the WSHShell Object: http://www.microsoft.com/iis/support/iishelp/iis/htm/asp/wsho7t84.htm For the WSHNetwork Object: http://www.microsoft.com/iis/support/iishelp/iis/htm/asp/wsho20qc.htm

Wscript Methods

CreateObject (strProgid [,strPrefix]) This method creates an instance of an automation server. This article began with an example of using the Shell Object to create an instance of Microsoft Excel. The ability also exists to create instances of your own COM Components as well. The first parameter specifies the ProgID of the automation server instance you wish to create. oMyObject = Wscript.Createobject("MyObject.MyClass") The second parameter relates to instances where the new object supports an event model. For example, if the object you create has an event called MyEvent, you can write a handler for the event. The only requirement is that a procedure prefix must be specified: oMyObject = Wscript.Createobject("MyObject.MyClass","eventhandler_") Sub eventhandler_myevent() 'Your custom event code goes here... End Sub ConnectObject (strObjName,strPrefix) The ConnectObject method allows developers to hook into the event model for objects that have already been created. To illustrate, an object called oMyObject already exists. The oMyObject object has an event called myevent. oMyObject = Wscript.Createobject("MyObject.MyClass") Wscript.ConnectObject oMyObject, "eventhandler_" Sub eventhandler_myevent() 'Your custom event code goes here... End Sub

DisconnectObject (ObjID)

The DisconnectObject method allows for the uncoupling of an object instance and an event handler. It is important to note that once the event handler is uncoupled, the object instance remains in tact. Wscript.DisconnectObject(oMyObject) Echo(...argN) The Echo Method provides a host independent mechanism for dialoging the user. Within the Windows GUI, where Wscript.EXE is used, the Echo Method is manifested as a Messagebox: Wscript.Echo "Cool" script files can also be run from the command prompt. If the previous example was contained in a file called FOO.VBS, the following code would display the word Cool on the command line: C:\Temp>cScript foo.vbs Microsoft (R) Windows Script Host Version 5.1 for Windows Copyright (C) Microsoft Corporation 1996-1999. All rights reserved. Cool

Sleep

The Sleep Method suspends program execution for a specified period of time. The following example suspends execution for 2 seconds before continuing: Wscript.Sleep 2000

Shell Object Properties and Methods

Environment: This property provides access to environment collection. Information such as number of processors, paths, OS, etc can be determined from this collection. oEnv = wshshell.environment For Each x In oEnv ?oEnv Next x The following is a partial listing of some typical environmental variables: NUMBER_OF_PROCESSORS OS PROCESSOR_ARCHITECTURE PROCESSOR_IDENTIFIER WINDIR So, to find out the number of processors: Numprocessors = oEnv.Item("NUMBER_OF_PROCESSORS") Like most collections, if you want to find out how many members are contained in the collection, you can refer to the Count Property: Numitems = oEnv.Count To be compliant with the Java Language, collections in the Windows Scripting Host also support the Length Property, which provides the same functionality as the Count Property: Numitems = oEnv.Length SpecialFolders: This property provides access to the collection of Windows Shell Folders. The following is a listing of folders: AllUsersDesktop AllUsersStartMenu AllUsersPrograms AllUsersStartup Desktop Favorites Fonts MyDocuments NetHood PrintHood Programs Recent SendTo StartMenu Startup Templates AllUsersDesktop AllUsersStartMenu AllUsersPrograms AllUsersStartup Desktop Favorites Fonts MyDocuments NetHood PrintHood Programs Recent SendTo StartMenu Startup Templates To find the actual path of the desktop folder, issue this line of code: DesktopPath = WSHShell.SpecialFolders("Desktop") CreateShortcut (strPathname) This method creates and returns a shortcut object. The following block of code illustrates how to create a desktop shortcut: */ Read desktop path using WshSpecialFolders object DesktopPath = WSHShell.SpecialFolders("Desktop") */ Create a shortcut object on the desktop MyShortcut = ; WSHShell.CreateShortcut(DesktopPath + "\Shortcut to MyFile.lnk") */ Set shortcut object properties and save it FileName = GetFile() If !Empty(FileName) FileDir = JustPath(FileName) With MyShortcut .TargetPath = Filename .WorkingDirectory = FileDir .Save EndWith Endif The CreateShortcut Method returns a WSHShortcut Object. This object is only exposed through the CreateShortcut Method. The WSHShortcut object has the following properties: Arguments - Parameters to a shortcut object. Description - A description of a shortcut object. Hotkey - The hot key of a shortcut object. IconLocation - The icon location of a shortcut object. TargetPath - The target path of a shortcut object. WindowStyle - The window style of a shortcut object. WorkingDirectory - The working directory of a shortcut object. The WSHShortcut Object only has one method, Save(), which saves the shortcut object to the file system. ExpandEnvironmentSettings (*strString)* This method expands a process environment variable and returns the result. A typical environment variable is WINDIR. The following code illustrates how this method works: Fullpath = WSHShell.ExpandEnvironmentStrings("%windir%\notepad.exe, 0") Popup (strText, [natSecondsToWait], [strTitle], [natType]) This method displays the Window MessageBox. Unlike the existing MessageBox Function, the Popup method accepts an optional argument to clear the dialog after a specified amount of time. The following line of code illustrates how the Popup Method works: WSHShell.Popup("Message",1,"Title",64) RegDelete(strName) RegRead(strName) RegWrite(strName, anyValue, [strType] ) The Windows Scripting Host Shell Object provides three methods for working with the Windows Registry. With these methods, entries can be created, written, read, and deleted. If you attempt to write to a key that does not exist, the key will be created. The following code illustrates how these three methods work: To create a new key: WSHshell.RegWrite("HKCU\Software\Microsoft\VisualFoxPro\6.0\Desktop\JVP",'Default Value') Then, to modify the value: WSHshell.RegWrite("HKCU\Software\Microsoft\VisualFoxPro\6.0\Desktop\JVP",'New Value') Next, to just read a value from a key: WSHshell.RegRead("HKCU\Software\Microsoft\VisualFoxPro\6.0\Desktop\JVP") Finally, to delete a key: WSHshell.RegDelete("HKCU\Software\Microsoft\VisualFoxPro\6.0\Desktop\JVP") Run(strCommand, [intWindowStyle], [blnWaitOnReturn]) The Run Method creates a new process that executes a specified command with a specified window style. In addition to being able to specify the command and the window style, a third parameter can be used to determine if script execution should pause until the new process has terminated. Applications windows can be started in several states. The following outlines the various options available: SW_HIDE = 0 SW_MINIMIZE = 6 SW_RESTORE = 9 SW_SHOW = 5 SW_SHOWMAXIMIZED = 3 SW_SHOWMINIMIZED = 2 SW_SHOWMINNOACTIVE = 7 SW_SHOWNA = 8 SW_SHOWNOACTIVATE = 4 SW_SHOWNORMAL = 1 The following code starts Notepad with a normal window: WSHshell.Run("notepad",1) This code starts Notepad with a maximized window. In addition, the user must close Notepad before control will return to Visual FoxPro: WSHshell.Run("notepad",3,.T.) Fully qualified paths can be used to denote a file to execute. The following code starts Visio: WSHshell.Run("D:\VISIO\VISIO32.EXE") Also, script files can be executed with the Run Method as well: WSHshell.Run("hello world.vbs") WSHshell.Run("hello world.js")

Network Object Properties and Methods

ComputerName: This property denotes the name of the computer. ComputerName = WSHNetwork.ComputerName UserDomain: This property denotes the domain to which the user belongs. DomainName = WSHNetwork.UserDomain UserName: This property denotes the ID of the currently logged-in user. UserName = WSHNetwork.UserName AddPrinterConnection(strLocalName, strRemoteName, [bUpdateProfile], [strUser], [strPassword] ) This method maps a network printer to a local resource. WSHNetwork.AddPrinterConnection("LPT1","\\server\printer_share",.T.,"UserID","Password") Of special interest here is the third parameter, bUpdateProfile. If this parameter is set to .T., the user profile for the local machine is updated to restore the printer mapping the next time the user logs onto the machine and network.

EnumNetworkDrives

This method returns a collection of drive mappings. The following code loops through the collection of network drive mappings: oDrives = WSHNetwork.EnumDriveMappings item = -1 For Each x In oDrives item = item + 1 If Mod(item,2) = 0 ?"Drive Letter: ",x Else ?"Network Resource: ",x Endif Next x Like other collections, the drive mapping collection supports both the Count and Length Properties, as well as the Item() Method.

EnumPrinterConnections

This method works just like the EnumNetworkDrives, with the exception that the collection returned represents printers, not drive mappings: item = -1 For Each x In oPrinters item = item + 1 If Mod(item,2) = 0 ?"Printer Name: ",x Else ?"Network Resource: ",x Endif Next x MapNetworkDrive( strLocalName, strRemoteName, [bUpdateProfile], [strUser], [strPassword] ) This method works just like the AddPrinterConnection Method, with the exception that a local drive to a network resource is created: WSHNetwork.MapNetworkDrive("z:","\\server\server_share",.T.,"User","Password") RemoveNetworkDrive(strName, [bForce], [bUpdateProfile] ) This method removes a specified network drive mapping. Optionally, you can force the removal even if the resource is being used. An optional third parameter specifies if the user profile should be updated: WSHNetwork.RemoveNetworkDrive("z:",.T.,.T.) Or WSHNetwork.RemoveNetworkDrive("\\server\server_share",.T.,.T.) RemovePrinterConnection( strName, [bForce], [bUpdateProfile] ) This method works just like the RemoveNetworkDrive method, with the exception that a printer resource is being removed: WSHNetwork.RemovePrinerConnection("LPT1",.T.,.T.) Or WSHNetwork.RemovePrinterConnection("\\server\printer_share",.T.,.T.) SetDefaultPrinter(strName) This method sets the default printer: WSHNetwork.SetDefaultPrinter("\\server\printer_share")

Summary

The ability to work with the Windows Registry, create desktop shortcuts, map and view network resources, all required you to know how to use extensive Windows API Functions, or a 3rd party DLL. The Windows Scripting Host provides a simple and elegant set of objects with simple interfaces that allow you to accomplish many of these tasks. Perhaps your application requires special Registry Entries. Perhaps you have been tasked with developing a utility that modifies the default printer or dynamically maps network resources. All of these tasks can easily be accomplished with the Windows Scripting Host. The good news is that the Windows Scripting Host is part of the Operating System beginning with Windows 98 and Windows 2000. For older systems you need to make sure WSH is installed on any client workstation that uses your application. One approach to this problem is to add a method to your application class that tests to see if the Windows Scripting Host is installed. If it is not, prompt the user through the process of both downloading and installing WSH. The Windows Scripting Host is yet another valuable tool to add to your toolbox!

Programming the Windows Script Host

Programming the Windows Script Host

Example: Scripting Internet Explorer

To give you a taste of the power and flexibility of scripting—particularly Automation programming—I'll close this chapter by showing you how to program a specific Automation server: Internet Explorer. You'll see that your scripts can control just about everything associated with Internet Explorer:
  • The position and dimensions of the window
  • Whether the menu bar, toolbar, and status bar are displayed
  • The current URL
  • Sending the browser backward and forward between navigated URLs
  • Displaying a Web Page

    To get started, I'll show you how to use the InternetExplorer object to display a specified URL. You use the Navigate method to do this, and this method uses the following syntax:InternetExplorer.Navigate URL [, Flags,] [ TargetFramename] [, PostData] [ ,Headers]
    InternetExplorer A reference to the InternetExplorer object with which you're working.
    URL The address of the web page you want to display.
    Flags One of (or the sum of two or more of) the following integers that control various aspects of the navigation:
    1Opens the URL in a new window
    2Prevents the URL from being added to the history list
    4Prevents the browser from reading the page from the disk cache
    8Prevents the URL from being added to the disk cache
    TargetFrameName The name of the frame in which to display the URL.
    PostData Specifies additional POST information that HTTP requires to resolve the hyperlink. The most common uses for this argument are to send a web server the contents of a form, the coordinates of an imagemap, or a search parameter for an ASP file. If you leave this argument blank, this method issues a GET call.
    Headers Specifies header data for the HTTP header.
    Here's an example: Set objIE = CreateObject("InternetExplorer.Application") objIE.Navigate "http://www.microsoft.com/"

    Navigating Pages

    Displaying a specified web page isn't the only thing the InternetExplorer object can do. It also has quite a few methods that give you the ability to navigate backward and forward through visited web pages, refresh the current page, stop the current download, and more. Here's a summary of these methods:
    GoBack Navigates backward to a previously visited page
    GoForward Navigates forward to a previously visited page
    GoHome Navigates to Internet Explorer's default Home page
    GoSearch Navigates to Internet Explorer's default Search page
    Refresh Refreshes the current page
    Refresh2 Refreshes the current page using the following syntax:
    Refresh2 (Level)
    LevelA constant that determines how the page is refreshed:
    0Refreshes the page with a cached copy
    1Refreshes the page with a cached copy only if the page has expired
    3Performs a full refresh (doesn't use a cached copy)
    Stop Cancels the current download or shuts down dynamic page objects, such as background sounds and animations.

    Using the InternetExplorer Object's Properties

    Here's a summary of many of the properties associated with the InternetExplorer object:
    BusyReturns True if the InternetExplorer object is in the process of downloading text or graphics. This property returns False when a download of the complete document has finished.
    FullScreenA Boolean value that toggles Internet Explorer between the normal window and a full-screen window in which the title bar, menu bar, toolbar, and status bar are hidden.
    HeightReturns or sets the window height.
    LeftReturns or sets the position of the left edge of the window.
    LocationNameReturns the title of the current document.
    LocationURLReturns the URL of the current document.
    MenuBarA Boolean value that toggles the menu bar on and off.
    StatusBarA Boolean value that toggles the status bar on and off.
    StatusTextReturns or sets the status bar text.
    ToolBarA Boolean value that toggles the toolbar on and off.
    TopReturns or sets the position of the top edge of the window.
    TypeReturns the type of document currently loaded in the browser.
    VisibleA Boolean value that toggles the object between hidden and visible.
    WidthReturns or sets the window width.

    Running Through a Sample Script

    To put some of the properties and methods into practice, Listing 12.10 shows a sample script.

    Example 12.10. A Script That Puts the InternetExplorer Object Through Its Paces

    Option Explicit Dim objIE, objWshShell, strMessage, intResult ' Set up the Automation objects Set objIE = WScript.CreateObject("InternetExplorer.Application") Set objWshShell = WScript.CreateObject("WScript.Shell") ' Navigate to a page and customize the browser window objIE.Navigate "http://www.wordspy.com/" objIE.Toolbar = False objIE.StatusBar = False objIE.MenuBar = False ' Twiddle thumbs while the page loads Do While objIE.Busy Loop ' Get the page info strMessage = "Current URL: " & objIE.LocationURL & vbCrLf & _ "Current Title: " & objIE.LocationName & vbCrLf & _ "Document Type: " & objIE.Type & vbCrLf & vbCrLf & _ "Would you like to view this document?" ' Display the info intResult = objWshShell.Popup(strMessage, , "Scripting IE", vbYesNo + vbQuestion) ' Check the result If intResult = vbYes Then ' If Yes, make browser visible objIE.Visible = True Else ' If no, bail out objIE.Quit End If Set objIE = Nothing Set objWshShell = Nothing The script begins by creating instances of the InternetExplorer and WScript Shell objects. The Navigate method displays a page, and then turns off the toolbar, status bar, and menu bar. A Do...Loop checks the Busy property and loops while it's True. In other words, this loop won't exit until the page is fully loaded. A string variable is used to store the URL, the title, and type of the page, and this string is then displayed in a Popup box, which also asks whether the user wants to see the page. If the user clicks the Yes button, the browser is made visible; if the user clicks the No button, the Quit method shuts down the browser.

    Difference between cscript and wscript

    Windows Script Host (WSH) has been part of Windows since Windows NT4. Windows Script Host provides architecture for building dynamic scripts that consist of a core object model, scripting hosts, and scripting engines. The key components of Windows Script Host are CSCript, WScript, WSH ActiveX Control and Scripting engines. WSH ActiveX Control: An ActiveX control that provides the core object model for the scripting host. Scripting engines Scripting engines provide the core functions, objects, and methods for a particular scripting language. VBScript and JScript scripting engines are installed by default on Windows. CSCript and WScript are executables for the scripting host that are used to run the scripts. CSCript and WScript are both interpreters to run VBScript (and other scripting languages like JScript) on the Windows platform. CSScript is for console applications and WScript is for Windows applications. The Kernel checks a flag in the executable to determine which When starting using CreateProcess, if it is a console application, the kernel will create a console window for it if the parent process doesn't have one, and attach the STDIN and STDOUT and STDERR to the console. If it is a Windows application, no console will be created and STDIN, STDOUT and STDERR will be closed by default. If you want your script to have a console window, use CSCRIPT.EXE. If you want it to NOT have a console window, use WSCRIPT.EXE. This also affects some behaviors, such as the WScript.Echo command. In a CSCRIPT.EXE this writes a line to the console window. In WSCRIPT.EXE it shows a messagebox. When using CScript.exe: When we execute the above VBScript with CScript.exe, it displays hi (called through WScript.echo) in command prompt. When using WScript.exe: When we execute the above VBScript with WScript.exe, it displays hi (called through WScript.echo) in MessageBox. MsgBox will display a message box in both cases. The WScript word in WScript.echo is not related to WScript.exe. WScript.exe -> a command line executable for WSH. WSCript -> an object in Core Object Model provided in WSH. Usage of CSCript.exe: The command line options for CSCript.exe are in this screenshot. [ ] refers to optional data, i.e., not mandatory. Usage of WSCript.exe: The command line options for WSCript.exe in this screenshot. Again, [ ] refers to optional data, i.e., not mandatory. In Windows, an executable is either a console application or a Windows application (or a SFU or Native application, but that doesn't matter here). The kernel checks a flag in the executable to determine which. When starting using CreateProcess WinAPI function, if it is a console application, the kernel will create a console window for it if the parent process doesn't have one, and attach the STDIN, STDOUT and STDERR streams to the console. If it is a Windows application, no console will be created and STDIN, STDOUT and STDERR will be closed by default. WSCRIPT.EXE and CSCRIPT.EXE are almost exactly identical, except that one is flagged as a windows application and the other is flagged as a console application (Guess which way around!). So the answer is: If you want your script to have a console window, use CSCRIPT.EXE. If you want it to NOT have a console window, use WSCRIPT.EXE. This also affects some behaviors, such as the WScript.Echo command. In a CSCRIPT.EXE this writes a line to the console window. In WSCRIPT.EXE it shows a messagebox. For your application I suggest CSCRIPT.EXE. I think you should also look at PuTTY and PLink, and you should also see this here: vbscript output to console Wscript.Echo "Like this?" If you run that under wscript.exe (the default handler for the .vbs extension, so what you'll get if you double-click the script) you'll get a "MessageBox" dialog with your text in it. If you run that under cscript.exe you'll get output in your console window. You can directly use on the wscript.exe the function MsgBox("text") or MsgBox(object.property) but Wscript.Echo is easier to write. There are five ways to output text to the console: Dim StdOut : Set StdOut = CreateObject("Scripting.FileSystemObject").GetStandardStream(1) WScript.Echo "Hello" WScript.StdOut.Write "Hello" WScript.StdOut.WriteLine "Hello" Stdout.WriteLine "Hello" Stdout.Write "Hello" WScript.Echo will output to console but only if the script is started using cscript.exe. It will output to message boxes if started using wscript.exe. WScript.StdOut.Write and WScript.StdOut.WriteLine will always output to console. StdOut.Write and StdOut.WriteLine will also always output to console. It requires extra object creation but it is about 10% faster than WScript.Echo.

    WScript.GetObject

    Retrieve an Automation object Syntax Set objObject = Wscript.GetObject(strPathname [,strProgID] ], [strPrefix]) Arguments: strPathname : The pathname of the file containing the object to retrieve. (required) strProgID : The program identifier (ProgID) of the object. strPrefix : A prefix for subroutine names (optional) e.g. if strPrefix is "MYOBJ_" and the object fires an event named "OnBegin," WSH calls the subroutine "MYOBJ_OnBegin" objObject is an Automation object. GetObject is a wscript method. Example Open a copy of the Excel application: Set objExcel = CreateObject("Excel.Application") objExcel.Visible = True objExcel.Workbooks.Add objExcel.Cells(1, 1).Value = "Some demonstration text" Open an Excel file: Set objExcelFile = GetObject("C:\demo\example.xlsx") WScript.Echo objExcelFile.Name objExcelFile.Close “When I take action I'm not going to fire a $2 million missile at a $10 empty tent and hit a camel in the butt. It's going to be decisive” ~ George W Bush, 2001

    wscript.echo embed a new line / "CR" in a text string

    LF = chr(10) wscript.echo "Hello world", LF

    WScript.echo without a Carriage Return

    Wscript.Echo always includes a carriage return. If you want to write several outputs on the same line, you have to use the "StdOut" property of the scrtipt host Here's a small example on how to use "StdOut" and "StdIn" Wscript.Stdout.Write ("Please enter your name: " Wscript.StdOut.Write "Your name is: " & Wscript.StdIn.ReadLin Please notice that "StdOut" also has a "WriteLine" method that also sends a carriage return like "Wscript.Echo". If you want to have a carriage return when using "StdOut.Write", you have to write a "vbCrLf" at the end, too

    activeX component can't create object 'Wscript.Timer'

    The error message "ActiveX component can't create object 'WScript.Timer'" typically occurs when the WScript.Timer object is not available or registered on the system. This object is not natively available in VBScript. If you encounter this error, you can use an alternative approach to implement a timer in VBScript. One way to achieve this is by using the WScript.Sleep method in a loop to create a timer-like behavior. Here's an example: Set objShell = CreateObject("WScript.Shell") ' Define timer duration in milliseconds Dim timerDuration timerDuration = 5000 ' 5 seconds ' Define repeat count Dim repeatCount repeatCount = 3 ' Repeat 3 times ' Loop for the desired number of repetitions For i = 1 To repeatCount ' Display a message objShell.Popup "Timer expired!", , "Timer" ' Wait for the specified duration WScript.Sleep timerDuration Next In this example, the WScript.Sleep method is used to pause the script execution for the specified duration. After the sleep period, a message box is displayed. The loop allows you to repeat the timer functionality as many times as needed. Save the script with a .vbs extension and run it. It will display the message box after the specified duration and repeat it for the desired number of times. Please note that the WScript.Sleep method suspends the entire script execution, so it may not be suitable for scenarios where you need to perform other tasks concurrently.

    WScript.ScriptName

    The ScriptName property is read only and returns the filename of the script currently being executed. Examples Code: WScript.Echo "Name of current script =", WScript.ScriptName Output: Name of current script = test.vbs

    WScript.Arguments

    Return command-line parameters. Syntax WScript.Arguments WScript.Arguments(n) WScript.Arguments.item(n) n = Return the single argument n counting from 0 To pass named arguments use: WScript.Arguments.named In addition to the argument itself : MyObject.item(I)you can also retrieve a count or length: MyObject.Count MyObject.Length The default property is .item Examples C:> cscript demo.vbs arg1 value2 33 456 "Last Arg" [demo.vbs] ' Store the arguments in a variable: Set objArgs = Wscript.Arguments 'Count the arguments WScript.Echo objArgs.Count ' Display all command-line arguments For Each strArg in objArgs WScript.Echo strArg Next ' Display the first 3 command-line arguments For I = 0 to 2 Wscript.Echo objArgs(I) Next 'Display just the third argument Wscript.Echo objArgs(2) 'Or without the reference WScript.Echo "The third argument is", WScript.Arguments(2)

    VBScript Tutorials

    VBScript Tutorial VBScript For Each VBScript 实例 Introduction / What is it? VBScript Tutorials Notepad++, Launch with Default Program VBScript Tutorials Variables VBScript Tutorials Option Explicit / Dim / Comments VBScript Tutorials Arithmetic Operators VBScript Tutorials Concatenation VBScript Tutorials Relational Operators VBScript Tutorials ArrayList ( methods & properties ) VBScript Examples Environment Variables ( add; change; remove ) VBScript Examples FormatString Class VBScript Tutorials Message Box - Numbers (MsgBox) Message Box - Constants (MsgBox) If - ElseIf - Else - Then Statements Vertical & Horizontal Spacing Run Command Input Box (InputBox) Do Loops SendKeys Len - Left - Right Script Directory Subroutines Internet Explorer - SendKeys (Automation) Internet Explorer - HTML (Automation) File - Folder - Exists Copy - Move - Rename - Files & Folders Create Shortcuts Special Folders Create - Delete - Files & Folders Open Files (OpenTextFile) Read Files (OpenTextFile) Write Files (OpenTextFile) Append Files (OpenTextFile) Replace Words (Replace Command) Replace Lines (Replace Command) Replace using InputBox (Replace Command) With Command Get File - Folder (Properties) Get File - Folder (Attributes) Get File - Folder (Methods) For - Each - Next - Loops Internet Explorer - Existing Window (Automation) Select Case Functions AppActivate - Maximize - Minimize - Restore - Close - Windows Kill - Create - Process Cancel Input Box (InputBox) BrowseForFolder BrowseForFile Command Prompt (Arguments) Date Functions Copy All Files In Subfolders Mid - Split - InStr LCase - UCase - Trim Creating Arrays (Arrays) Adding to an Array (Arrays) Math Functions Formatting Numbers & Dates Repeating Characters - String() - Space() TypeName - VarType - IsTests Dropped Files - Folders (Arguments) Execute - Read from another vbscript file. Run As Administrator Classes Unzip - Extract Compressed Files Make your computer talk/speak (SAPI) Change the voice/gender (SAPI) Read the registry (Regedit) Write to the registry (Regedit) Delete items in the registry (Regedit) Multidimensional Arrays (Arrays) Join Multidimensional Array (Arrays) Adding and Viewing (Dictionary) Change and Remove (Dictionary) Multidimensional (Dictionary) Manipulating Clipboard Text Multiline String Formatter (create code with code) RegExp (Test & Replace) RegExp (Execute) RegExp ( Submatches ) Regular Expressions ( [] {} () ? ) Regular Expressions ( [^] + * \w \d \s \b ) Regular Expressions ( ^ $ \escape ) Run as Admin ( without UAC prompt ) VBScript Tutorials

    01 - Introduction / What is it? VBScript Tutorials

    02 - Notepad++, Launch with Default Program VBScript Tutorials

    03 - Variables VBScript Tutorials

    04 - Option Explicit / Dim / Comments VBScript Tutorials

    05 - Arithmetic Operators VBScript Tutorials

    06 - Concatenation VBScript Tutorials

    07 - Relational Operators VBScript Tutorials

    ArrayList ( methods & properties ) VBScript Examples

    Environment Variables ( add; change; remove ) VBScript Examples

    FormatString Class VBScript Tutorials

    Part 1 Message Box - Numbers (MsgBox)

    Part 2 Message Box - Constants (MsgBox)

    Part 3 If - ElseIf - Else - Then Statements

    Part 4 Vertical & Horizontal Spacing

    Part 5 Run Command

    Part 6 Input Box (InputBox)

    Part 7 Do Loops

    Part 8 SendKeys

    Part 9 Len - Left - Right

    Part 10 Script Directory

    Part 11 Subroutines

    Part 12 Internet Explorer - SendKeys (Automation)

    Part 13 Internet Explorer - HTML (Automation)

    Part 14 File - Folder - Exists

    Part 15 Copy - Move - Rename - Files & Folders

    Part 16 Create Shortcuts

    Part 17 Special Folders

    Part 18 Create - Delete - Files & Folders

    Part 19 Open Files (OpenTextFile)

    Part 20 Read Files (OpenTextFile)

    Part 21 Write Files (OpenTextFile)

    Part 22 Append Files (OpenTextFile)

    Part 23 Replace Words (Replace Command)

    Part 24 Replace Lines (Replace Command)

    Part 25 Replace using InputBox (Replace Command)

    Part 26 With Command

    Part 27 Get File - Folder (Properties)

    Part 28 Get File - Folder (Attributes)

    Part 29 Get File - Folder (Methods)

    Part 30 For - Each - Next - Loops

    Part 31 Internet Explorer - Existing Window (Automation)

    Part 32 Select Case

    Part 33 Functions

    Part 34 AppActivate - Maximize - Minimize - Restore - Close - Windows

    Part 35 Kill - Create - Process

    Part 36 Cancel Input Box (InputBox)

    Part 37 BrowseForFolder

    Part 38 BrowseForFile

    Part 39 Command Prompt (Arguments)

    Part 40 Date Functions

    Part 41 Copy All Files In Subfolders

    Part 42 Mid - Split - InStr

    Part 43 LCase - UCase - Trim

    Part 44 Creating Arrays (Arrays)

    Part 45 Adding to an Array (Arrays)

    Part 46 Math Functions

    Part 47 Formatting Numbers & Dates

    Part 48 Repeating Characters - String() - Space()

    Part 49 TypeName - VarType - IsTests

    Part 50 Dropped Files - Folders (Arguments)

    Part 51 Execute - Read from another vbscript file.

    Part 52 Run As Administrator

    Part 53 Classes

    Part 54 Unzip - Extract Compressed Files

    Part 55 Make your computer talk/speak (SAPI)

    Part 56 Change the voice/gender (SAPI)

    Part 57 Read the registry (Regedit)

    Part 58 Write to the registry (Regedit)

    Part 59 Delete items in the registry (Regedit)

    Part 60 Multidimensional Arrays (Arrays)

    Part 61 Join Multidimensional Array (Arrays)

    Part 62 Adding and Viewing (Dictionary)

    Part 63 Change and Remove (Dictionary)

    Part 64 Multidimensional (Dictionary)

    Part 65 Manipulating Clipboard Text

    Part 66 Multiline String Formatter (create code with code)

    Part 70 RegExp (Test & Replace)

    Part 71 RegExp (Execute)

    Part 72 RegExp ( Submatches )

    Regular Expressions ( [] {} () ? )

    Regular Expressions ( [^] + * \w \d \s \b )

    Regular Expressions ( ^ $ \escape )

    Run as Admin ( without UAC prompt ) VBScript Tutorials

    VB Scraper

    scrape from webpages using VBA Scraping website using vba

    Visual Basic sample

    counter = 2 Do counter=counter+1 MsgBox("Hello World!" & cstr(counter)) Loop until counter>10 save as test.vbs and click to run not work: Beep() Threading.Thread.Sleep(250) For Each P As Process In System.Diagnostics.Process.GetProcessesByName("cmd") P.Kill() Next

    System Beep in Batch/VB Script

    WScript.StdOut.Write Chr(7)

    VBS Play Sound

    play MP3 files in VBScript using Windows Media Player scripting object, WMPlayer.OCX Dim oPlayer Set oPlayer = CreateObject("WMPlayer.OCX") oPlayer.URL = "C:\welcome.mp3" ' Play audio oPlayer.controls.play While oPlayer.playState <> 1 ' 1 = Stopped WScript.Sleep 100 Wend ' Release the audio file oPlayer.close

    VBS script to play sound repeatedly

    strSoundFile = "C:\Temp\test.wav" Set objShell = CreateObject("Wscript.Shell") strCommand = "sndrec32 /play /close " & chr(34) & strSoundFile & chr(34) objShell.Run strCommand, 0, True Wscript.Sleep 1000

    to Run VBScript on Windows

    cscript hello.vbs Execute the VBS script by double-clicking the file

    Date/Time Functions

    CDate Converts a valid date and time expression to the variant of subtype Date Date Returns the current system date DateAdd Returns a date to which a specified time interval has been added DateDiff Returns the number of intervals between two dates DatePart Returns the specified part of a given date DateSerial Returns the date for a specified year, month, and day DateValue Returns a date Day Returns a number that represents the day of the month (between 1 and 31, inclusive) FormatDateTime Returns an expression formatted as a date or time Hour Returns a number that represents the hour of the day (between 0 and 23, inclusive) IsDate Returns a Boolean value that indicates if the evaluated expression can be converted to a date Minute Returns a number that represents the minute of the hour (between 0 and 59, inclusive) Month Returns a number that represents the month of the year (between 1 and 12, inclusive) MonthName Returns the name of a specified month Now Returns the current system date and time Second Returns a number that represents the second of the minute (between 0 and 59, inclusive) Time Returns the current system time Timer Returns the number of seconds since 12:00 AM TimeSerial Returns the time for a specific hour, minute, and second TimeValue Returns a time Weekday Returns a number that represents the day of the week (between 1 and 7, inclusive) WeekdayName Returns the weekday name of a specified day of the week Year Returns a number that represents the year

    Conversion Functions

    Asc Converts the first letter in a string to ANSI code CBool Converts an expression to a variant of subtype Boolean CByte Converts an expression to a variant of subtype Byte CCur Converts an expression to a variant of subtype Currency CDate Converts a valid date and time expression to the variant of subtype Date CDbl Converts an expression to a variant of subtype Double Chr Converts the specified ANSI code to a character CInt Converts an expression to a variant of subtype Integer CLng Converts an expression to a variant of subtype Long CSng Converts an expression to a variant of subtype Single CStr Converts an expression to a variant of subtype String Hex Returns the hexadecimal value of a specified number Oct Returns the octal value of a specified number

    Format Functions

    FormatCurrency Returns an expression formatted as a currency value FormatDateTime Returns an expression formatted as a date or time FormatNumber Returns an expression formatted as a number FormatPercent Returns an expression formatted as a percentage

    Math Functions

    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 Rnd Returns a random number less than 1 but greater or equal to 0 Sgn Returns 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 number Tan Returns the tangent of a specified number (angle)

    Array Functions

    Array Returns a variant containing an array Filter Returns a zero-based array that contains a subset of a string array based on a filter criteria IsArray Returns a Boolean value that indicates whether a specified variable is an array Join Returns a string that consists of a number of substrings in an array LBound Returns the smallest subscript for the indicated dimension of an array Split Returns a zero-based, one-dimensional array that contains a specified number of substrings UBound Returns the largest subscript for the indicated dimension of an array

    String Functions

    InStr Returns the position of the first occurrence of one string within another. The search begins at the first character of the string InStrRev Returns the position of the first occurrence of one string within another. The search begins at the last character of the string LCase Converts a specified string to lowercase Left Returns a specified number of characters from the left side of a string Len Returns the number of characters in a string LTrim Removes spaces on the left side of a string RTrim Removes spaces on the right side of a string Trim Removes spaces on both the left and the right side of a string Mid Returns a specified number of characters from a string Replace Replaces a specified part of a string with another string a specified number of times Right Returns a specified number of characters from the right side of a string Space Returns a string that consists of a specified number of spaces StrComp Compares two strings and returns a value that represents the result of the comparison String Returns a string that contains a repeating character of a specified length StrReverse Reverses a string UCase Converts a specified string to uppercase

    Other Functions

    CreateObject Creates an object of a specified type Eval Evaluates an expression and returns the result IsEmpty Returns a Boolean value that indicates whether a specified variable has been initialized or not IsNull Returns a Boolean value that indicates whether a specified expression contains no valid data (Null) IsNumeric Returns a Boolean value that indicates whether a specified expression can be evaluated as a number IsObject Returns a Boolean value that indicates whether the specified expression is an automation object RGB Returns a number that represents an RGB color value Round Rounds a number ScriptEngine Returns the scripting language in use ScriptEngineBuildVersion Returns the build version number of the scripting engine in use ScriptEngineMajorVersion Returns the major version number of the scripting engine in use ScriptEngineMinorVersion Returns the minor version number of the scripting engine in use TypeName Returns the subtype of a specified variable VarType Returns a value that indicates the subtype of a specified variable

    JavaScript 和 VBScript 的比較

    JavaScript 使用「+」來並排字串,而 VBScript 使用「&」來並排字串。 JavaScript 程式碼會分辨大小寫,VBScript 程式碼則不分大小寫。 一般高階程式碼(如 C/C++ 等),都會分辨大小寫,因此 VBScript 不區分大小寫,是一個主要的缺失。 JavaScript 使用「//」或「/* ... */」來加入註解,而 VBScript 則是使用「'」來加入註解。 一般而言,JavaScript 的每一列敘述後面必須加上分號,VBScript 程式碼則不需要。 更明確地說,JavaScript 若一列只包含一項敘述,則尾端之分號可以省略。 當然如果要將數個 JavaScript 的敘述寫在同一列,就需要在每一個敘述的尾巴加上分號(但最後一個敘述仍然可以省略分號)。 JavaScript 是自由格式(Free Format),因此可以把多個敘述放在同一列,或是把同一列敘述拆放在兩列。 但是 VBScript 則不是自由格式,因此通常是每個敘述放在一列,若要將多個敘述放在同一列,必須使用「:」來分開每一個敘述; 若要將一個敘述拆成多列,必須將「_」至於每一列尾端。 javaScript/example/jsVbsComp02.htm) JavaScript 的語法接近 C 或 C++ 程式語言,VBScript 則接近於 Basic 程式語言。 JavaScript 適用的瀏覽器包含 IE、Firefox、Opera、Netscape 等,但 VBScript 則只能用在 IE 瀏覽器。 因此若為了跨瀏覽器平台,選用 JavaScript 是正確的抉擇。 JavaScript 和 VBScript 兩者都適用於 ASP(Active Server Pages) 和 WSH(Window Scripting Hosts)。

    VBScript intro and samples

    Windows操作系统 VBScript可以被用来自动地完成重复性的Windows操作系统任务。 在Windows操作系统中,VBScript可以在Windows Script Host的范围内运行。 Windows操作系统可以自动辨认和执行*.VBS和*.WSF两种文件格式,此外Internet Explorer可以执行HTA和CHM文件格式。 VBS和WSF文件完全是文字式的,它们只能通过少数几种对话窗口与用户通讯。 HTA和CHM文件使用HTML格式,它们的程序码可以像HTML一样被编辑和检查。 在WSF、HTA和CHM文件中VBScript和JavaScript的程序码可以任意混合。 HTA文件实际上是加有VBS、JavaScript成分的HTML文件。 CHM文件是一种在线帮助,用户可以使用专门的编辑程序将HTML程序编辑为CHM。 Windows 操作系统也提供一些 VBScript 脚本来进行高级管理功能,例如管理 Windows 激活密钥的 slmgr.vbs(Windows Server License Manager Script)。 网页浏览器(客户端的VBS) 网页中的VBS可以用来控制客户端的网页浏览器(以浏览器执行VBS程序)。 VBS与JavaScript在这一方面是竞争者,它们可以用来实现动态HTML,甚至可以将整个程序结合到网页中来。 至今为止VBS在客户方面未能占优势,因为它只获得Microsoft Internet Explorer的支持(Mozilla Suite可以透过安装一个包来支持VBS),并且IE11起已不再支持VBScript[1]。 而JavaScript则受到所有网页浏览器的支持。 在Internet Explorer中VBS和JavaScript使用同样的权限,它们只能有限地使用Windows操作系统中的对象。 网页服务器(服务器方面的VBS) 在网页服务器方面VBS是微软的Active Server Pages的一部分,它与JavaServer Pages和PHP是竞争对手。 在这里VBS的程序码直接嵌入到HTML页内,这样的网页以ASP结尾。 网页服务器Internet信息服务执行ASP页内的程序部分并将其结果转化为HTML传递给网页浏览器供用户使用。 这样服务器可以进行数据库闻讯并将其结果放到HTML网页中。 示范 Hello World 最简单的例子: MsgBox "Hello World" 以.vbs文件保存。 再使用cscript.exe或wscript.exe执行。 一个更复杂的例子中,示出了使用MsgBox作为函数(返回一个结果),并使用了三个参数,其中第二个参数使用的是常量。 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") ' 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 终止任务 VBScript能访问Windows管理规范 (WMI),就像Windows任务管理器。 以下的代码执行时将会终止(“杀掉”)任何关于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 使用Option Explicit并不是必须的,但它被认为是VBScript的最佳实践。 创建具有唯一的名称的十个文件 这个实例显示如何创建文件并向它添加内容。 它还演示了字符串连接。 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方法模拟一个或多个按键到活动窗口(模拟在键盘上输入)。 在该示例中,脚本发送字符串“Hello World!”3次,每次暂停2秒(2000毫秒)。 SendKeys宏可能会在某些程序中失效,因为一些软件(如在安装时输入许可证密钥)将检查是否是真正的按键,而不是虚拟的。 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 执行期间,“Hello World!”将显示在命令提示符。 Windows文件操作 对象FileSystemObject执行一些文件操作(例如测试一个文件是否存在),并且还创建一个文本文件(一个TextStream对象)。 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 MakeHelloWorldFile将会在按下按钮后于C:\ 驱动器根目录创建(若已经存在则更新)一个小文本文件。 Excel对象操作 Option Explicit '所有变量必须显式声明 Dim app,workbook,sheet Dim row,col Set app = WScript.CreateObject("Excel.Application") app.Visible = True Set workbook = app.WorkBooks.Add Set sheet = workbook.Worksheets(1) '10x10 random value For row = 1 To 10 For col = 1 To 10 sheet.Cells(row,col).Value = CInt(Int((100 * Rnd()) + 1)) Next Next Set sheet = workbook.Worksheets(2) '10x10 random value sheet.Range("A1:J10").Formula = "=Int(Rand() * 100 + 1)" 语言 VBScript主要的优点有: 由于VBScript由操作系统,而不是由网页浏览器解释,它的文件比较小。 易学。 在所有2000 / 98SE以后的Windows版本都可直接使用。 可以使用其它程序和可使用的对象(尤其是Microsoft Office)。 缺点有: 现在VBS无法作为电子邮件的附件了。 Microsoft Outlook拒绝接受VBS为附件,收信人无法直接使用VBS附件。 VBS的各种编辑器不受欢迎。 操作系统没有任何特别的保护设施。 VBS程序与其它JS、EXE、BAT或CMD程序一样对待。 操作系统没有监察恶意功能的能力。
    VBScript Scripting Techniques

    set delay in vbscript

    set delay in vbscript
    WScript.Sleep 1000 MsgBox "TEST" Note, the number is in Milliseconds, so 1000 is 1 second.

    check battery

    set oLocator = CreateObject("WbemScripting.SWbemLocator") set oServices = oLocator.ConnectServer(".","root\wmi") set oResults = oServices.ExecQuery("select * from batteryfullchargedcapacity") for each oResult in oResults iFull = oResult.FullChargedCapacity next while (1) set oResults = oServices.ExecQuery("select * from batterystatus") for each oResult in oResults iRemaining = oResult.RemainingCapacity bCharging = oResult.Charging next iPercent = ((iRemaining / iFull) * 100) mod 100 if bCharging and (iPercent > 94) Then msgbox "Battery is at " & iPercent & "%",vbInformation, "Battery monitor" if Not(bCharging) and (iPercent < 30) Then msgbox "Chr(7)Battery is at " & iPercent & "%",vbInformation, "Battery monitor" wscript.sleep 300000 ' 5 minutes wend

    bell character

    Chr(7)

    MsgBox function

    MsgBox function The MsbBox function is set up as any function to return certain values. It is not set up to change fonts and add pictures.
    Dim Msg, Style, Title, Help, Ctxt, Response, MyString Msg = "Do you want to continue ?" ' Define message. Style = vbYesNo + vbCritical + vbDefaultButton2 ' Define buttons. Title = "MsgBox Demonstration" ' Define title. Help = "DEMO.HLP" ' Define Help file. Ctxt = 1000 ' Define topic context. ' Display message. Response = MsgBox(Msg, Style, Title, Help, Ctxt) If Response = vbYes Then ' User chose Yes. MyString = "Yes" ' Perform some action. Else ' User chose No. MyString = "No" ' Perform some action. End If

    Visual Basic Functions

    VB Functions
    Conversion functions Asc, Chr, CVErr, Format, Hex, Oct, Str, Val Math functions Abs, Atn, Cos, Derived math, Exp, Int, Fix, Log, Rnd, Sgn, Sin, Sqr, Tan Other functions Array, CallByName, Choose, Command, CreateObject, CurDir, Date, DateAdd, DateDiff, DatePart, DateSerial, DateValue, Day, DDB, Dir, DoEvents, Environ, EOF, Error, FileAttr, FileDateTime, FileLen, Filter, FormatCurrency, FormatDateTime, FormatNumber, FormatPercent, FreeFile, FV, GetAllSettings, GetAttr, GetObject, GetSetting, Hour, IIf, IMEStatus, Input, InputBox, InStr, InStrRev, IPmt, IRR, IsArray, IsDate, IsEmpty, IsError, IsMissing, IsNull, IsNumeric, IsObject, Join, LBound, LCase, Left, Len, Loc, LOF, LTrim, RTrim, and Trim, MacID, MacScript, Mid, Minute, MIRR, Month, MonthName, MsgBox, Now, NPer, NPV, Partition, Pmt, PPmt, PV, QBColor, Rate, Replace, RGB, Right, Round, Second, Seek, Shell, SLN, Space, Spc, Split, StrComp, StrConv, String, StrReverse, Switch, SYD, Tab, Time, Timer, TimeSerial, TimeValue, TypeName, UBound, UCase, VarType, Weekday, WeekdayName, Year

    Sample VBScript Programs

    Getting started: Input string from a user and echo back: simple.vbs Simple html file: simplehtml.html Get 3 numbers from a user and find the largest: largestNum.vbs Put largestNum program in an html file: largestNum.html Put largestNum program in an html file using a table: largestNumTable.html If you ever find that you have created an infinite loop (so your script keeps running and running and running ...), use ctrl-alt-delete and open the Task Manager. Under the "Processes" tab, end the "wscript" process. Loop examples: Using mod and division operators in a zero-terminated loop: digits.vbs Using mod and division operators in a loop terminated by string "done": digits2.vbs Read in numbers until a negative number is found; determine the average: avg.vbs Start with $1, double money everyday until $1,000,000 (practice prob 4): million.vbs Find the largest number inputted by a user (practice prob 6): findLarge.vbs Display a square of asterisks of a given size (practice prob 9): prob9.vbs Subroutine/Function examples: Find the largest number inputted by a user (practice prob 6), without subroutines: findLarge.vbs Find the largest number inputted by a user (practice prob 6), using subroutines: findLargeWithSubs.vbs Sort three numbers, without subroutines: sortThreeNums.vbs Sort three numbers, using subroutines: sortThreeNumsWithSubs.vbs Demonstrate the difference between ByVal and ByRef: byValbyRef.vbs Opening files -- MS Excel, text files, and Word doc: Open a new excel spreadsheet and enter and add two numbers: openNewExcel.vbs Open an existing excel spreadsheet: openOldExcel.vbs Open an existing excel spreadsheet and loop through cells: loopCells.vbs Open an existing text file and loop through lines: openText.vbs Open an existing Word doc search for a given string: searchWord.vbs Open an existing Powerpoint document and display text of each slide: openPpt.vbs Open an existing Powerpoint document and put text of each slide into a word document: pptToWord.vbs Array examples: Demonstrate simple array manipulation using static arrays: array.vbs Demonstrate dynamic arrays: arrayDynamic.vbs Find something in an array (linear search) (find grade given name): linearSearch.vbs First open a text file with names, e.g., names.txt Then open a text file with grades, e.g., grades.txt Sort a collection of integers using a bubble sort: bubble.vbs Sample VBScript Programs VBScript Examples VBScript examples Sample VBScript

    simple.vbs

    ' Based on code by Kelvin Sung ' File: simple.vbs ' ' Purpose: Input a string from the user and echo the string back to the user. ' ' Lessons ' -- comments start with a single quote (') ' -- execution starts from the first line ' -- always say you will explicitly declare variables ' -- variable declarations don't have types ' ' There are two ways we can run this script: ' 1. On a command (console) window type ' wscript simple.vbs ' 2. Click on the simple.vbs file Option Explicit ' says we must declare variables, we will always use it Dim inputString ' user input string ' Call a function: InputBox ' pass in one parameter: the entire sentence in double-quotes, ' often called a string ' Notice: a function returns something, and you MUST parenthecize the parameter ' in this situation (we'll learn the details later) inputString = InputBox("Please enter some phrase or sentence. Thanks!") ' Calling a procedure: MsgBox ' pass in one parameter: a string (in double quotes) concatenated with ' inputString; the '&' connects the two strings together ' Notice there are no parentices around the parameter MsgBox "You entered: " & inputString

    largestNum.vbs

    ' Based on code by Kelvin Sung ' File: largestNum.vbs ' ' Purpose: input three numbers and figure out the maximum of the numbers. ' ' Lessons ' -- the if/then/else construct ' -- be careful when working with numbers ' -- continue code to the next line by using the underscore ' -- parameters are separated by a comma Option Explicit ' recall force explicit var declaration Dim largestNum ' variable for largest number Dim num1, num2, num3 ' variables for the three input numbers num1 = InputBox("Please enter the first number: ") num2 = InputBox("Please enter the second number: ") num3 = InputBox("Please enter the third number: ") ' check to make sure all input are "numeric" - integer/float/double If IsNumeric(num1) and IsNumeric(num2) and IsNumeric(num3) Then ' MsgBox is a subroutine, the first parameter is the "prompt" ' ' if the last character of the line is an underscore, then the line of ' code is continued to the next line (CANNOT put comment here) ' ' the second parameter is what button to put on the MsgBox ' ' the third parameter is the "title" for the MsgBox ' ' note, there are more parameters for MsgBox, but we choose to use defaults MsgBox "You have entered: " & num1 & " " & num2 & " " & num3, _ vbOKOnly, "Entered Values" ' the numbers can be integers or floating point number (have dec point), ' compare them as "Double" (or floating point numbers) largestNum = num1 If CDbl(num2) > CDbl(largestNum) Then largestNum = num2 End If If CDbl(num3) > CDbl(largestNum) Then largestNum = num3 End If MsgBox "The largest number entered is: " & largestNum, vbOKOnly, _ "Largest Number" Else MsgBox "You must enter three numbers! Try Again", vbOKOnly, "Invalid Input" End If

    largestNum

    The <:script> tag says we are going to have script code here. Notice, we place the <script> inside the <body> section. The <script> can be inside or outside any part of the <html> section. <script Language="vbscript"> Option Explicit ' This is the "service" routine for our button: SubmitButton ' we are going to service "_onClick" event for this button. ' Refer to page 161 of the VBScript reference book for all ' valid events of all controls Sub SubmitButton_onClick ' Code from largestNum.vbs, but without most comments for easy reading ' Note that we no longer have InputBox for input. Handled below. ' Below, data type is &VarType(num1.value). ' So, num1 is a string, not a number, but num1.value is a number. Dim largestNum ' variable for largest number ' check to make sure all input are "numeric" - integer/float/double If IsNumeric(num1.value) and IsNumeric(num2.value) _ and IsNumeric(num3.value) Then MsgBox "You have entered: " & num1.value & " " & num2.value & " " _ & num3.value, vbOKOnly, "Entered Values" largestNum = num1.value If CDbl(num2.value) > CDbl(largestNum) Then largestNum = num2.value End If If CDbl(num3.value) > CDbl(largestNum) Then largestNum = num3.value End If MsgBox "The largest number entered is: " & largestNum, vbOKOnly, _ "Largest Number" Else MsgBox "You must enter three numbers! Try Again", vbOKOnly, _ "Invalid Input" End If End Sub </script> First Number: Second Number: Third Number: Input Type - list of all valid types on page 161 of VBScript Reference book Name - variable name for this control Value - what to show on the webpage (or the label for this control) <Input Type="Button" Name="SubmitButton" Value="Submit" >

    largestNumTable

    The <script> tag says we are going to have script code here. Notice, we place the <script> inside the <body> section. The <script> can be inside or outside any part of the <html> section. <script Language="vbscript"> Option Explicit ' This is the "service" routine for our button: SubmitButton ' we are going to service "_onClick" event for this button. ' Refer to page 161 of the VBScript reference book for all ' valid events of all controls Sub SubmitButton_onClick ' Code from largestNum.vbs, but without most comments for easy reading ' Note that we no longer have InputBox for input. Handled below. ' Below, data type is &VarType(num1.value). ' So, num1 is a string, not a number, but num1.value is a number. Dim largestNum ' variable for largest number ' check to make sure all input are "numeric" - integer/float/double If IsNumeric(num1.value) and IsNumeric(num2.value) _ and IsNumeric(num3.value) Then MsgBox "You have entered: " & num1.value & " " & num2.value & " " _ & num3.value, vbOKOnly, "Entered Values" largestNum = num1.value If CDbl(num2.value) > CDbl(largestNum) Then largestNum = num2.value End If If CDbl(num3.value) > CDbl(largestNum) Then largestNum = num3.value End If MsgBox "The largest number entered is: " & largestNum, vbOKOnly, _ "Largest Number" Else MsgBox "You must enter three numbers! Try Again", vbOKOnly, _ "Invalid Input" End If End Sub </script> <table> <tr> First Number: <Input Type="Text" Name="num1" Value=""> <Second Number:> <Input Type="Text" Name="num2" Value=""> Third Number: <Input Type="Text" Name="num3" Value=""> </table> Input Type - list of all valid types on page 161 of VBScript Reference book Name - variable name for this control Value - what to show on the webpage (or the label for this control) <Input Type="Button" Name="SubmitButton" Value="Submit">

    digits.vbs

    ' Based on code by Kelvin Sung ' File: digits.vbs ' ' example demonstrates mod (modulus, finding remainder) and integer div (\) ' by breaking a five-digit number into individual digits Option Explicit ' must declare every variables before use dim inputNumber ' input from user dim origNumber ' save the inputNumber dim onesDigit, tenDigit, hunDigit, thouDigit, tenThouDigit do inputNumber = InputBox("Please Enter a 5 digit number, zero to end") ' check for validity if not IsNumeric(inputNumber) then MsgBox "You must enter a number. Try Again.", vbOKOnly, "Invalid Input" else ' check to see if the loop should be terminated if inputNumber = 0 then exit do end if ' have obtained a good number, demonstrate different kinds of division origNumber = inputNumber MsgBox "Using division (/): " & origNumber & "/100 is " _ & origNumber/100 MsgBox "Using integer division (\): " & origNumber & "\100 is " _ & origNumber\100 ' extract digits tenThouDigit = inputNumber\10000 inputNumber = inputNumber mod 10000 thouDigit = inputNumber\1000 inputNumber = inputNumber mod 1000 hunDigit = inputNumber\100 inputNumber = inputNumber mod 100 tenDigit = inputNumber\10 onesDigit = inputNumber mod 10 MsgBox "The digits of " & origNumber & " are " & tenThouDigit & " " _ & thouDigit & " " & hunDigit & " " & tenDigit & " " & onesDigit end if loop MsgBox "All done!"

    digits2.vbs

    ' Based on code by Kelvin Sung ' File: digits2.vbs ' ' example demonstrates mod (modulus, finding remainder) and integer div (\) ' by breaking a five-digit number into individual digits Option Explicit ' must declare every variables before use dim inputNumber ' input from user dim origNumber ' save the inputNumber dim onesDigit, tenDigit, hunDigit, thouDigit, tenThouDigit do inputNumber = InputBox("Please enter a 5 digit number, enter 'done' to end") ' check for validity, exit on entry of word "done" if not IsNumeric(inputNumber) then if inputNumber = "done" then exit do else MsgBox "You must enter a number, try again.", vbOKOnly, "Invalid Input" end if else origNumber = inputNumber MsgBox "Using division (/): " & origNumber & "/100 is " _ & origNumber/100 MsgBox "Using integer division (\): " & origNumber & "\100 is " _ & origNumber\100 ' separate digits tenThouDigit = inputNumber\10000 inputNumber = inputNumber mod 10000 thouDigit = inputNumber\1000 inputNumber = inputNumber mod 1000 hunDigit = inputNumber\100 inputNumber = inputNumber mod 100 tenDigit = inputNumber\10 onesDigit = inputNumber mod 10 MsgBox "The digits of " & origNumber & " are " & tenThouDigit & " " _ & thouDigit & " " & hunDigit & " " & tenDigit & " " & onesDigit end if loop MsgBox "All done!"

    avg.vbs

    ' File: avg.vbs ' ' count how many data and compute average Option Explicit ' must declare every variables before use dim inputNumber ' input from user dim count ' count data items dim sum ' sum data items dim avg ' average of data items ' initialize count = 0 sum = 0 avg = 0 ' for every valid data item, sum and count it do inputNumber = InputBox("Please enter one number, negative number to end") ' check for validity if not IsNumeric(inputNumber) then MsgBox "You must enter a number. Try Again.", vbOKOnly, "Invalid Input" else if inputNumber < 0 then exit do end if sum = sum + inputNumber count = count + 1 end if loop ' computer average and output if count <> 0 then avg = sum/count else avg = 0 end if MsgBox "The number of items entered: " & count & " has an average of " & avg

    million.vbs

    ' File: million.vbs ' ' 4. Suppose you start with $1 and double your money every day. How many days ' does it take to make more than $1000000? Option Explicit ' must declare every variables before use const MAXAMOUNT = 1000000 dim amount ' current amount of money dim sum ' total sum of accumulated money dim days ' number of days ' initialize amount = 1 sum = 0 days = 0 do until sum > MAXAMOUNT sum = sum + amount amount = 2 * amount days = days + 1 loop MsgBox "Start with $1 and double your money everyday. It takes " _ & days & " days to make " & sum & " dollars"

    findLarge.vbs

    ' File: findLarge.vbs ' ' 6. In a loop, you input one integer at a time. The word "done" ' terminates the loop. Find and display the largest number inputted. Option Explicit ' force declaration of variables before use dim inputNumber ' input from user dim outputNums ' to show all the numbers user inputs dim largest ' always current largest number dim doneWithInput ' whether or not user is done entering input doneWithInput = false outputNums = "" ' Loop to get one valid number from the user to initialize largest. ' The var doneWithInput will remember if the user is done before ' ever entering a valid number. do inputNumber = InputBox("Please enter one number, enter 'done' to end") ' check for validity, exit on entry of word "done" if not IsNumeric(inputNumber) then if inputNumber = "done" then doneWithInput = true exit do else MsgBox "You must enter a number, try again.", vbOKOnly, "Invalid Input" end if else largest = inputNumber outputNums = outputNums & " " & inputNumber exit do end if loop ' If user isn't done, continue getting integers to find the largest. ' Continually compare with the current largest to see if it's larger, ' then it becomes the new current largest. if not doneWithInput then do inputNumber = InputBox("Please enter one number, enter 'done' to end") ' check for validity, exit on entry of word "done" if not IsNumeric(inputNumber) then if inputNumber = "done" then exit do else MsgBox "You must enter a number, try again.", vbOKOnly, _ "Invalid Input" end if else ' recall that InputBox returns a string, so convert to ' make sure they are treated as numbers, not strings if Cdbl(inputNumber) > Cdbl(largest) then largest = inputNumber end if outputNums = outputNums & " " & inputNumber end if loop end if if doneWithInput then MsgBox "Can't find the largest because you never entered any numbers!!" else MsgBox "Of all the numbers, " & outputNums & ", the largest is " & largest end if

    prob9.vbs

    ' 9. Given some integer number as input, print out a solid square in ' asterisks the size of that number. E.g., input is 5, output is ' ***** ' ***** ' ***** ' ***** ' ***** Option Explicit ' must declare every variables before use dim inputNumber ' input from user dim i, j dim output do ' start with no characters in the output string, called the empty string output = "" inputNumber = InputBox("Please enter one positive number, 'done' to end") ' check for validity of input if not IsNumeric(inputNumber) then if inputNumber = "done" then exit do else MsgBox "You must enter a number. Try Again.", vbOKOnly, "Invalid Input" end if ' can't have a negative number of asterisks in a box elseif inputNumber < 0 then MsgBox "You must enter a positive number. Try Again.", vbOKOnly, _ "Invalid Input" else ' have valid inputNumber ' i loop yields different lines of asterisks for i = 1 to inputNumber ' j loop gives all the asterisks in one line for j = 1 to inputNumber output = output & "*" next ' after the j loop asterisks are concatenated, need NewLine in output output = output & vbNewLine next MsgBox output end if loop

    findLargeWithSubs.vbs

    ' File: findLarge.vbs ' ' 6. In a loop, you input one integer at a time. The word "done" ' terminates the loop. Find and display the largest number inputted. Option Explicit ' force declaration of variables before use dim outputNums ' to show all the numbers user inputs dim largest ' always current largest number dim doneWithInput ' whether or not user is done entering input doneWithInput = false outputNums = "" call setFirstLargest(outputNums, doneWithInput, largest) call findLargestInRest(outputNums, doneWithInput, largest) if doneWithInput then MsgBox "Can't find the largest because you never entered any numbers!!" else MsgBox "Of all the numbers, " & outputNums & ", the largest is " & largest end if '---------------------------------------------------------------------------- ' setFirstLargest ' Loop to get one valid number from the user to initialize largest. ' The var doneWithInput will remember if the user is done before ' ever entering a valid number. sub setFirstLargest(outputNums, doneWithInput, largest) dim inputNumber ' input from user do inputNumber = InputBox("Please enter one number, enter 'done' to end") ' check for validity, exit on entry of word "done" if not IsNumeric(inputNumber) then if inputNumber = "done" then doneWithInput = true exit do else MsgBox "You must enter a number, try again.", vbOKOnly, _ "Invalid Input" end if else largest = inputNumber outputNums = outputNums & " " & inputNumber exit do end if loop end sub '---------------------------------------------------------------------------- ' findLargestInRest ' If user isn't done, continue getting integers to find the largest. ' Continually compare with the current largest to see if it's larger, ' then it becomes the new current largest. sub findLargestInRest(outputNums, doneWithInput, largest) dim inputNumber ' input from user if not doneWithInput then do inputNumber = InputBox("Please enter one number, enter 'done' to end") ' check for validity, exit on entry of word "done" if not IsNumeric(inputNumber) then if inputNumber = "done" then exit do else MsgBox "You must enter a number, try again.", vbOKOnly, _ "Invalid Input" end if else ' recall that InputBox returns a string, so convert to ' make sure they are treated as numbers, not strings if Cdbl(inputNumber) > Cdbl(largest) then largest = inputNumber end if outputNums = outputNums & " " & inputNumber end if loop end if end sub

    sortThreeNums.vbs

    ' File: sortThreeNums.vbs ' Sort three Numbers Option Explicit dim num1, num2, num3 ' used for input dim largeNum ' variable for largest number dim middleNum ' variable for second largest number dim smallNum ' variable for smallest number dim temp num1 = InputBox("Please enter the first number") num2 = InputBox("Please enter the second number") num3 = InputBox("Please enter the third number") ' check to make sure all input are "numeric" - integer/float/double if IsNumeric(num1) and IsNumeric(num2) and IsNumeric(num3) then MsgBox "You have entered: " & num1 & " " & num2 & " " _ & num3, vbOKOnly, "Entered Values" largeNum = CDbl(num1) middleNum = CDbl(num2) smallNum = CDbl(num3) if largeNum < middleNum then temp = largeNum largeNum = middleNum middleNum = temp end if if largeNum < smallNum then temp = largeNum largeNum = smallNum smallNum = temp end if if middleNum < smallNum then temp = middleNum middleNum = smallNum smallNum = temp end if MsgBox "The numbers sorted: " & smallNum & " " & middleNum & " " _ & largeNum, vbOKOnly, "Sorted Numbers" else MsgBox "You must enter three numbers! Try Again", vbOKOnly, _ "Invalid Input" end if

    sortThreeNumsWithSubs.vbs

    ' File: sortThreeNumsWithSubs.vbs ' Sort three Numbers Option Explicit dim num1, num2, num3 ' used for input dim largeNum ' variable for largest number dim middleNum ' variable for second largest number dim smallNum ' variable for smallest number num1 = InputBox("Please enter the first number") num2 = InputBox("Please enter the second number") num3 = InputBox("Please enter the third number") ' check to make sure all input are "numeric" - integer/float/double if IsNumeric(num1) and IsNumeric(num2) and IsNumeric(num3) then MsgBox "You have entered: " & num1 & " " & num2 & " " _ & num3, vbOKOnly, "Entered Values" largeNum = CDbl(num1) middleNum = CDbl(num2) smallNum = CDbl(num3) call compareAndSwap(largeNum, middleNum) call compareAndSwap(largeNum, smallNum) call compareAndSwap(middleNum, smallNum) MsgBox "The numbers sorted: " & smallNum & " " & middleNum & " " _ & largeNum, vbOKOnly, "Sorted Numbers" else MsgBox "You must enter three numbers! Try Again", vbOKOnly, _ "Invalid Input" end if '---------------------------------------------------------------------- ' compareAndSwap ' Compare num1 to num2 and swap if they are out of order. ' Result is that at the end of the routine, num1 is always less than num2. sub compareAndSwap(num1, num2) dim temp if num1 < num2 then temp = num1 num1 = num2 num2 = temp end if end sub

    byValbyRef.vbs

    ' File: byValbyRef.vbs ' demonstrate difference between byVal parameter and byRef parameter option explicit dim a, b, c, d a = 2 b = 3 c = 2 d = 3 call byValSub(a, b) call byRefSub(c, d) MsgBox "a = " & a & " b = " & b & " c = " & c & " d = " & d '---------------------------------------------------------------------------- ' byValSub ' Parameters that are pass by value make a copy of the value passed to ' the parameter and if the parameter is changed, it is only changed ' locally, meaning within the subprogram. SUB byValSub(ByVal num1, ByVal num2) num1 = 10 num2 = 20 end SUB '---------------------------------------------------------------------------- ' byRefSub ' Parameters that are pass by reference are sent the memory address of the ' sender. If the parameter is changed, it is changed at the sending location. SUB byRefSub(ByRef num1, ByRef num2) num1 = 10 num2 = 20 end SUB

    openNewExcel.vbs

    ' Based on code by Kelvin Sung ' File: openNewExcel.vbs ' ' Enter two numbers from the user and add them up using Microsoft Excel ' Shows How to open an MicroSoft Excel ActiveX service through VB Option Explicit ' force variable declarations ' Excel.Document - is a predefined name for "ActiveX" services provided by Excel ' (xlAppl is our "connection" to all functions MS Excell provides) ' ' "set" - new VBScript for us (only can "set" non-VB types, i.e., "objects") ' For example, ' dim num ' set num = 123 ' is an ERROR !!!) ' ' If you forget to use "set", e.g., ' xlAppl = CreateObject("Excel.Application") ' it will compile, but when it runs, we'll get a run-time error: ' "Object Required: .... " ' ' Also note that if you encounter errors after Excel is opened, ' you have to manually close the excel application dim xlAppl set xlAppl = CreateObject("Excel.Application") ' We do not need to let the user see what is going on, ' can switch the visibility on/off xlAppl.Application.Visible = false ' Now create a new excel document to work with, ' MS Excel refers to its documents (files) as "Workbook" dim newDocument set newDocument = xlAppl.Application.Workbooks.Add() ' Each excel document can have many work sheets, ' we will activate the first one and work with it ... dim activeSheet set activeSheet = xlAppl.Worksheets("Sheet1") ' we can use the value returned by MsgBox, to let user decide what to see dim choice choice = MsgBox("Do you want to look at the Excel Page?", vbYesNo) if choice = vbYes then xlAppl.Application.Visible = true end if ' now we are ready, let's enter number and add the numbers up ' for the user ' dim num1, num2 num1 = InputBox("Please enter a number: ") num2 = InputBox("Please enter another number: ") ' put num values in first and second rows, put sum in third row, first column activeSheet.Cells(1, 1).Value = num1 activeSheet.Cells(2, 1).Value = num2 activeSheet.Cells(3, 1).Value = "=Sum(A1:A2)" dim answer answer = activeSheet.Cells(3,1).Value MsgBox num1 & "+" & num2 & " is: " & answer ' When I want to quit, let me quit, do not ask me if I want to save my work xlAppl.Application.DisplayAlerts = true ' and quit xlAppl.Application.Quit

    openOldExcel.vbs

    ' Based on code by Kelvin Sung ' File: openOldExcel.vbs ' ' Use Microsoft Office (mso) ActiveX service to open an existing document ' ' Open a document from user input Option Explicit ' We need to go through MS Excel (or MS Office, Word is fine), the ' application script editor, to find the value to send to the FileDialog. ' Refer to on-line help page for the details. ' ' In this case, MsoFileDialogType.msoFileDialogOpen with a value of one ' is used to open the file. const msoFileDialogOpen = 1 dim xlAppl set xlAppl = CreateObject("Excel.Application") ' use Microsoft Office FileDialog to open a file dim dlgOpen set dlgOpen = xlAppl.Application.FileDialog(msoFileDialogOpen) dim selectedFile dim dlgAnswer ' only allow the selection of one file dlgOpen.AllowMultiSelect = false ' -1 says user clicked on "Open" if (dlgOpen.Show() = -1 ) then ' since we disallow multiple select, the first selected item is our file selectedFile = dlgOpen.SelectedItems(1) ' now open the file xlAppl.Application.Workbooks.Open(selectedFile) msgbox "selectedFile is: " & selectedFile else MsgBox "No document opened!" end if xlAppl.Application.DisplayAlerts = false xlAppl.Application.Quit

    loopCells.vbs

    ' Based on code from Kelvin Sung ' File: loopCells.vbs ' Allow the user to open an existing excel document, and access cells Option Explicit 'force all variables to be declared ' Get information on the "current folder" of this script and open a connection ' to the "operating environment". dim wshShell, currentFolder ' wshShell contains the environment for which we are operating in; ' use it to retrieve the current work folder set wshShell = WScript.CreateObject("WScript.Shell") ' currentFolder contains the path to the folder where this script is located currentFolder = wshShell.CurrentDirectory ' open the the msoFileDialog with initial folder setting to the "currentFolder" dim xlAppl set xlAppl = CreateObject("Excel.Application") const msoFileDialogOpen = 1 dim dlgOpen ' use MS Office FileDialog to open a file set dlgOpen = xlAppl.Application.FileDialog(msoFileDialogOpen) dim selectedFile dim dlgAnswer dlgOpen.AllowMultiSelect = false ' only allow selection of one file dlgOpen.InitialFileName = currentFolder if (dlgOpen.Show() = -1) then ' -1 says user clicked on "Open" ' the first selected item will be our file name selectedFile = dlgOpen.SelectedItems(1) ' now open the file xlAppl.Application.Workbooks.Open(selectedFile) else MsgBox "No document opened!" end if ' each excel document can have many work sheets, do our work on Sheet1 dim activeSheet set activeSheet = xlAppl.Worksheets("Sheet1") '-------------------------------------------------------------------------- ' The code to work with the spreadsheet starts here. dim row ' row is row number dim col ' col is column number ' activeSheet.Cells(row, col) is the cell value ' ' For example, activeSheet.Cells(4, 6) is the cell in row 4, column 6 ' The cells are strings, so convert if needed. If you do arithmetic ' with them, they are automatically converted. ' Pause to see the original spreadsheet. MsgBox "Notice that there is nothing in column five or six." ' Here is a loop to demonstrate. ' The loop puts the value of variable row into each cell in rows one ' through ten, column five. It then copies column 5 to column 6. for row = 1 to 10 activeSheet.Cells(row, 5) = row activeSheet.Cells(row, 6) = activeSheet.Cells(row, 5) next ' To keep the spradsheet open to allow saving MsgBox "The End. Click the excel closing box if you wish to save it." '-------------------------------------------------------------------------- xlAppl.Application.DisplayAlerts = false xlAppl.Application.Quit

    openText.vbs

    ' Based on code by Kelvin Sung ' File: openTextFile.vbs ' ' Define a Function to use MSO FileOpenDial facility ' to help the user select a text file to open Option Explicit ' ask the scripting runtime environemt for access to files dim FS set FS = CreateObject("Scripting.FileSystemObject") const FILEFORREADING = 1 dim dataFile dataFile = selectAFileOrFolder("FILE") if FS.FileExists(dataFile) then ' get the fileHander based on the dataFile dim FileHandler set FileHandler = FS.GetFile(dataFile) ' open the file as a inputTextStream so text data can be "streamed" dim inputTextStream set inputTextStream = FileHandler.OpenAsTextStream(FILEFORREADING) dim inputLine ' a line in the file dim lineCount ' number of lines in the file lineCount = 0 do while not inputTextStream.AtEndOfStream lineCount = lineCount + 1 inputLine = inputTextStream.ReadLine MsgBox "Line " & lineCount & " content: " & inputLine loop else MsgBox "File: " & dataFile & " does not exists." end if '------------------------------------------------------------------------------ ' selectAFileOrFolder ' Takes in one input parameter, "FILE" or "FOLDER", and returns its path ' in a string that contains either the selected file or folder path. FUNCTION selectAFileOrFolder(ByRef fileOrFolder) dim WshShell, currentFolder ' Open a "connection" to the "operating environment" . ' WshShell contains the environment for which we are operating in. ' For example, below we will use it to retrieve the current working folder. set WshShell = WScript.CreateObject("WScript.Shell") ' Get the current folder (where this script is opened from). ' currentFolder now contains the path to the folder currentFolder = wshShell.CurrentDirectory ' XlAppl is our "connection" to all functions MS Excel provides dim XlAppl set XlAppl = WScript.CreateObject("Excel.Application") ' don't let user see what is going on, ' can switch the visibility of MSon/off (TRUE/FALSE) XlAppl.Application.Visible = FALSE ' specific constants to OFFICE Object. ' VBScript cannot see these constants, so we have ' to find out what they are, and re-define them. dim msoFileDialogOpen if (fileOrFolder = "FILE") then msoFileDialogOpen = 1 end if if (fileOrFolder = "FOLDER") then msoFileDialogOpen = 4 end if ' OpenFile Dialog we use MSO facility, since MSO is implemented in either ' Word, Excel, even PowerPoint. It can be used in exactly the same way. ' Notice "set" is used here too. dim DlgOpen set DlgOpen = XlAppl.Application.FileDialog(msoFileDialogOpen) ' Only allow selection of one file ' TRUE: Allow multiple file selection ' FALSE: Do not allow multiple file selection DlgOpen.AllowMultiSelect = FALSE ' Set up the "Filters" so that we only work with certain types of files. ' ' DlgOpen.Filters.Clear ' DlgOpen.Filters.Add "Text Files", "*.txt", 1 ' Only want to work with Text files ' The parameters of Add are: ' 1st - description of what is the file type ' 2nd - the extension (don't forget the "*") ' 3rd - the position for this entry ' Start looking from current working folder ' currentFolder contains the path to the folder where this script is located DlgOpen.InitialFileName = currentFolder SelectAFileOrFolder = "" ' Set the return value to "" if (DlgOpen.Show() = -1) then ' -1 says user clicked on "Open" ' first selected item is the file name SelectAFileOrFolder = DlgOpen.SelectedItems(1) end if ' TRUE: Prompt user to save the work ' FALSE: Do not prompt user to save the work XlAppl.Application.DisplayAlerts = FALSE XlAppl.Application.Quit ' quit the application end FUNCTION

    searchWord.vbs

    ' Based on code by Kelvin Sung ' File: searchWord.vbs ' ' Shows how to open a MS Word document via ActiveX. ' Ask the user for a string and search for it in the document. ' ' Uses the same MSO FileOpenDialog as used via the excel examples. Option Explicit ' Very similar to opening an excel document. ' dim XlAppl ' set XlAppl = CreateObject("Excel.Application") dim DOCAppl set DOCAppl = CreateObject("Word.Application") dim searchString dim count if (Open_OFFICE_Document(DOCAppl, "Word Files", "*.doc")) then searchString = "Something" do while searchString <> "" searchString = InputBox("Enter the string to search [enter to quit]: ") if (searchString <> "") then count = countStringInDoc(searchString, DOCAppl) if (count > 0) Then MsgBox "String [" & searchString & "] is found in the document: " _ & count & " times" else MsgBox "String [" & searchString & "] is NOT found in the document" end if end if loop DOCAppl.Application.Documents.Close DOCAppl.Application.Quit else DOCAppl.Application.Quit end if '----------------------------------------------------------------------------- ' Function Name: countStringInDoc(ByVal searchString) ' Description: Takes in 1 input parameter, and returns count, the ' number of times the string is found in the document ' ' Input Parameters: ByRef searchString, ByRef applObj ' 1) searchString -- the string you want to find ' 2) applObj -- the application object ' ' Returns Value: INTEGER: number of times string is found FUNCTION countStringInDoc(ByVal searchString, ByRef applObj) ' set up to search the entire document dim findRange set findRange = applObj.ActiveDocument.Range() ' program Word's search facility With findRange .Find.Text = searchString ' assign the string to search .Find.Forward = TRUE ' look in the forward direction end With dim doneSearching, count doneSearching = FALSE count = 0 ' search through the doc, counting occurrences of searchString do while not doneSearching findRange.Find.Execute() ' start Word searching if (findRange.Find.Found) then count = count + 1 else doneSearching = TRUE ' can't find anymore strings end if loop countStringInDoc = count end FUNCTION '----------------------------------------------------------------------------- ' Function Name: Open_OFFICE_Document(ByRef applicationObj, ByRef filterDes, ' ByRef filterExt) ' Description: Takes in 3 input parameter, and returns ' TRUE or FALSE, whether the file is being opened. ' ' It uses the WScript's CreateObject method to establish the ' connection with the "Operation Enviroment". ' ' After setting up the "connection", use the Microsoft Office ' OpenFileDialog facility to open a file, through the ' "connection". ' ' Input Parameters: ByRef applicationObj, ByRef filterDes, ByRef filterExt ' 1) applicationObj -- The application object ' 2) filterDes -- file description type you want to open, ' pass by reference as String ' e.g., filterDes = "MS Word Files" to work with Word ' 3) filterExt -- extension of the file type to open, ' pass by reference as String, e.g., ' filterExt = "*.ppt" to work with PowerPoint files ' ' Returns Value: BOOLEAN, whether the file is being opened or not ' Possible Errors: The passed in applicationObj is not created correctly ' The values of filterDes or filterExt are not inside ' double quotations FUNCTION Open_OFFICE_Document(ByRef applicationObj, ByRef filterDes, _ ByRef filterExt) ' Constants specific to _OFFICE_ Object. VBScript cannot see these ' constants, so we have to find out what they are, and redefine them. const msoFileDialogOpen = 1 ' Open a "connection" to the "operating environment" . ' WshShell contains the environment for which we are operating in. ' For example, below it is used to retrieve the current working folder. dim WshShell set WshShell = WScript.CreateObject("WScript.Shell") ' OpenFile Dialog we use MSO facility, since MSO is implemented in either ' Word, Excel, even PowerPoint, we can use it in exactly the same way. dim DlgOpen set DlgOpen = applicationObj.FileDialog(msoFileDialogOpen) With DlgOpen ' Notice when we want to perform multiple operations based on the ' same object, we can use the "With" statement. This is much more ' efficient (especially when dealing with ActiveX connection) .AllowMultiSelect = False ' Only allow selection of one file ' TRUE: Allow multiple file selection ' FALSE: Do not allow multiple file selection .InitialFileName = WshShell.CurrentDirectory ' Start looking from current working folder ' CurrentFolder contains the path to the folder of this script .Filters.Clear 'clear filter ' Set up "Filters", so that we only work with certain types of files. ' The parameters of Add are: ' 1st - description of what is the file type ' 2nd - the extension (don't forget the "*") ' 3rd - the position for this entry .Filters.Add filterDes, filterExt, 1 end With if ( dlgOpen.Show() = -1 ) then ' -1 says user clicked on "Open" ' Since we do not allow multiple select, the first selected item ' will be our file name dim selectedFile selectedFile = dlgOpen.SelectedItems(1) ' Open the file, can switch the visibility of MSon/off (true/false) ' TRUE: Show Excel is running ' FALSE: Do not show Excel is running applicationObj.Visible = TRUE '-------- ALTERNATIVES -------- Select Case filterExt case "*.mdb" ' For Access files applicationObj.OpenCurrentDatabase selectedFile case "*.ppt" ' For PowerPoint files applicationObj.Presentations.Open selectedFile case "*.doc" ' For Word files applicationObj.Application.Documents.Open selectedFile case "*.xls" ' For Excel files applicationObj.Application.Documents.Open selectedFile end select Open_OFFICE_Document = TRUE ' set return to TRUE else 'else if user did not click on "Open" Open_OFFICE_Document = FALSE ' set return to FALSE end if end FUNCTION

    openPpt.vbs

    ' Based on code by Kelvin Sung ' File: openPpt.vbs ' ' Open a powerpoint file and display the text from each slide. ' The same MSO FileOpenDialog (as used with Excel) is used. Option Explicit ' specific constants, vbScript cannot see these constants, so ' find out what they are, and redefine them const msoFileDialogOpen = 1 dim WshShell set WshShell = WScript.CreateObject("WScript.Shell") ' For getting our operating environment (e.g. Current Working Folder) ' Very similar to word and excel, remember: ' dim xlAppl ' set xlAppl = CreateObject("Excel.Application") dim pptAppl set pptAppl = CreateObject("Powerpoint.Application") ' OpenFile Dialog uses MSO facility, since MSO is implemented in both ' Word and Excel, use it in exactly the same way. dim dlgOpen set dlgOpen = pptAppl.FileDialog(msoFileDialogOpen) if (openPPTDocument()) then ' PPT uses ActivePresenation whereas ' Word uses ActiveDocument ' Excel uses ActiveWorkbook ' slideShow is the entire powerpoint presentation dim slideShow, oneSlide set slideShow = pptAppl.ActivePresentation.Slides MsgBox "This powerpoint file has: " & slideShow.Count & " number of slides" dim count for count = 1 To slideShow.Count set oneSlide = slideShow.Item(count) ' one of the slides dim slideSections, titleName ' look at how many input boxes that are defined for this slide set slideSections = oneSlide.Shapes ' find the title for this slide if (slideSections.HasTitle) then titleName = slideSections.Title.TextFrame.TextRange.Text else titleName = "HAS NO TITLE" end if dim shapeIndex, slideText slideText = "" for shapeIndex = 1 to slideSections.Count ' Rest of the text for this slide dim aSection set aSection = slideSections.Item(shapeIndex) if (aSection.HasTextFrame) then slideText = slideText & aSection.TextFrame.TextRange.Text & vbCrLf end if next MsgBox "Slide Number Is: " & oneSlide.SlideNumber & vbCrLf & _ "Title is: " & titleName & vbCrLf & "Texts In This Slide: " & _ vbCrLf & slideText next pptAppl.ActivePresentation.Close pptAppl.Quit else MsgBox("No PowerPoint Document Selected, Bye Bye") pptAppl.Quit end if '----------------------------------------------------------------------------- ' FUNCTION: openPPTDocument() ' ' Input: none (uses the global dlgOpen to let user open a .ppt document) ' Returns: none (changes the global pptAppl variable to have an opened document) ' Error: Checks to make sure input is a number ' ' Remark: FUNCTION openPPTDocument() with dlgOpen ' Notice when we want to perform multiple operations based on the ' same object, we can use the "with" statement. This is much more ' efficient (especially when dealing with ActiveX connection) ' .AllowMultiSelect = FALSE .InitialFileName = WshShell.CurrentDirectory .Filters.Clear .Filters.Add "PowerPoint Files", "*.ppt" end with openPPTDocument = FALSE if (dlgOpen.Show() = -1) then dim selectedFile ' -1 says user clicked "Open" selectedFile = dlgOpen.SelectedItems(1) pptAppl.Visible = TRUE ' first set ppt to visible pptAppl.Presentations.Open selectedFile ' now open the file openPPTDocument = TRUE end if end FUNCTION

    pptToWord.vbs

    ' Based on code by Kelvin Sung ' File: pptToWord.vbs ' ' Open a powerpoint document and put all the text into a word document. Option Explicit ' specific constants, vbScript cannot see these constants, so ' find out what they are, and redefine them const msoFileDialogOpen = 1 ' getting the operating environment (e.g., Current Working Folder) dim WshShell set WshShell = WScript.CreateObject("WScript.Shell") dim pptAppl set pptAppl = CreateObject("Powerpoint.Application") dim WdAppl set WdAppl = CreateObject("Word.Application") WdAppl.Application.Visible = FALSE ' OpenFile Dialog using MSO facility, since MSO is implemented in both ' Word and Excel, use it in exactly the same way. dim DlgOpen set DlgOpen = pptAppl.FileDialog(msoFileDialogOpen) if (OpenPPTDocument()) then ' Powerpoint uses ActivePresenation just as Word uses ActiveDocument ' and Excel uses ActiveWorkbook. ' ' slideShow is now the entire powerpoint presentation dim slideShow, oneSlide set slideShow = pptAppl.ActivePresentation.Slides MsgBox "This powerpoint file has: " & slideShow.Count & " number of slides" SavePptToWord slideShow, pptAppl.ActivePresentation.Name ' quit powerpoint pptAppl.ActivePresentation.Close pptAppl.Quit ' quit word WdAppl.Application.Quit else MsgBox("No PowerPoint Document Selected, Bye Bye") pptAppl.Quit WdAppl.Application.Quit end if '---------------------------------------------------------------------------- ' Function: OpenPPTDocument() ' ' Input: none (uses the global DlgOpen to let user open a .doc document) ' Returns: none (changes the global pptAppl variable to have an opened document ' Error: Checks to make sure input is a number FUNCTION OpenPPTDocument() ' perform multiple operations based on the same object, so use the ' "with" statement. This is cleaner, especially with activeX. with DlgOpen .AllowMultiSelect = FALSE .InitialFileName = WshShell.CurrentDirectory .Filters.Clear .Filters.Add "PowerPoint Files", "*.ppt" end with OpenPPTDocument = FALSE if (dlgOpen.Show() = -1) then dim selectedFile ' -1 says user clicked "Open" selectedFile = dlgOpen.SelectedItems(1) pptAppl.Visible = TRUE ' set ppt to visible pptAppl.Presentations.Open selectedFile ' now open the file OpenPPTDocument = TRUE end if end FUNCTION '---------------------------------------------------------------------------- ' SUB SavePptToWord slideShow: ' ' Creates an MS Word Doc document with from ppt slideShow content. ' It is formatted somewhat. SUB SavePptToWord(ByRef slides, ByVal name) const wdToggle = 9999998 ' create a new MS Word Doc dim newWdDoc set newWdDoc = WdAppl.Documents.Add dim sel set sel = WdAppl.Application.Selection WdAppl.Application.Visible = TRUE ' get back reference for editing with sel .Style = WdAppl.Application.ActiveDocument.Styles("Heading 1") .TypeText "Content of the Presenation: " + name .TypeParagraph .TypeParagraph end with dim count for count = 1 to slides.Count Set oneSlide = slides.Item(count) ' one of the slides ' look at how many input boxes are defined for this slide dim slideSections, titleName set slideSections = oneSlide.Shapes ' find the title for this slide if (slideSections.HasTitle) then titleName = slideSections.Title.TextFrame.TextRange.Text else titleName = "HAS NO TITLE" end if with sel .Style = WdAppl.Application.ActiveDocument.Styles("Heading 2") .TypeText "Slide " & Count & ": " & titleName .TypeParagraph end with dim shapeIndex for shapeIndex = 1 to slideSections.Count ' Rest of the text for this slide dim aSection set aSection = slideSections.Item(shapeIndex) if (aSection.HasTextFrame) then with sel .TypeText aSection.TextFrame.TextRange.Text .TypeParagraph end with end if next next end SUB

    array.vbs

    ' File: array.vbs ' ' Demonstrate very basic array functionality. Option Explicit dim i, j ' to be used for subscripting arrays dim A(10) ' A has 11 elements: A(0) to A(10) for i = 0 to 6 A(i) = 2 * i next ' notice there are only have 6 entries in a size 11 array call printOneArray(A, "This is the A Array") dim B B = Array(11, 22, 33, 44) ' This is the same as: dim B(3) with setting ' B(0) = 11 ' B(1) = 22 ' B(2) = 33 ' B(3) = 44 call printOneArray(B, "This is the B Array") ' C is a 2-dimensional array, with 3 rows and 4 columns ' The first subscript is the row, second is column, ' e.g., C(1,2) is the element in row 1, column 2 dim C(2, 3) for i = 0 to 2 for j = 0 to 3 C(i,j) = i + j next next call printTwoDArray(C, "This is the C Array") '---------------------------------------------------------------------------- ' printOneArray ' Takes in 2 input parameters, the array to display and a string which ' is a description of what is displayed to be used as the MsgBox title. ' It displays the contents of the array in message box titled description. SUB printOneArray(ByRef myArray, ByRef description) dim output, i output = "" For i = 0 to UBound(myArray) output = output & "myArray(" & i & ") = " & myArray(i) & vbNewLine next ' concatenate lower and upper bound of the array output = output & "Array Lower Bound: " & LBound(myArray) & vbNewLine output = output & "Array Upper Bound: " & UBound(myArray) & vbNewLine MsgBox output, ,description end SUB '---------------------------------------------------------------------------- ' printTwoDArray ' Takes in 2 input parameters, the 2D array to display and a string which ' is a description of what is displayed to be used as the MsgBox title. ' It displays the contents of the array in message box titled description. SUB printTwoDArray(ByRef myArray, ByRef description) dim output, i, j output = "" for i = 0 to UBound(myArray, 1) for j = 0 to UBound(myArray, 2) output = output & "myArray(" & i & "," & j &") = " & _ myArray(i,j) & vbNewLine next output = output & vbNewLine next ' concatenate lower and upper bound of the array ' second parameter of LBound or UBound is the dimension output = output & "Array Row Lower Bound: " & LBound(myArray, 1) & vbNewLine output = output & "Array Row Upper Bound: " & UBound(myArray, 1) & vbNewLine output = output & "Array Col Lower Bound: " & LBound(myArray, 2) & vbNewLine output = output & "Array Col Upper Bound: " & UBound(myArray, 2) & vbNewLine MsgBox output, ,description end SUB

    arrayDynamic.vbs

    ' File: arrayDynamic.vbs ' Demonstrate dynamic arrays. Option Explicit dim A(), B() ' A and B have no memory allocated yet redim A(3), B(5) ' allocate 4 elements for A, 6 elements for B call fillArrayWithMult2(A, 0, UBound(A)) call fillArrayWithMult2(B, 0, UBound(B)) call printOneArray(A, "This is the A Array with 4 values") call printOneArray(B, "This is the B Array with 6 values") ' redimension A to be of size 11 and display ' notice different memory is allocated and you lose all the values ' of the original array A redim A(10) call printOneArray(A, "This is the A Array with 10 values, redimensioned") ' fill again and display call fillArrayWithMult2(A, 0, UBound(A)) call printOneArray(A, "This is the A Array with 10 values, redimensioned") ' preserve the values in B by using "preserve" keyword redim preserve B(10) call printOneArray(B, "This is the B Array with 10 values, preserved") ' can fill some or the rest of B call fillArrayWithMult2(B, 7, 9) call printOneArray(B, "This is the B Array with 10 values, preserved and more") '---------------------------------------------------------------------------- ' fillArrayWithMult2: ' SUB fillArrayWithMult2(ByRef myArray, ByVal beginIndex, ByVal endIndex) dim i for i = beginIndex to endIndex myArray(i) = 2 * i next end SUB '---------------------------------------------------------------------------- ' printOneArray ' Takes in 2 input parameters, the array to display and a string which ' is a description of what is displayed to be used as the MsgBox title. ' It displays the contents of the array in message box titled description. SUB printOneArray(ByRef myArray, ByRef description) dim output, i output = "" for i = 0 to UBound(myArray) output = output & "myArray(" & i & ") = " & myArray(i) & vbNewLine next ' concatenate lower and upper bound of the array output = output & "Array Lower Bound: " & LBound(myArray) & vbNewLine output = output & "Array Upper Bound: " & UBound(myArray) & vbNewLine MsgBox output, ,description end SUB

    linearSearch.vbs

    ' File: linearSearch.vbs ' ' Open a text file to save names into an array. ' Open another text file to save grades into another array. ' Given a name to search for, display the grade. Option Explicit dim names(50) ' holds names dim grades(50) ' holds grades dim count ' total number of names, subscript 0 to count-1 dim count2 ' used for filling array with grades count = 0 count2 = 0 ' Fill the names and grades arrays with data from text files that ' are opened in the subroutine. Display the two arrays in MsgBoxes. call fillArray(names, count) call fillArray(grades, count2) call printOneArray(names, "The names") call printOneArray(grades, "The grades") dim targetName ' name to search for dim foundGrade ' grade associated with name ' For each name that is entered, locate the name in the names array, ' and display the associated grade from the grades array. do targetName = inputBox("Enter a name to search for [enter to quit]") if targetName = "" then exit do end if ' search the names array for targetName and return the associated grade foundGrade = gradeValue(targetName, names, grades, count) if foundGrade <> -1 then MsgBox(targetName & " has a grade of " & foundGrade) else MsgBox(targetName & " was not found in the list of names") end if loop '------------------------------------------------------------------------------ ' gradeValue ' Given an array of names and an array of grades with the count of how ' many are in the array, return the grade of the entered name. ' Return a -1 if the name is not found. FUNCTION gradeValue(ByVal targetName, ByRef names, ByRef grades, ByVal count) dim i, found i = 0 found = FALSE ' have not found name yet gradeValue = -1 ' Look for targetName as long as we are still within the bounds ' of the array and the name has not been found yet. do while i <= count and not found if names(i) = targetName then gradeValue = grades(i) found = TRUE end if i = i + 1 loop end FUNCTION '------------------------------------------------------------------------------ ' fillArray ' Open a text file and read the data into an array. ' The count will be the true size of the array (number of elements in use). SUB fillArray(ByRef myArray, ByRef count) ' ask the scripting runtime environemt for access to files dim FS set FS = CreateObject("Scripting.FileSystemObject") const FILEFORREADING = 1 dim dataFile dataFile = selectAFileOrFolder("FILE") if FS.FileExists(dataFile) then ' get the fileHander based on the dataFile dim FileHandler set FileHandler = FS.GetFile(dataFile) ' open the file as a inputTextStream so text data can be "streamed" dim inputTextStream set inputTextStream = FileHandler.OpenAsTextStream(FILEFORREADING) dim inputLine ' a line in the file ' As long as we're not at the end of the file, read a line from ' the file and place it into myArray. do while not inputTextStream.AtEndOfStream inputLine = inputTextStream.ReadLine myArray(count) = inputLine count = count + 1 loop else MsgBox "File: " & dataFile & " does not exists." end if end SUB '---------------------------------------------------------------------------- ' printOneArray ' Takes in 2 input parameters, the array to display and a string which ' is a description of what is displayed to be used as the MsgBox title. ' It displays the contents of the array in message box titled description. SUB printOneArray(ByRef myArray, ByRef description) dim output, i output = "" For i = 0 to UBound(myArray) output = output & "myArray(" & i & ") = " & myArray(i) & vbNewLine next MsgBox output, ,description end SUB '------------------------------------------------------------------------------ ' selectAFileOrFolder ' Takes in one input parameter, "FILE" or "FOLDER", and returns its path ' in a string that contains either the selected file or folder path. FUNCTION selectAFileOrFolder(ByRef fileOrFolder) dim WshShell, currentFolder ' Open a "connection" to the "operating environment" . ' WshShell contains the environment for which we are operating in. ' For example, below we will use it to retrieve the current working folder. set WshShell = WScript.CreateObject("WScript.Shell") ' Get the current folder (where this script is opened from). ' currentFolder now contains the path to the folder currentFolder = wshShell.CurrentDirectory ' XlAppl is our "connection" to all functions MS Excel provides dim XlAppl set XlAppl = WScript.CreateObject("Excel.Application") ' don't let user see what is going on, ' can switch the visibility of MSon/off (TRUE/FALSE) XlAppl.Application.Visible = FALSE ' specific constants to OFFICE Object. ' VBScript cannot see these constants, so we have ' to find out what they are, and re-define them. dim msoFileDialogOpen if (fileOrFolder = "FILE") then msoFileDialogOpen = 1 end if if (fileOrFolder = "FOLDER") then msoFileDialogOpen = 4 end if ' OpenFile Dialog we use MSO facility, since MSO is implemented in either ' Word, Excel, even PowerPoint. It can be used in exactly the same way. ' Notice "set" is used here too. dim DlgOpen set DlgOpen = XlAppl.Application.FileDialog(msoFileDialogOpen) ' Only allow selection of one file ' TRUE: Allow multiple file selection ' FALSE: Do not allow multiple file selection DlgOpen.AllowMultiSelect = FALSE ' Set up the "Filters" so that we only work with certain types of files. ' ' DlgOpen.Filters.Clear ' DlgOpen.Filters.Add "Text Files", "*.txt", 1 ' Only want to work with Text files ' The parameters of Add are: ' 1st - description of what is the file type ' 2nd - the extension (don't forget the "*") ' 3rd - the position for this entry ' Start looking from current working folder ' currentFolder contains the path to the folder where this script is located DlgOpen.InitialFileName = currentFolder SelectAFileOrFolder = "" ' Set the return value to "" if (DlgOpen.Show() = -1) then ' -1 says user clicked on "Open" ' first selected item is the file name SelectAFileOrFolder = DlgOpen.SelectedItems(1) end if ' TRUE: Prompt user to save the work ' FALSE: Do not prompt user to save the work XlAppl.Application.DisplayAlerts = FALSE XlAppl.Application.Quit ' quit the application end FUNCTION

    names.txt

    Joe Sue Andy Sally Jane Bill John Mary

    grades.txt

    82 70 60 95 85 74 92 67

    bubble.vbs

    ' File: bubble.vbs ' ' Sort a list of numbers using a bubble sort Option Explicit const MINVALUE = 0 const MAXVALUE = 1000 dim a(20) ' array to demonstrate bubble sort ' Initialize the random generation system of VB-script. ' After this call, Rnd will return a number between 0 and 1. Randomize call fillWithRandomNumbers(a, MINVALUE, MAXVALUE) call printOneArray(a, "An unsorted array") call bubbleSort(a) call printOneArray(a, "A sorted array") '---------------------------------------------------------------------------- ' bubbleSort ' Sort the input array using a bubble sort SUB bubbleSort(ByRef a()) dim pass ' pass of the sort dim done ' whether sorted or not dim i, temp pass = 0 done = FALSE ' Each pass puts one element into its sorted position, ' smallest value bubbles to the top of the array. while not done done = TRUE ' possibly sorted ' compare consecutive elements, swap if out of order for i = UBound(a) to pass+1 step -1 if a(i) < a(i-1) then temp = a(i) ' swap a(i) and a(i-1) a(i) = a(i-1) a(i-1) = temp done = FALSE ' had to swap so still not sorted end if next pass = pass + 1 wend end SUB '---------------------------------------------------------------------------- ' printOneArray ' Takes in 2 input parameters, the array to display and a string which ' is a description of what is displayed to be used as the MsgBox title. ' It displays the contents of the array in message box titled description. SUB printOneArray(ByRef myArray, ByRef description) dim output, i output = "" for i = 0 to UBound(myArray) output = output & "myArray(" & i & ") = " & myArray(i) & vbNewLine next MsgBox output, ,description end SUB '---------------------------------------------------------------------------- ' RandomNumber ' Given two input parameters, a min value and max value for a range of numbers, ' it will generate and return random number between the parameter values. FUNCTION RandomNumber(ByVal min, ByVal max) RandomNumber = CInt( ((max - min + 1) * Rnd) + min) end FUNCTION '---------------------------------------------------------------------------- ' fillWithRandomNumbers ' Given an input array, fill it with random numbers generated by a ' random number generator. SUB fillWithRandomNumbers(ByRef a, ByRef minValue, ByRef maxValue) dim index 'continually generate random numbers to fill the array for index = 0 to UBound(a) a(index) = RandomNumber(minValue, maxValue) next end SUB

    list all available ProgIDs

    The following VBScript code can be used to list all available ProgIDs: Option Explicit Const HKEY_CLASSES_ROOT = &H80000000 Dim arrProgID, lstProgID, objReg, strMsg, strProgID, strSubKey, subKey, subKeys() Set lstProgID = CreateObject( "System.Collections.ArrayList" ) Set objReg = GetObject( "winmgmts://./root/default:StdRegProv" ) ' List all subkeys of HKEY_CLASSES_ROOT\CLSID objReg.EnumKey HKEY_CLASSES_ROOT, "CLSID", subKeys ' Loop through the list of subkeys For Each subKey In subKeys ' Check each subkey for the existence of a ProgID strSubKey = "CLSID\" & subKey & "\ProgID" objReg.GetStringValue HKEY_CLASSES_ROOT, strSubKey, "", strProgID ' If a ProgID exists, add it to the list If Not IsNull( strProgID ) Then lstProgID.Add strProgID Next ' Sort the list of ProgIDs lstProgID.Sort ' Copy the list to an array (this makes displaying it much easier) arrProgID = lstProgID.ToArray ' Display the entire array WScript.Echo Join( arrProgID, vbCrLf )

    StdOut.Write

    Echo text to the screen (Stdout) Syntax WScript.StdOut.Write("text string to display") WScript.StdOut.Write(strMyTextVariable) Example Set objStdOut = WScript.StdOut objStdOut.Write "User: " objStdOut.Write "Joe Smith" objStdOut.WriteBlankLines(1) objStdOut.Write "Procurement Dept"

    VBScript Do While Loop

    Dim x x=1 Do While x<5 document.write("Welcome.") x=x+1 Loop Dim x x=7 Do document.write("Welcome.") x=x+1 Loop While x<5

    VBScript Do Until Loop

    <script type="text/vbscript"> Dim x x=1 Do Until x=5 document.write("Welcome.") x=x+1 Loop </script>

    VBScript While Loop

    Dim x x = 1 While x < 5 document.write("Welcome.") x=x+1 Wend

    VBScript For-Next Loop

    For i = 1 To 5 document.write("The number is " & i & " ") Next

    VBScript For-Step-Next Loop

    For i = 1 To 5 Step 2 document.write("The number is " & i & "<br />") Next For i = 1 To 5 Step 2 If i=3 Then Exit For document.write("The number is " & i & "<br />") Next

    VBScript For-Each-Next Loop

    Dim students(4) students(0)="John" students(1)="Hanah" students(2)="Sarah" students(3)="Kevin" students(4)="Emma" For Each x In students document.write(x & "<br />") Next Dim name, length name = InputBox("Enter your name") length = Len(name)’Gives length of the input string For i = 1 To length txt = Mid(name,i,1)'Returns a specified number of characters from a string, the first parameter is the string, second parameter is the starting position and third parameter is the number of characters to return If txt="a" or txt="A" or txt="e" or txt="E" or txt="i" or txt="I" or txt="o" or txt="O" or txt="u" or txt="U" Then counter = counter+1 End If Next document.write("Hi " & name & "!!!Your name contains " & counter & " vowels.")

    Run a vbscript from another vbscript

    Run a vbscript from another vbscript CreateObject("WScript.Shell").Run "Your-VBScript-Here" Dim objShell Set objShell = Wscript.CreateObject("WScript.Shell") objShell.Run "TestScript.vbs" ' Using Set is mandatory Set objShell = Nothing

    Show time

    Show time in form 24 hours Right("0" & hour(now),2) & ":" & Right("0" & minute(now),2) = 01:35 Right("0" & hour(now),2) = 01 Right("0" & minute(now),2) = 35 FormatDateTime(Now) = 2/29/2016 1:02:03 PM FormatDateTime(Now, vbGeneralDate) = 2/29/2016 1:02:03 PM FormatDateTime(Now, vbLongDate) = Monday, February 29, 2016 FormatDateTime(Now, vbShortDate) = 2/29/2016 FormatDateTime(Now, vbLongTime) = 1:02:03 PM FormatDateTime(Now, vbShortTime) = 13:02 FormatDateTime(now, 4) = 08:12 Year(Now) = 2016 Month(Now) = 2 Day(Now) = 29 Hour(Now) = 13 Minute(Now) = 2 Second(Now) = 3 Year(Date) = 2016 Month(Date) = 2 Day(Date) = 29 Hour(Time) = 13 Minute(Time) = 2 Second(Time) = 3 Function LPad (str, pad, length) LPad = String(length - Len(str), pad) & str End Function LPad(Month(Date), "0", 2) = 02 LPad(Day(Date), "0", 2) = 29 LPad(Hour(Time), "0", 2) = 13 LPad(Minute(Time), "0", 2) = 02 LPad(Second(Time), "0", 2) = 03 Weekday(Now) = 2 WeekdayName(Weekday(Now), True) = Mon WeekdayName(Weekday(Now), False) = Monday WeekdayName(Weekday(Now)) = Monday MonthName(Month(Now), True) = Feb MonthName(Month(Now), False) = February MonthName(Month(Now)) = February Set os = GetObject("winmgmts:root\cimv2:Win32_OperatingSystem=@") os.LocalDateTime = 20131204215346.562000-300 Left(os.LocalDateTime, 4) = 2013 ' year Mid(os.LocalDateTime, 5, 2) = 12 ' month Mid(os.LocalDateTime, 7, 2) = 04 ' day Mid(os.LocalDateTime, 9, 2) = 21 ' hour Mid(os.LocalDateTime, 11, 2) = 53 ' minute Mid(os.LocalDateTime, 13, 2) = 46 ' second Dim wmi : Set wmi = GetObject("winmgmts:root\cimv2") Set timeZones = wmi.ExecQuery("SELECT Bias, Caption FROM Win32_TimeZone") For Each tz In timeZones tz.Bias = -300 tz.Caption = (UTC-05:00) Eastern Time (US & Canada) Next

    inputbox

    dim v v = inputbox ("what is ur name?") msgbox " hello, " & v beep to beep multiple times Beeep(3) Sub Beeep(itimes) dim itemp For itemp = 1 to itimes beep next end sub

    Play a beep in VBS

    From Windows Scripting Host you can do either one of the below: Set Shell = CreateObject("WScript.Shell") Shell.Run "sndrec32 /play /close %windir%\media\ding.wav",0 or Set Shell = CreateObject("WScript.Shell") Shell.Run "%comspec% /cecho " & Chr(7),0 or strSoundFile = “C:\Windows\Media\Notify.wav” Set objShell = CreateObject(“Wscript.Shell”) strCommand = “sndrec32 /play /close ” & chr(34) & strSoundFile & chr(34) objShell.Run strCommand, 0, True To run Sound Recorder from the command-prompt, we need to type in this command: sndrec32 /play /close “C:\Windows\Media\Notify.wav” Sample script that plays a sound and pops up a message box: strSoundFile = “C:\windows\Media\Notify.wav” Set objShell = CreateObject(“Wscript.Shell”) strCommand = “sndrec32 /play /close ” & chr(34) & strSoundFile & chr(34) objShell.Run strCommand, 0, False Wscript.Sleep 1000 Msgbox “A problem has occurred.”

    vbs call external program with parameters

    Set WshShell = CreateObject("WScript.Shell") WshShell.Exec("C:\Program Files\App\start.exe -resexport -r C:\test.txt") Set ss = CreateObject("WScript.Shell") ss.run "COMMAND /C C:\util\pkzip.exe a:master02.zip",1,TRUE Set WshShell = WScript.CreateObject("WScript.Shell") runCmd = "%systemroot%\system32\servermanagercmd.exe -install SNMP-Service" WshShell.Run "cmd /c " & runCmd, 0, True The following VBScript code opens a copy of the currently running script with Notepad. Set WshShell = WScript.CreateObject("WScript.Shell") WshShell.Run "%windir%\notepad " & WScript.ScriptFullName Set WshShell = WScript.CreateObject("WScript.Shell") Return = WshShell.Run("notepad " & WScript.ScriptFullName, 1, true) Dim oShell Set oShell = WScript.CreateObject ("WSCript.shell") oShell.run "cmd /K CD C:\ & Dir" Set oShell = Nothing

    play sound

    Dim oPlayer Set oPlayer = CreateObject("WMPlayer.OCX") oPlayer.URL = "C:\Windows\Media\Notify.wav" oPlayer.controls.play While oPlayer.playState <> 1 ' 1 = Stopped WScript.Sleep 100 Wend oPlayer.URL = "C:\Windows\Media\recycle.wav" While oPlayer.playState <> 1 ' 1 = Stopped WScript.Sleep 100 Wend oPlayer.close

    call R script from VB Script

    Dim oShell As Object Set oShell = CreateObject("WScript.Shell") Dim oExec As Object Dim oOutput As Object Set oExec = oShell.Exec("C:\Program Files\R\R-3.2.3\bin\Rscript.exe C:\SubFolder\YourScriptName.R " & "" & var1 & "") Set oOutput = oExec.StdOut "handle the results as they are written to and read from the StdOut object" Dim s As String Dim sLine As String While Not oOutput.AtEndOfStream sLine = oOutput.ReadLine If sLine <> "" Then s = s & sLine & vbCrLf Wend Above code also showing how to pass arguments to Rscript. If your Rscript returns value it will return to vbscript again.

    Calling MPlayer

    Set WshShell = WScript.CreateObject("WScript.Shell") WshShell.Run """c:\mplayer.exe"" ""I:\DVCapture\video.avi"""

    Video Downloader

    Writing a YouTube Video Downloader

    use of input box and speak message

    Dim message, sapi message = InputBox("What do you want me to say?","Made by Candy") Set sapi=CreateObject("sapi.spvoice") sapi.Speak message Dim text, speech text = "High critical limit" Set speech = CreateObject("SAPI.SpVoice") speech.Speak text

    Converting alarm/event text to speech

    https://www.reliance-scada.com/en/support/articles/technical/vbscript-tip-converting-alarm-event-text-to-speech

    VBScript to run .bat file

    Set shell = CreateObject("WScript.Shell") shell.CurrentDirectory = "C:\Users\js\Desktop\createIndex" shell.Run "createindex.bat" https://stackoverflow.com/questions/34820685/want-to-use-vbscript-to-run-bat-file-in-a-different-folder

    speak the time

    Dim speech, hr, sez hr=hour(time) if hr=0 then hr = 12 end if if hr>12 then hr = hr - 12 end if sez = hr & " O'clock" Set speech = CreateObject("sapi.spvoice") speech.Speak sez Wscript.Quit

    print random number

    Sub randomAnum() nLow = 1 nHigh = 100 Randomize msgbox Int((nHigh - nLow + 1) * Rnd + nLow) End Sub randomAnum()

    randomly play a sound

    Randomize With CreateObject("WMPlayer.OCX") .URL = "C:\Users\User\Music\freesound\" & Int(Rnd * 2027)) & ".mp3" .controls.play Do While .playState <> 1 WScript.Sleep 100 Loop .close End With

    Regular Expressions

    Regular Expressions is a sequence of characters that forms a pattern, which is mainly used for search and replace. The purpose of creating a pattern is to match specific strings, so that the developer can extract characters based on conditions and replace certain characters. RegExp Object RegExp object helps the developers to match the pattern of strings and the properties and methods help us to work with Regular Expressions easily. It is similar to RegExp in JavaScript Properties Pattern − The Pattern method represents a string that is used to define the regular expression and it should be set before using the regular expression object. IgnoreCase − A Boolean property that represents if the regular expression should be tested against all possible matches in a string if true or false. If not specified explicitly, IgnoreCase value is set to False. Global − A Boolean property that represents if the regular expression should be tested against all possible matches in a string. If not specified explicitly, Global value is set to False. Methods Test(search-string) − The Test method takes a string as its argument and returns True if the regular expression can successfully be matched against the string, otherwise False is returned. Replace(search-string, replace-string) − The Replace method takes 2 parameters. If the search is successful then it replaces that match with the replace-string, and the new string is returned. If there are no matches then the original search-string is returned. Execute(search-string) − The Execute method works like Replace, except that it returns a Matches collection object, containing a Match object for each successful match. It doesn't modify the original string. Matches Collection Object The Matches collection object is returned as a result of the Execute method. This collection object can contain zero or more Match objects and the properties of this object are read-only. Count − The Count method represents the number of match objects in the collection. Item − The Item method enables the match objects to be accessed from matches collections object. Match Object The Match object is contained within the matches collection object. These objects represent the successful match after the search for a string. FirstIndex − It represents the position within the original string where the match occurred. This index are zero-based which means that the first position in a string is 0. Length − A value that represents the total length of the matched string. Value − A value that represents the matched value or text. It is also the default value when accessing the Match object. All about Pattern Parameter The pattern building is similar to PERL. Pattern building is the most important thing while working with Regular Expressions. In this section, we will deal with how to create a pattern based on various factors. Position Matching The significance of position matching is to ensure that we place the regular expressions at the correct places. Symbol Description ^ Matches only the beginning of a string. $ Match only the end of a string. \b Matches any word boundary \B Matches any non-word boundary Literals Matching Any form of characters such as alphabet, number or special character or even decimal, hexadecimal can be treated as a Literal. Since few of the characters have already got a special meaning within the context of Regular Expression, we need to escape them using escape sequences. Symbol Description Alphanumeric Matches alphabetical and numerical characters only. \n Matches a new line. \[ Matches [ literal only \] Matches ] literal only \( Matches ( literal only \) Matches ) literal only \t Matches horizontal tab \v Matches vertical tab \| Matches | literal only \{ Matches { literal only \} Matches } literal only \\ Matches \ literal only \? Matches ? literal only \* Matches * literal only \+ Matches + literal only \. Matches . literal only \b Matches any word boundary \B Matches any non-word boundary \f Matches a form feed \r Matches carriage return \xxx Matches the ASCII character of an octal number xxx. \xdd Matches the ASCII character of an hexadecimal number dd. \uxxxx Matches the ASCII character of an UNICODE literal xxxx. Character Classes Matching The character classes are the Pattern formed by customized grouping and enclosed within [ ] braces. If we are expecting a character class that should not be in the list, then we should ignore that particular character class using the negative symbol, which is a cap ^. Symbol Description [xyz] Match any of the character class enclosed within the character set. [^xyz] Matches any of the character class that are NOT enclosed within the character set. . Matches any character class except \n \w Match any word character class. Equivalent to [a-zA-Z_0-9] \W Match any non-word character class. Equivalent to [^a-zA-Z_0-9] \d Match any digit class. Equivalent to [0-9]. \D Match any non-digit character class. Equivalent to [^0-9]. \s Match any space character class. Equivalent to [ \t\r\n\v\f] \S Match any space character class. Equivalent to [^\t\r\n\v\f] Repetition Matching Repetition matching allows multiple searches within the regular expression. It also specifies the number of times an element is repeated in a Regular Expression. Symbol Description * Matches zero or more occurrences of the given regular Expression. Equivalent to {0,}. + Matches one or more occurrences of the given regular Expression. Equivalent to {1,}. ? Matches zero or one occurrences of the given regular Expression. Equivalent to {0,1}. {x} Matches exactly x number of occurrences of the given regular expression. {x,} Match atleast x or more occurrences of the given regular expression. {x,y} Matches x to y number of occurences of the given regular expression. Alternation & Grouping Alternation and grouping helps developers to create more complex Regular Expressions in particularly handling intricate clauses within a Regular Expression which gives a great flexibility and control. Symbol Description 0 Grouping a clause to create a clause. "(xy)?(z)" matches "xyz" or "z". | Alternation combines one regular expression clause and then matches any of the individual clauses. "(ij)|(23)|(pq)" matches "ij" or "23" or "pq". Building Regular Expressions Given below are a few examples that clearly explain how to build a Regular Expression. Regular Expression Description "^\s*.." and "..\s*$" Represents that there can be any number of leading and trailing space characters in a single line. "((\$\s?)|(#\s?))?" Represents an optional $ or # sign followed by an optional space. "((\d+(\.(\d\d)?)?))" Represents that at least one digit is present followed by an optional decimals and two digits after decimals.

    Regular Expressions Example

    strid = "welcome.user@tutorialspoint.co.us" Set re = New RegExp With re .Pattern = "^[\w-\.]{1,}\@([\da-zA-Z-]{1,}\.){1,}[\da-zA-Z-]{2,3}$" .IgnoreCase = False .Global = False End With ' Test method returns TRUE if a match is found If re.Test( strid ) Then Document.write(strid & " is a valid e-mail address") Else Document.write(strid & " is NOT a valid e-mail address") End If Set re = Nothing

    VB scripts samples

    VB scripts samples

    Option Explicit

    Use Option Explicit to generate an error whenever a variable that has not been declared is encountered. The Option Explicit statement must appear in a script before any other statements; otherwise, a nontrappable error occurs. Where Option Explicit is used, all variables must be declared using the Dim, Private, Public, or ReDim statements.

    vbs calculator

    Dim strResult: strResult = Wscript.ScriptName Dim strExpr, strInExp, strLastY, yyy strInExp = "1+1" strLastY = "" Do While True strExpr = inputbox("Last calculation:" & vbCR & strLastY, "Calculator", strInExp) If Len( strExpr) = 0 Then Exit Do ''' in my locale, decimal separator is a comma but VBScript arithmetics premises a dot strExpr = Replace( strExpr, ",", ".") ''' locale specific On Error Resume Next ' enable error handling yyy = Eval( strExpr) If Err.Number = 0 Then strInExp = CStr( yyy) strLastY = strExpr & vbTab & strInExp strResult = strResult & vbNewLine & strLastY Else strLastY = strExpr & vbTab & "!!! 0x" & Hex(Err.Number) & " " & Err.Description strInExp = strExpr strResult = strResult & vbNewLine & strLastY End If On Error GoTo 0 ' disable error handling Loop Wscript.Echo strResult Wscript.Quit

    Creating and writing lines to a file

    Set objFSO=CreateObject("Scripting.FileSystemObject") ' How to write file outFile="c:\test\autorun.inf" Set objFile = objFSO.CreateTextFile(outFile,True) objFile.Write "test string" & vbCrLf objFile.Close 'How to read a file strFile = "c:\test\file" Set objFile = objFS.OpenTextFile(strFile) Do Until objFile.AtEndOfStream strLine= objFile.ReadLine Wscript.Echo strLine Loop objFile.Close 'to get file path without drive letter, assuming drive letters are c:, d:, etc strFile="c:\test\file" s = Split(strFile,":") WScript.Echo s(1)

    Read files from URL

    url = "http://main/shared/css/main.css" Set req = CreateObject("Msxml2.XMLHttp.6.0") req.open "GET", url, False req.send If req.Status = 200 Then Set fso = CreateObject("Scripting.FileSystemObject") fso.OpenTextFile("C:\main.txt", 2).Write req.responseText End If

    Run a vbscript from another vbscript

    Dim oShell Set oShell = Wscript.CreateObject("WScript.Shell") oShell.Run "name_of_vbs_file_here.vbs" Set oShell = Nothing Dim objShell Set objShell = Wscript.CreateObject("WScript.Shell") objShell.Run "TestScript.vbs" ' Using Set is mandatory Set objShell = Nothing Send 3 arguments like this: objShell.Run "TestScript.vbs 42 ""an arg containing spaces"" foo" Using the Wshshell.Run method or the WshShell.Exec method give you control to terminate it, get a response, pass more parameters (other than commandline args), get status, and others To use Run (Simple Method) Dim ProgramPath, WshShell, ProgramArgs, WaitOnReturn,intWindowStyle Set WshShell=CreateObject ("WScript.Shell") ProgramPath="c:\test run script.vbs" ProgramArgs="/hello /world" intWindowStyle=1 WaitOnReturn=True WshShell.Run Chr (34) & ProgramPath & Chr (34) & Space (1) & ProgramArgs,intWindowStyle, WaitOnReturn To Use EXEC (Advanced Method) Dim ProgramPath, WshShell, ProgramArgs, Process, ScriptEngine Set WshShell=CreateObject ("WScript.Shell") ProgramPath="c:\test run script.vbs" ProgramArgs="/hello /world" ScriptEngine="CScript.exe" Set Process=WshShell.Exec (ScriptEngine & space (1) & Chr(34) & ProgramPath & Chr (34) & Space (1) & ProgramArgs) Do While Process.Status=0 'Currently Waiting on the program to finish execution. WScript.Sleep 300 Loop

    load the body of the script and execute it within the same process

    Set fs = CreateObject("Scripting.FileSystemObject") Set ts = fs.OpenTextFile("script2.vbs") body = ts.ReadAll ts.Close Execute body

    VBScript RegExp

    VBScript RegExp use vbNewLine, vbTab and vbCrLf instead of \n\r\t when you use replace like: newLine = re.Replace(oldLine, vbTab) ( < this is what you'd use if you want to replace 4 spaces with a Tab for example), while you should use the escaped characters in the pattern like re.Pattern = "\t" Examples 'this sub finds the matches Sub RegExpTest(strMatchPattern, strPhrase) 'create variables Dim objRegEx, Match, Matches, StrReturnStr 'create instance of RegExp object Set objRegEx = New RegExp 'find all matches objRegEx.Global = True 'set case insensitive objRegEx.IgnoreCase = True 'set the pattern objRegEx.Pattern = strMatchPattern 'create the collection of matches Set Matches = objRegEx.Execute(strPhrase) 'print out all matches For Each Match in Matches strReturnStr = "Match found at position " strReturnStr = strReturnStr Match.FirstIndex ". Match Value is '" strReturnStr = strReturnStr Match.value "'." 'print Response.Write(strReturnStr "
    ") Next End Sub 'call the subroutine RegExpTest "is.", "Is1 is2 Is3 is4" %> Output: Match found at position 0. Match Value is 'Is1'. Match found at position 4. Match Value is 'is2'. Match found at position 8. Match Value is 'Is3'. Match found at position 12. Match Value is 'is4'.

    MsgBox

    MsgBox(prompt[,buttons][,title][,helpfile,context]) Prompt − A Required Parameter. A String that is displayed as a message in the dialog box. The maximum length of prompt is approximately 1024 characters. If the message extends to more than a line, then we can separate the lines using a carriage return character (Chr(13)) or a linefeed character (Chr(10)) between each line. buttons − An Optional Parameter. A Numeric expression that specifies the type of buttons to display, the icon style to use, the identity of the default button, and the modality of the message box. If left blank, the default value for buttons is 0. Title − An Optional Parameter. A String expression displayed in the title bar of the dialog box. If the title is left blank, the application name is placed in the title bar. helpfile − An Optional Parameter. A String expression that identifies the Help file to use to provide context-sensitive help for the dialog box. context − An Optional Parameter. A Numeric expression that identifies the Help context number assigned by the Help author to the appropriate Help topic. If context is provided, helpfile must also be provided. The Buttons parameter can take any of the following values − 0 vbOKOnly Displays OK button only. 1 vbOKCancel Displays OK and Cancel buttons. 2 vbAbortRetryIgnore Displays Abort, Retry, and Ignore buttons. 3 vbYesNoCancel Displays Yes, No, and Cancel buttons. 4 vbYesNo Displays Yes and No buttons. 5 vbRetryCancel Displays Retry and Cancel buttons. 16 vbCritical Displays Critical Message icon. 32 vbQuestion Displays Warning Query icon. 48 vbExclamation Displays Warning Message icon. 64 vbInformation Displays Information Message icon. 0 vbDefaultButton1 First button is default. 256 vbDefaultButton2 Second button is default. 512 vbDefaultButton3 Third button is default. 768 vbDefaultButton4 Fourth button is default. 0 vbApplicationModal Application modal. The current application will not work until the user responds to the message box. 4096 vbSystemModal System modal. All applications will not work until the user responds to the message box. The above values are logically divided into four groups: The first group(0 to 5) indicates the buttons to be displayed in the message box. The second group (16, 32, 48, 64) describes the sytle of the icon to be displayed, the third group (0, 256, 512, 768) indicates which button must be the default, and the fourth group (0, 4096) determines the modality of the message box. Return Values The MsgBox function can return one of the following values − 1 - vbOK - OK was clicked 2 - vbCancel - Cancel was clicked 3 - vbAbort - Abort was clicked 4 - vbRetry - Retry was clicked 5 - vbIgnore - Ignore was clicked 6 - vbYes - Yes was clicked 7 - vbNo - No was clicked Example MsgBox("Welcome") a = MsgBox("Do you like blue color?",3,"Choose options") document.write("The Value of a is " & a) When the above script is executed, the message box is displayed, and if you press No Button, then the value of a is 7. The Value of a is 7

    InputBox

    The InputBox function helps the user to get the values from the user. After entering the values, if the user clicks the OK button or presses ENTER on the keyboard, the InputBox function will return the text in the text box. If the user clicks on the Cancel button, the function will return an empty string (""). Syntax InputBox(prompt[,title][,default][,xpos][,ypos][,helpfile,context]) Parameter Description Prompt − A Required Parameter. A String that is displayed as a message in the dialog box. The maximum length of prompt is approximately 1024 characters. If the message extends to more than a line, then we can separate the lines using a carriage return character (Chr(13)) or a linefeed character (Chr(10)) between each line. Title − An Optional Parameter. A String expression displayed in the title bar of the dialog box. If the title is left blank, the application name is placed in the title bar. Default − An Optional Parameter. A default text in the text box that the user would like to be displayed. XPos − An Optional Parameter. The Position of X axis which represents the prompt distance from left side of the screen horizontally. If left blank, the input box is horizontally centered. YPos − An Optional Parameter. The Position of Y axis which represents the prompt distance from left side of the screen Vertically. If left blank, the input box is Vertically centered. helpfile − An Optional Parameter. A String expression that identifies the Help file to use to provide context-sensitive Help for the dialog box. context − An Optional Parameter. A Numeric expression that identifies the Help context number assigned by the Help author to the appropriate Help topic. If context is provided, helpfile must also be provided. Example InputBox("Enter a number") a = InputBox("Enter a Number","Enter Value") msgbox a a = InputBox("Enter a Number","Enter Value",123) msgbox a a = InputBox("Enter your name","Enter Value",123,700) msgbox a a = InputBox("Enter your name","Enter Value",123,,500) msgbox a

    display an image

    Create a VBS file: Set objExplorer = CreateObject("InternetExplorer.Application") With objExplorer .Navigate "about:blank" .Visible = 1 .Document.Title = "Show Image" .Toolbar=False .Statusbar=False .Top=400 .Left=400 .Height=200 .Width=200 .Document.Body.InnerHTML = "<img src='C:\Users\pankaj\Desktop\a.jpg'>" End With

    VBS call chrome

    Dim objShell Set objShell = WScript.CreateObject("WScript.Shell") objShell.Run "https://www.youtube.com/watch?v=nIpPSh4h_AA" OR: Dim URL, theShell URL = "D:/Dropbox/Public/start20120304.htm" set theShell = CreateObject("Shell.Application") theShell.ShellExecute "chrome.exe", URL, "", "", 1

    Shell.Application

    The wscript.Shell + Shell.Application objects Provides access to OS Shell methods.

    Wscript.Shell

    Syntax Set objShell = CreateObject("Wscript.Shell") Methods .AppActivate 'Activate running command. .Run 'Run an application .TileVertically 'Tile app windows .RegRead 'Read from registry .RegDelete 'Delete from registry .RegWrite 'Write to the registry

    Shell.Application

    Syntax Set objShell = CreateObject("Shell.Application") Methods .CanStartStopService("ServiceName") 'Can the current user start/stop the named service? .CascadeWindows 'Arrange app windows .EjectPC 'Eject PC from a docking station .Explore(FolderPath) 'Open a folder .FileRun 'Open the File-run dialogue .GetSystemInformation("PhysicalMemoryInstalled") 'Physical memory installed, in bytes. .IsServiceRunning("ServiceName") 'Check if a Windows service is running .MinimizeAll 'Minimize everything .NameSpace("C:\\") 'Create an object reference to a folder .ServiceStart("ServiceName", true) 'Start a windows service .ServiceStop("ServiceName", true) 'Stop a windows service .SetTime 'Open the set time GUI .ShellExecute 'Run a script or application .ShutdownWindows .TileHorizontally 'Tile app windows .TileVertically 'Tile app windows .ToggleDesktop 'Show/Hide Desktop .TrayProperties 'Display the Taskbar/Start Menu Properties .UndoMinimizeAll 'Un-Minimize everything Example Dim objShell Set objShell = WScript.CreateObject("WScript.Shell") objShell.Run "C:\Demo" Set objShell = Nothing Dim objShell Set objShell = WScript.CreateObject("WScript.Shell") objShell.Run "https://www.youtube.com/watch?v=nIpPSh4h_AA"

    An A-Z Index of Windows VBScript commands

    Abs(number) Absolute (positive) value of number .AppActivate Activate running command .Application BrowseForFolder/Open Array(el1,el2,el3) Add values to an Array variable Arguments Command line arguments Asc(String) Return ASCII code for string AscB(String) Return the byte code for a character AscW(String) Return Unicode code for string b Beep - see StdOut.Write .BrowseForFolder Prompt the user to select a folder c Call subroutine (arguments) or subroutine arguments CBool(expression) Convert expression to Boolean (True/False) • CByte(expression) Convert expression to Byte (0-255) • CCur(expression) Convert expression to Currency (numeric) • CDate(expression) Convert expression to Date • CDbl(expression) Convert expression to Double (up to 1.79x10308) • Chr(ChrCode) Return the string character for ChrCode (ASCII code) ChrB(ChrCode) Return the string character for ChrCode (Byte code) ChrW(ChrCode) Return the string character for ChrCode (Unicode/DBCS) CInt(expression) Convert expression to Integer • CLng(expression) Convert expression to long • CSng(expression) Convert expression to single • CStr(expression) Convert expression to a string • .CreateObject Create an automation object / run an external command .CreateShortcut Create Shortcut cscript Run a VBScript .vbs file .CurrentDirectory Retrieve or change the current directory d Date() The current system date DateAdd Add a time interval to a Date DateDiff Return the time interval between two dates DatePart Return part of a given date DateSerial Return a Date from a numeric Year, Month and Day DateValue Return a Date from a string expression Day(date) Return the day component of date (1-31) Dim Declare a new variable or array variable Do..Loop Repeat a block of statements Drives Drive Map .MapNetworkDrive - .Enum - .Remove e .Echo Echo text to screen, also StdOut.Write /.Popup End End a procedure or code block Environment Variables - Expand - .Delete/Remove Escape(String) Return only ASCII characters from a Unicode string. Eval(expr) Evaluate an expression .Exec Run a command Execute Execute one or more statements Exp(n) Return e (base of natural logs) raised to a power n. Exit Exit a block of code immediately f FileSystemObject Work with Drives, Folders and Files Filter Produce an array by filtering an existing array Fix(number) Return the integer portion of a number For...Next Repeat a block of statements a given number of times For Each... Loop through the items in a collection or array FormatCurrency Format a number with a currency symbol FormatNumber Format a number FormatPercent Format a number with a % symbol FormatDateTime Format a Date/Time value Function Define a function procedure g GetLocale() Return the Regional LocaleID .GetObject Get an Automation object h Hex(number) Return the hex value of number Hour(time) Return the hour component of time i If..Then Conditionally execute a block of statements InputBox Prompt for user input InStr Find one string within another InStrRev Find one string within another, starting from the end Int(number) Return the integer portion of a number IsArray(varname) Is varname an array? IsDate(expression) Is expression a DateTime? IsEmpty(expression) Is expression initialised? IsNull(expression) Is expression NULL? IsNumeric(expression) Is expression a Numeric? IsObject(expression) Is expression an object? Join Combine the contents of an array into a single variable. l LBound Return the smallest subscript for an array. LCase(String) Return String in lower case Left(String,len) Return the leftmost len characters of string LeftB(String,len) Return the leftmost len bytes of string Len(String) Return length of string in characters LenB(String) Return length of string in Bytes Log(number) Return natural log of number .LogEvent Log an item in the Event log LTrim(String) Remove any leading spaces from a string expression m .MapNetworkDrive Drive Map Mid Return a mid-section from a string Minute(time) Return the minute component of time Month(date) Return the month component of date MonthName Convert a month number to a descriptive Month MsgBox Display a dialogue box message n .Network Access network resources Now Return the current Date and Time o On Error Error handling Option Explicit Force all variables to be defined p .AddPrinterConn / .AddWindowsPrConn Add Printer connection .EnumPrinterConnections List Printer connections .SetDefaultPrinter Set default printer .RemovePrinterConnection Remove printer connection Private VarName Declare a local variable/array variable Public VarName Declare a public variable/array variable q .Quit Quit r Randomize(number) Initialise the random number generator .ReadLine Accept user text input ReDim Resize a dynamic array RegExp Regular expression search object .RegDelete Registry, delete .RegRead Registry, read .RegWrite Registry, write REM Add a Comment Replace Find and replace text RGB(Red,Green,Blue) Return a system color code Right(String,len) Return the rightmost len characters of string RightB(String,len) Return the rightmost len bytes of string Rnd Return a random number Round Round a number to n decimal places RTrim(String) Remove any trailing spaces from a string expression .Run a command s Second(time) Return the second component of time Select...Case Conditionally execute a block of statements .SendKeys Set variable = object Assign an object reference SetLocale(LocaleID) Set the Regional LocaleID Sgn(number) The sign of a number .Shell + Shell.Application objects/methods .ShellExecute Run a script/application in the Windows Shell Shortcut create .CreateShortcut .Sleep Space Return a string consisting of spaces. .SpecialFolders Path to Desktop,Start menu, Programs... Split Parse a string of delimited values into an array Sqr(number) Square root StdOut.Read Obtain User Input from the command prompt StdOut.Write Echo text to the screen, also beep. StrComp Compare two strings String Create a string with a single character repeated StrReverse Reverse a string Sub Declare a sub procedure t Time() The current system time Timer() The number of seconds since midnight TimeSerial Construct a Time value from Hours, Minutes and seconds TimeValue Convert a string to a Time value Trim(String) Remove leading and trailing spaces from string TypeName Return variable type (variant subtype). u UBound Return the largest subscript for an array dimension UCase(String) Uppercase String UnEscape(Str) Return Unicode characters from an escaped ASCII string w Weekday Return the day of the week (1-7) WeekdayName Return the named day of the week While...Wend Conditionally repeat a block of statements With Assign multiple properties of an object Year(date) Return the year component of date (1-12) ' Remark Add a Comment Syntax and Examples How-to

    vbs close chrome tab

    try keyboard actions. example: Browser("...").Type micCtrlDwn+micF4+micCtrlUp. For Each w In CreateObject("Shell.Application").Windows If InStr(1, w.LocationURL, "google", 1) Then _ w.Quit() Next 'w

    to stop a vb script running in windows

    2 different ways: using Task Manager (Ctrl-Shift-Esc), end process name cscript.exe or wscript.exe From the command line taskkill /fi "imagename eq cscript.exe" (change to wscript.exe as needed) taskkill /F /IM wscript.exe /T Another way is using scripting and WMI. Here are some hints: look for the Win32_Process class and the Terminate method. However, scripts that perpetually focus program windows using .AppActivate may make it very difficult to get to the task manager -i.e you and the script will be fighting for control. Hence i recommend writing a script (which i call self destruct for obvious reasons) and make a keyboard shortcut key to activate the script. Self destruct script: Option Explicit Dim WshShell Set WshShell = WScript.CreateObject("WScript.Shell") WshShell.Run "taskkill /f /im Cscript.exe", , True WshShell.Run "taskkill /f /im wscript.exe", , True Keyboard shortcut: rightclick on the script icon, select create shortcut, rightclick on script shortcut icon, select properties, click in shortcutkey and make your own. type your shortcut key and all scripts end. Cheers

    VBScript Main Index

    VBScript statement apostrophe sign: ' VBScript operator minus sign: - VBScript operator ampersand sign: & VBScript operator greater than: > VBScript operator greater than or equal: >= VBScript operator less than: < VBScript operator inequality: <> VBScript operator less than or equal: <= VBScript operator multiplication: * VBScript operator division: / VBScript operator rounding division: \ VBScript operator hat: ^ VBScript operator plus sign: + VBScript operator assignment: = VBScript function abs: Abs Add VBScript dictionary add: Dictionary VBScript folders collection add: Folders Collection VBScript operator and: And VBScript function array: Array VBScript function asc: Asc VBScript textstream atendofline: AtEndOfLine VBScript textstream atendofstream: AtEndOfStream VBScript function atn: Atn Attributes VBScript file attributes: File VBScript folder attributes: Folder VBScript drive available space: AvailableSpace VBScript file system object buildpath: BuildPath VBScript call statement: Call VBScript function cbool: CBool VBScript function cbyte: CByte VBScript function ccur: CCur VBScript function CDate: CDate VBScript function CDbl: CDbl VBScript function Chr: Chr VBScript function chrb: ChrB VBScript function chrw: ChrW VBScript function CInt: CInt VBScript statement class: Class VBScript err clear method: Clear VBScript function CLng: CLng VBScript textstream close: Close VBScript constant COLOR: COLOR VBScript textstream column: Column VBScript dictionary compare mode: CompareMode VBScript constant comparison: COMPARISON VBScript statement const: Const Copy VBScript file copy method: File VBScript folder copy method: Folder VBScript file system object copyfile: CopyFile VBScript file system object copyfolder: CopyFolder VBScript function Cos: Cos Count VBScript dictionary count property: Dictionary VBScript drives collection count property: Drives Collection VBScript files collection count property: Files Collection VBScript folders collection count property: Folders Collection VBScript matches collection count property: Matches Collection VBScript file system object createfolder: CreateFolder VBScript file system object createfolder: CreateFolder CreateTextFile VBScript file system object create textfile: FileSystemObject VBScript folder create textfile method: Folder VBScript function CSng: CSng VBScript function CStr: CStr VBScript function date: Date VBScript constant dateandtime: Date And Time VBScript function DateAdd: DateAdd DateCreated VBScript file datecreated property: File VBScript folder datecreated property: Folder VBScript function DateDiff: DateDiff VBScript constant dateformat: DateFormat DateLastAccessed VBScript file date last accessed property: File VBScript folder date last accessed: Folder DateLastModified VBScript file-date last modified: File VBScript folder date last modified: Folder VBScript function DatePart: DatePart VBScript function DateSerial: DateSerial VBScript function DateValue: DateValue VBScript function Day: Day Delete VBScript file delete method: File VBScript folder delete method: Folder VBScript file system object deletefile: DeleteFile VBScript file system object deletefolder: DeleteFolder VBScript err description property: Description VBScript object dictionary: Dictionary VBScript statement dim: Dim VBScript statement do: Do Drive VBScript object drive: File VBScript file drive: Folder VBScript file system object driveexists: DriveExists VBScript drive driveletter: DriveLetter VBScript file system object drives: Drives VBScript object drives collection: Drives Collection VBScript drive drivetype: DriveType VBScript operator eqv: Eqv VBScript statement erase: Erase VBScript object err: Err VBScript function Eval: Eval VBScript statement execute: Execute VBScript statement executeglobal: ExecuteGlobal VBScript dictionary exists method: Exists VBScript statement exit: Exit VBScript function Exp: Exp VBScript object file: File VBScript constant FILEATTRIBUTE: FILE ATTRIBUTE VBScript constant fileinputoutput: File Input/Output VBScript file system object fileexists: FileExists VBScript folder files: Files VBScript object filescollection: Files Collection VBScript drive file system: FileSystem VBScript file system object: FileSystemObject VBScript function Filter: Filter VBScript match first index: FirstIndex VBScript function Fix: Fix VBScript object folder: Folder VBScript file system object folderexists: FolderExists VBScript object folderscollection: Folders Collection VBScript statement for: For VBScript statement foreach: ForEach VBScript function format currency: FormatCurrency VBScript function Format Date Time: FormatDateTime VBScript function Format Number: FormatNumber VBScript function Format Percent: FormatPercent VBScript drive freespace: FreeSpace VBScript statement function: Function VBScript file system object getabsolutepathname: GetAbsolutePathName VBScript file system object getbasename: GetBaseName VBScript file system object getdrive: GetDrive VBScript file system object getdrivename: GetDriveName VBScript file system object getextensionname: GetExtensionName VBScript file system object getfile: GetFile VBScript file system object getfilename: GetFileName VBScript file system object getfileversion: GetFileVersion VBScript file system object getfolder: GetFolder VBScript function GetLocale: GetLocale VBScript function GetObject: GetObject VBScript file system object- getparentfoldername: GetParentFolderName VBScript function GetRef: GetRef VBScript file system object getspecialfolder: GetSpecialFolder VBScript file system object gettempname: GetTempName VBScript regexp global: Global VBScript err helpcontext: HelpContext VBScript err helpfile: HelpFile VBScript function Hex: Hex VBScript function hour: Hour VBScript statements if: If VBScript regexp ignorecase: IgnoreCase VBScript operator imp: Imp VBScript event initialize: Initialize VBScript function inputbox: InputBox VBScript function instr: InStr VBScript function instrrev: InStrRev VBScript function int: Int VBScript operator is: Is VBScript function isarray: IsArray VBScript function isdate: IsDate VBScript function isempty: IsEmpty VBScript function isnull: IsNull VBScript function isnumeric: IsNumeric VBScript function isobject: IsObject VBScript drive isready: IsReady VBScript folder isrootfolder: IsRootFolder Item VBScript dictionary item property: Dictionary VBScript drivescollection item property: Drives Collection VBScript files collection item property: Files Collection VBScript folders collection item property: Folders Collection VBScript matches collection item property: Matches Collection VBScript dictionary items: Items VBScript function join: Join VBScript dictionary key: Key VBScript dictionary keys: Keys VBScript function lbound: LBound VBScript function lcase: LCase VBScript function left: Left VBScript function len: Len VBScript match length: Length VBScript textstream line: Line VBScript function loadpicture: LoadPicture VBScript function log: Log VBScript function ltrim: LTrim VBScript object match: Match VBScript object matches collection: Matches Collection VBScript function mid: Mid VBScript function minute: Minute VBScript operator mod: Mod VBScript function month: Month VBScript function monthname: MonthName Move VBScript file move: File VBScript folder move: Folder VBScript file system object movefile: MoveFile VBScript file system object movefolder: MoveFolder VBScript function msgbox: MsgBox Name VBScript file name: File VBScript folder name: Folder VBScript operator not: Not VBScript function now: Now VBScript err number: Number VBScript function oct: Oct VBScript statement onerror: OnError VBScript file openastextstream: OpenAsTextStream VBScript file system object opentextfile: OpenTextFile VBScript statement optionexplicit: Option Explicit VBScript operator or: Or ParentFolder VBScript file parent folder: File VBScript folder parent folder: Folder Path VBScript drive path: Drive VBScript file path: File VBScript folder path: Folder VBScript regexp pattern: Pattern VBScript statement private: Private VBScript statement propertyget: PropertyGet VBScript statement propertylet: PropertyLet VBScript statement propertyset: PropertySet VBScript statement public: Public VBScript err raise: Raise VBScript statement randomize: Randomize VBScript textstream read: Read VBScript textstream readall: ReadAll VBScript textstream readline: ReadLine VBScript statement redim: ReDim VBScript object regexp: RegExp VBScript statement rem: Rem VBScript dictionary remove: Remove VBScript dictionary removeall: RemoveAll VBScript function replace: Replace VBScript function RGB: RGB VBScript function right: Right VBScript function rnd: Rnd VBScript drive roofolder: RootFolder VBScript function round: Round VBScript function rtrim: RTrim VBScript function scriptengine: ScriptEngine VBScript function scriptenginebuildversion: ScriptEngineBuildVersion VBScript function scriptenginemajorversion: ScriptEngineMajorVersion VBScript function scriptengineminorversion: ScriptEngineMinorVersion VBScript function second: Second VBScript statement selectcase: SelectCase VBScript drive serialnumber: SerialNumber VBScript statement set: Set VBScript function setlocale: SetLocale VBScript function sgn: Sgn VBScript drive sharename: ShareName ShortName VBScript file short name: File VBScript folder short name: Folder ShortPath VBScript file short path: File VBScript folder short path: Folder VBScript function sin: Sin Size VBScript file size: File VBScript folder size: Folder VBScript textstream skip: Skip VBScript textstream skipline: SkipLine VBScript err source: Source VBScript function space: Space VBScript function split: Split VBScript function sqr: Sqr VBScript function strcomp: StrComp VBScript function string: String VBScript function strreverse: StrReverse VBScript statement sub: Sub VBScript folder subfolders: SubFolders VBScript function tan: Tan VBScript event terminate: Terminate VBScript regexp test: Test VBScript object textstream: TextStream VBScript function time: Time VBScript function timer: Timer VBScript function timeserial: TimeSerial VBScript function timevalue: TimeValue VBScript drive totalsize: TotalSize VBScript function trim: Trim VBScript constant tristate: Tristate Type VBScript file type: File VBScript folder type: Folder VBScript function typename: TypeName VBScript function ubound: UBound VBScript function ucase: UCase VBScript match value: Value VBScript function vartype: VarType VBScript constant vbobjecterror: VBObjectError VBScript drive volumename: VolumeName VBScript function weekday: Weekday VBScript function weekdayname: WeekdayName VBScript statement while: While VBScript statement with endwith: With...End With VBScript textstream write: Write VBScript textstream writeblanklines: WriteBlankLines VBScript textstream writeline: WriteLine VBScript operator xor: Xor VBScript function year: Year

    run js from vb

    wscript.exe C:\Scripts\helloworld.js

    VBScript Variable

    Variables can also be used for holding expressions. Suppose you have stored the marks of a student in English and Mathematics using the variables markE and markM. You want to find the total marks. Then, you can use a variable named markT and set its value to markE + markM. In other words, markT = markE + markM. Here, markT is a variable which holds an expression.

    Declaring Variables

    Declaring variables is the same as creating variables because you are instructing the computer to reserve memory space. You can name the variable the way you want. It can be short names like x, y or z or more self-describing names like student, Name, salary etc. Providing clear and meaningful names to variables is considered a good programming practice. There are certain rules for VBScript variable names. Variable name must begin with a letter. Examples: salary, mark etc. Variables beginning with numbers or special characters are not allowed. Examples: 1stSchool, 3rdCar, _name etc. Variable name cannot exceed 255 characters. Variable name should not contain a period (.). For declaring variables, you need to use the keyword Dim. Suppose you plan to use a variable named “salary” in your VBScript program, syntax Dim salary; Just declaring the VBS variables will not help you, use it. You will have to assign a value to it at some point or another and this process is known as initializing the variable. If you are planning to declare a variably named salary, then you can code like this: Dim salary salary = 10000 The important thing you need to make sure is that you should not assign a value to the variable as and when you declare it. Suppose you write a statement like this: Dim salary = 10000 If you try to output salary using document.write, it will not return any output. Code Example Step 1) Open your text editor and add the following lines of code. <html> <head> <title>Variables</title> </head> <body> <script type="text/vbscript"> Dim variable1 variable1="John" document.write(variable1) ‘Dim variable2 = "Smith" ‘document.write(variable2) </script> </body> </html> Step 2) Save this file as variable.html in your preferred location and then open this in IE (following the steps specified in the previous chapter). Now, you will see the value John on the browser. Step 3) Next, uncomment line # 11 & 12 Again save the file and refresh the IE browser if it is already opened or open the file in the IE browser. You might be wondered to see nothing; neither John nor Smith. The problem here is that you tried to assign the value to the variable while declaring it which is not allowed.

    Loose Binding

    VBScript provides you the freedom to use variables without declaring it (called loose binding). For example, without having the statement Dim student, you can assign a value to the variable student like – student = "John" But, it is not at all a good programming practice. If you use a variable without declaring it and misspell the same variable when you use it again, VBScript will not prompt you of the error. So to make the code easier to read and to identify the errors, you should use the Option Explicit statement at the beginning of your code so that you will be forced to declare all your variables even if you forget to do so. To avoid variable type related issues, it is always good to specify the statement Option Explicit at the beginning of your VBScript code. Code Example: Step 1) Open your text editor and add the following lines of code. <html> <body> <script type="text/vbscript"> Option Explicit ‘Dim markE, markM, markT markE=90 markM=86 markT=markE+markM document.write("Your marks in English is " & markE & "." & "<br />") document.write("Your marks in Mathematics is " & markM & "." & "<br />") document.write("Your total marks is " & markT & ".") </script> </body> </html> Step 2) Save the file as variables.html in your preferred location. Now open the file in Internet Explorer and your screen is blank. Why ? because you have used option explicit but not declared variables before using them Step 3) Now to understand the importance of Option Explicit statement, uncomment Line 5 in the above code Step 4) Save the variables.html file and refresh your browser. Now, your output will be like this: Note - To concatenate two strings, you need to use “&”. In above example, its used inside document.write command. It is obvious that the calculation of total marks is wrong. Now just add the first statement Option Explicit at the beginning of VBScript code (without the Dim statement). Save the file and see the output. You will get nothing as output which indicates that your code has some error. Here the error is you have not declared variables before using it even after specifying Option Explicit statement. You can also declare variables using public and private keywords like a public student or private student. But, you have to be more careful while using these two keywords for declaring variables because it will change the scope of your variables. You can also store multiple values in a single variable and such variables are known as VBScript array variables. Suppose, you want to store details like name, marks, address etc of 30 students. It will be really difficult to create and manage sets of 30 variables for names, marks, addresses and so on. Instead, you can declare a single variable named students and store the names of all 30 students in this variable. In such case, you will declare the variable as Dim students(29) (array index starts from zero) and you will assign values as students(0) = "John" students(1) = "Hannah" students(2) = "Kevin" ....... ....... students(28) = "Rose" students(29) = "Emma" Similarly, you can create variables like marks, address etc to store the respective values of all 30 students. You can also create multidimensional arrays having up to 60 dimensions. Code Example: Open your text editor and add the following lines of code. <html> <body> <script type="text/vbscript"> Option Explicit Dim students(19), marks(19) students(0) = "John" marks(0) = 95 students(1) = "Emma" marks(1) = "83" students(2) = "Kevin" marks(2) = 87 document.write(students(0) & " has scored " & marks(0) & ".<br />") document.write(students(1) & " has scored " & marks(1) & ".<br />") document.write(students(2) & " has scored " & marks(2) & ".<br />") </script> </body> </html> Here, we have stored details of only three students. You can add details of up to 20 students as we have set the size of the array as 20 (as index starts from 0).

    VBScript Data Types

    In the previous section, you might have noticed that we assigned different types of data to the variables.We have stored numbers (mark and salary), strings (name) etc in different variables. These numbers, strings etc are known as data types. In fact, VBScript has only one data type called Variant. A variant is a special kind of data type which can hold different kinds of information. If you use Variant in a numeric context, it behaves like a number and when you use it in a string context, it behaves as a string. In other words, when you specify salary=10000, VBScript assumes that salary is a numeric data type. A Variant makes specific distinctions about the nature of the data. For example, you can use variant type to store Boolean values, currency, date and so on. These different categories of information that can be contained in a Variant are called subtypes. Though most of the time, Variant behaves in such a way that is most appropriate for the data it contains, you should be aware of different subtypes. Following is the list of VBScript Data Types. Empty: A special subtype to represent a variable that has not been assigned with any value yet. Null: A special subtype to represent a variable assigned with a null value. Integer: Using 2 bytes to express signed integer in the range -32,768 to 32,767. Long: Using 4 bytes to express signed integers ranging from -2,147,483,648 to 2,147,483,647. Single: Using 4 bytes to express real numbers in floating-point format ranging from -3.402823e38 to -1.401298e-45 for negative values, and from 1.401298e-45 to 3.402823e38 for positive value. Double: Using 8 bytes to express real numbers in floating-point format ranging from -1.79769313486232e308 to -4.94065645841247e-324 for negative values, and from 4.94065645841247e-324 to 1.79769313486232e308 for positive values. Currency: Using 8 bytes to express real numbers in decimal format ranging from -922,337,293,685,477.5808 to 922,337,293,685,477.5807. Date: Using 8 bytes to express dates ranging from January 1, 100 to December 31, 9999. String: Using 1 byte per character to express a sequence of characters that can be up to approximately 2 billion characters. Object: A special subtype to represent a reference to an object. Error: A special subtype to represent an error number. Boolean: Using 2 bytes to contain either True or False. Byte: Using 1 byte to express integer in the range 0 to 255. There are two built-in VBScript functions that help you know the subtype of a variable: “varType()” and “typeName()”. The var type returns the numeric representation and typeName() returns the text representation of the subtype of the variable. Each subtype has a predefined numeric representation. Code Example Open your text editor and add the following lines of code. <html> <head> <script type="text/vbscript"> Option Explicit Dim a a = Empty document.write("a = " & a & "<br />") document.write("The numeric representation of a is " & VarType(a) & "<br />") document.write("The variable a is of " & TypeName(a) & " data type." & "<br /><br />") Dim b b = Null document.write("b = " & b & "<br />") document.write("The numeric representation of b is " & VarType(b) & "<br />") document.write("The variable b is of " & TypeName(b) & " data type." & "<br /><br />") Dim c c = 4 document.write("c = " & c & "<br />") document.write("The numeric representation of c is " & VarType(c) & "<br />") document.write("The variable c is of " & TypeName(c) & " data type." & "<br /><br />") Dim d d = -2100483648 document.write("d = " & d & "<br />") document.write("The numeric representation of d is " & VarType(d) & "<br />") document.write("The variable d is of " & TypeName(d) & " data type." & "<br /><br />") Dim e e = -3.402823E38 document.write("e = " & e & "<br />") document.write("The numeric representation of e is " & VarType(e) & "<br />") document.write("The variable e is of " & TypeName(e) & " data type." & "<br /><br />") Dim f f = "John" document.write("f = " & f & "<br />") document.write("The numeric representation of f is " & VarType(f) & "<br />") document.write("The variable f is of " & TypeName(f) & " data type." & "<br /><br />") Dim g g = True document.write("g = " & g & "<br />") document.write("The numeric representation of g is " & VarType(g) & "<br />") document.write("The variable g is of " & TypeName(g) & " data type." & "<br /><br />") </script> </head> <body> </body> </html> Save the file as subtype.html and open it in IE. Your output will look like this: Declaring and Using VBScript Variables NOTE: You can also declare variables using public and private keywords like public student or private student. But, you have to be more careful while using these two keywords for declaring variables because it will change the scope of your variables.

    Summary

    Variables are used to hold value or an expression while programming. Variables are to be declared and initialized separately. Though you can use variables without declaring, declaring variables before using them is considered as a good programming practice. A variant is the only data type of VBScript and variant has different subtypes including String, Boolean, Integer, Currency etc.

    Troubleshooting

    In case you see a blank page after you run the code, do the following Press F12 to open developer tools In left toolbar scroll down until you see "Emulation" settings page Change Document Mode from a default ("Edge") to 10 Add the following code to the head <meta http-equiv="x-ua-compatible" content="IE=10">

    VBScript special characters

    VBScript has two built-in functions —Escape and Unescape— that replace special characters to make them URL-safe. VBScript's Help file doesn't document the Escape and Unescape functions. However, if you use an object browser such as Microsoft OLEView to view VBScript's vbscript.dll file, you can see that these functions are implemented. The Escape function assesses a string argument one character at a time. When the function encounters a special character (i.e., a character other than a letter or number or one of the characters * + - . / @ or _), it replaces the character with a percent sign (%) and the replaced character's hexadecimal number. For example, the line-feed character is ASCII character code 10; 10 in hex notation is 0A— so, Escape replaces a line-feed character embedded in a string with For a demonstration, run the following code in a VBScript file: WScript.Echo Unescape("%40") You usually can't display characters such as the carriage return and line feed, but Escape lets you at least display their representation. For example, the following code shows the Escape codes for carriage return and line-feed characters: WScript.Echo Escape(VbCrLf) Although Escape and Unescape were designed to work with Internet URLs, I use these functions for debugging scripts that use unusual characters. For example, a few months ago I was testing a script that read the output of the Windows shell Ipconfig command. The Escape function showed me that the command inserted some special formatting characters that caused problems with extracting information.

    VBScript - Working With Strings

    vbscript strings This topic contains information about handling strings in VBScript and provides examples of operations that deal with strings. It contains the following sections:

    Basics

    A String is a sequence of symbols or digits. Strings are among the most frequently used data types. Like any other data type, strings in TestComplete are represented as OLE-compatible variants. In VBScript, a sequence of literal characters, enclosed in double quotes ("), is recognized as a string. Single quotation marks (') are allowed within a string. To insert a double quotation mark into a string, it should be duplicated. The following is an example of string: str1 = "The brig was heading to Liverpool, when the captain noticed a ship." str2 = "'Ahoy! Is there anyone?' - the captain cried." str3 = """Nobody."" - was the answer." To deal with strings, TestComplete has a special aqString scripting object. The object is available for all supported scripting languages, so that you can use it to operate with string values regardless of the chosen language.
    Method, Property Description
    aqString.AddListItemAdds a new item to a string list.
    aqString.ChangeListItemChanges the value of the string list item with the given index.
    aqString.CompareCompares two specified strings.
    aqString.ConcatConcatenates two specified strings.
    aqString.DeleteListItemRemoves an item with the given index from a string list.
    aqString.FindSearches for a substring within the given string. Use this method instead of the obsolete aqString.Contains.
    aqString.FormatGenerates a formatted string.
    aqString.GetCharRetrieves a single character from the input string.
    aqString.GetLengthReturns the number of characters in a string.
    aqString.GetListItemReturns an individual item from the list passed through the input string.
    aqString.GetListLengthReturns the number of items in the string list.
    aqString.InsertInserts one string to another at the specified position.
    aqString.ListSeparatorSpecifies a character used to separate individual values in a list.
    aqString.QuoteEncloses the specified string in quotes.
    aqString.QuoteSymbolSpecifies a symbol used as a quotation mark.
    aqString.RemoveRemoves a number of characters from the input string.
    aqString.ReplaceReplaces all the occurrences of one substring with another substring.
    aqString.SubStringRetrieves a substring from the input string.
    aqString.ToLowerConverts the specified string to lower case.
    aqString.ToUpperConverts the specified string to upper case.
    aqString.TrimRemoves spaces and control characters from the specified string.
    aqString.UnquoteConverts a quoted string to an unquoted string.
    Another scripting object that is useful for string manipulation is aqConvert. This object has several methods that convert values of different types to a string representation and vice versa.
    Method Description
    aqConvert.CurrencyToFormatStrConverts a currency value to a string using the specified format settings.
    aqConvert.CurrencyToStrConverts a currency value to a string.
    aqConvert.DateTimeToFormatStrConverts the given date value to a string using the specified format.
    aqConvert.DateTimeToStrConverts the given date value to a string.
    aqConvert.FloatToStrConverts a floating-point value to a string.
    aqConvert.IntToStrConverts the given number into a string.
    aqConvert.StrToCurrencyConverts the specified string to a currency value.
    aqConvert.StrToDateConverts the specified string to a date value.
    aqConvert.StrToDateTimeConverts the specified string to a date/time value.
    aqConvert.StrToFloatConverts the specified string to a floating-point value.
    aqConvert.StrToIntConverts the specified string to an integer value.
    aqConvert.StrToInt64Converts the specified string to a long integer value.
    aqConvert.StrToTimeConverts the specified string to a time value.
    aqConvert.VarToStrConverts the specified variant value to a string.
    Furthermore, you can use native VBScript functions that operate with strings. A detailed description of VBScript functions can be found in the Functions (VBScript) article of the MSDN library. The table below only lists major functions:
    Function Description
    Asc(string)Returns the ASCII character code corresponding to the first letter in a string.
    Chr(charcode)Returns the character associated with the specified ANSI character code.
    CStr(expression)Returns an expression that has been converted to a variant of sub-type string.
    Escape(charString)Encodes a string so it only contains ASCII characters. Non-ASCII characters are replaced with %xx encoding, where xx is equivalent to the hexadecimal number representing the character.
    InStr([startpos, ]string1, string2[, compare])Returns the position of the first occurrence for one string within another.The search can start at a given position and use binary (compare=0) or text (compare=1) comparisons.
    InStrRev(string1, string2[, start[, compare]])Returns the position of an occurrence for one string within another, from the end of string. The search can start at a given position and use binary (compare=0) or text (compare=1) comparisons.
    Join(list[, delimiter])Returns a string created by joining a number of substrings contained in an array.
    LCase(string)Returns a string that has been converted to lowercase.
    Left(string, length)Returns a specified number of characters from the left side of a string.
    Len(string | varname)Returns the number of characters in a string or the number of bytes required to store a variable.
    LTrim(string)Returns a copy of a string without leading spaces.
    Mid(string, start[, length])Returns a specified number of characters from a string.
    Replace(string, findstr, replacewith[, start[, count[, compare]]])Returns a string in which a specified substring has been replaced with another substring a specified number of times.
    Right(string, length)Returns a specified number of characters from the right side of a string.
    RTrim(string)Returns a copy of a string without trailing spaces.
    Space(number)Returns a string consisting of the specified number of spaces.
    Split(expression[, delimiter[, count[, compare]]])Returns a zero-based, one-dimensional array containing a specified number of substrings.
    StrComp(string1, string2[, compare])Returns a value indicating the result of a string comparison.
    String(number, character)Returns a repeating character string of the length specified.
    StrReverse(string)Returns a string in which the character order of a specified string is reversed.
    Trim(string)Returns a copy of a string without leading and trailing spaces.
    UCase(string)Returns a string that has been converted to uppercase.
    Unescape(charString)Decodes a string encoded with the Escape function.

    Special characters

    In VBScript you can emulate any character by using the Chr function with the appropriate ASCII code. This also applies to special characters that are used to format string values. Alternatively, you can emulate control characters using native string constants. The table below lists the most frequently used special characters and their constants.
    Description Character sequence
    Carriage return.Chr(13) -- or -- vbCr
    Line feed. On Unix platforms it is interpreted as new line.Chr(10) -- or -- vbLf
    A combination of carriage return and line feed. On Windows platforms it is interpreted as new line.Chr(13)+Chr(10) -- or -- VbCrLf
    New line. Either a line feed character or a combination of carriage return and line feed.vbNewLine
    Form feed.Chr(12) -- or -- vbFormFeed
    Horizontal tab.Chr(9) -- or -- vbTab
    Vertical tab.Chr(11) -- or -- vbVerticalTab
    Special characters obtained by a function or constant should be joined to the string by concatenation: Str1 = "A string." & Chr(13) & Chr(10) & "Another string." Str2 = "A string." & vbNewLine & "Another string."

    Getting the string length

    To obtain the total number of characters in a string, you can call either the aqString.GetLength method, or the Len function of VBScript. The character position in VBScript is not zero-based, so the maximum position number in a string equals the string length. The following code demonstrates both ways of obtaining the string length: Sub StringLengthDemo Dim aString aString="Some text" Log.Message("The string is " & aqString.GetLength(aString) & " character(s) long.") Log.Message("The string is " & Len(aString) & " character(s) long.") End Sub
    Using TestComplete, you can limit the length of string parameters returned by functions of the tested application. For this purpose, use the Maximum string length of [out] parameters project property. If the length of the string returned from the application via one of its out parameters exceeds the property’s value, TestComplete treats the returned string as a null one.

    Concatenating strings

    The operation that forms a string out of several others is called concatenation. The aqString object has special method aqString.Concat that perform this operation. In VBScript the concatenation is performed both by plus (+) and by ampersand (&) operators. The plus operator is intended to perform addition, but if both operators are strings, then string concatenation occurs. However it is more convenient to use the ampersand operator since it does not require a preliminary conversion to a string type. This sample code shows how to make a string out of several substrings: Sub ConcatenationDemo Dim Str1 Str1 = "String No 1 " Log.Message(aqString.Concat(Str1, "String No 2")) Log.Message(Str1 + "String No 2 " + "String No " + aqConvert.IntToStr(3)) Log.Message(Str1 & "String No 2 " & "String No " & 3) End Sub

    Comparing strings

    String comparison is widely used during testing. Generally, a test procedure obtains textual data (user input, file contents, property values and so on) and then compares it with the expected data. That is why both TestComplete and VBScript have their own methods to compare one string value with another. These methods are: aqString.Compare and StrComp. The aqString.Compare method has three parameters: two of them, String 1 and String2, specify the strings to be compared; the third parameter (CaseSensitive) defines whether the comparison should be case-sensitive or not. Similarly, VBScript's StrComp function has two mandatory parameters, Str1 and Str2, that define the compared strings, and one optional parameter, CompType, that specifies the comparison type. The CompType parameter can accept the following values: vbBinaryCompare (or 0), and vbTextCompare (or 1). vbBinaryCompare means binary case-sensitive comparison. vbTextCompare means case-insensitive comparison. The default type is vbBinaryCompare. The function result is -1 if Str1 is less than Str2, 1 if Str1 is greater than Str2 and they equal 0 if the strings are the same. Both methods can compare strings holding specific national symbols, for example characters with diacritical marks ( , , and others). The code below demonstrates how to use both methods: ' This helper function obtains the integer comparison result from the ' StrComp routine and returns a textual interpretation of the result. Function GetComparisonStr(IntegerComparisonResult) If IntegerComparisonResult = 0 Then GetComparisonStr = CStr(IntegerComparisonResult) & ". The strings are the same." Else GetComparisonStr = CStr(IntegerComparisonResult) & ". The strings are different." End If End Function Sub StringComparison ' Use the method of the aqString object Log.Message("aqString.Compare(""Abra"", ""abra"", False): " & aqString.Compare("Abra", "abra", False)) Log.Message("aqString.Compare(""Abra"", ""abra"", True): "& aqString.Compare("Abra", "abra", True)) ' Use the native routine of VBScript Log.Message("StrComp(""abra"", ""ABRA"", vbBinaryCompare): " & GetComparisonStr(StrComp("abra", "ABRA", vbBinaryCompare))) Log.Message("StrComp(""abra"", ""ABRA"", vbTextCompare): " & GetComparisonStr(StrComp("abra", "ABRA", vbTextCompare))) ' Working with native-language characters ' The following code assumes that the French layout is installed on the computer ' 040C is the identifier of the French layout If IsLanguageSupported(&H040C) And SetKeyboardLayout(Sys.Process("TestComplete").Id, "0000040c") Then Log.Message("aqString.Compare(""français"", ""Français"", False): " & aqString.Compare("français","Français", True)) Log.Message("aqString.Compare(""français"", ""Français"", True): " & aqString.Compare("français","Français", False)) Log.Message("aqString.Compare(""français"", ""francais"", True): " & aqString.Compare("français","francais", False)) Log.Message("StrComp(""français"", ""Français"", vbBinaryCompare): " & GetComparisonStr(StrComp("français", "Français", vbBinaryCompare))) Log.Message("StrComp(""français"", ""Français"", vbTextCompare): " & GetComparisonStr(StrComp("français", "Français", vbTextCompare))) Log.Message("StrComp(""français"", ""francais"", vbTextCompare): " & GetComparisonStr(StrComp("français", "francais", vbTextCompare))) End If End Sub

    Accessing individual character of a string

    The VBScript scripting language has no data type that can be used to store single symbols. However, this is not a problem, since the string type can hold both a series of characters and individual characters. Moreover, you can extract a single character from a string using the aqString.GetChar method and VBScript’s Mid function. The latter retrieves the given number of characters starting from the specified position. Note however that the VBScript function uses 1-based indexes, whereas the GetChar method uses zero-based indexes. The sample routine below demonstrates how to use both of these routines. It posts text to TestComplete log in two different ways: as a whole string and by a single letter. Sub StringByLetter Dim aString, i aString = "Per aspera ad astra" Log.Message("The string is : " & aString) Log.Message("And now this text letter by letter using aqString.GetChar:") For i = 0 To aqString.GetLength(aString)-1 Log.Message(aqString.GetChar(aString, i)) Next Log.Message("And now this text letter by letter using Mid function:") For i = 1 To Len(aString) Log.Message(Mid(aString, i, 1)) Next End Sub

    Searching for characters and substrings

    One of the most common tasks that one has to perform when working with string values is determining whether specific text is part of a string. To perform such tasks, the aqString object has the Find method. If the specified substring was found, the method returns the number of the first occurrence of the substring within the source string. If the specified substring was not found, the method returns -1: Sub StringOccurrenceDemo Dim aString, aSubString, Res aString = "Per aspera ad astra" aSubString = "astra" Res = aqString.Find(aString, aSubString) If Res <> -1 Then Log.Message("A substring '" & aSubString & "' was found in string '" & aString & "' at position " & Res) Else Log.Message("There are no occurrences of '" & aSubString & "' in '" & aString & "'") End If End Sub You can also get the position where the specified substring occurs using the VBScript functions InStr and InStrRev. They both return the initial position (from 1) of the first substring match, but the first one searches from left to right, while the other from right to left. If the substring was found, the functions return the initial position of the first substring match. If no occurrences were found, they return 0. The code below demonstrates how to use the InStr function: Sub TextPosDemo Dim aString, aSubString, findpos aString = "Per aspera ad astra" aSubString = "astra" findpos = InStr(aString, aSubString) If findpos <> 0 Then Log.Message("A substring '" & aSubString & "' was found at position " & findpos) Else Log.Message("There are no occurrences of '" & aSubString & "' in '" & aString & "'") End If End Sub

    Getting a substring

    VBScript has several methods that allow you to extract a substring out of a string. They are Left, Right and Mid. These methods vary in how the extracted substring is defined. Function Left returns a text fragment that starts at the beginning of the given string and has the specified length. Function Right does a similar action, but it gets the last fragment of the given string. If the fragment’s length is greater than the length of the whole string, then the entire string is returned. Negative length values are not allowed, zero-length returns an empty string. Function Mid returns a text fragment that starts at a given position and has a specified length. The length parameter is optional, and if it is omitted then the resulting substring continues up to the end of the source string. The aqString object also has a similar method, SubString that returns a substring that starts from the specified position and has the given length. However, this method requires all tree parameters, and position numbers are zero-based. The sample code below demonstrates how to use these functions: Sub GetStringDemo Dim Str Str = "123456789" Log.Message("Function 'Left' demo:") Log.Message(Left(Str, 3)) ' Posts "123" Log.Message(Left(Str, 20)) ' Posts "123456789" Log.Message(Left(Str, 0)) ' Posts "" Log.Message("Function 'Right' demo:") Log.Message(Right(Str, 3)) ' Posts "789" Log.Message(Right(Str, 20)) ' Posts "123456789" Log.Message(Right(Str, 0)) ' Posts "" Log.Message("Function 'Mid' demo:") Log.Message(Mid(Str, 4, 3)) ' Posts "456" Log.Message(Mid(Str, 5)) ' Posts "456789" Log.Message(Mid(Str, 4, 0)) ' Posts "" Log.Message("Method 'aqString.SubString' demo:") Log.Message(aqString.SubString(Str, 3, 3)) ' Posts "456" Log.Message(aqString.SubString(Str, 4, 20)) ' Posts "56789" Log.Message(aqString.SubString(Str, 2, 0)) ' Posts "" End Sub

    Splitting strings

    Sometimes it is required to make several strings out of a single string. This operation splits a string into substrings. It can be performed by VBScript's native function called Split. This routine searches the string for a delimiter character, separates the string and returns an array holding the constituent strings. If the delimiter is omitted, then the space character is assumed as a delimiter. Also you can constrain the maximum array length with the third parameter and set the comparison method with the forth. They are not obligatory and can be omitted. The same method can be used to split a string onto substrings, sentences and even separate words; it all depends on the specified delimiter. The first sample routine below uses a space character as a delimiter to extract words out of a string, and the second routine splits the string by line breaks: Sub SplitDemo Dim s, ss s = "Better late than never but better never late." ' Split at each space character. ss = Split(s) Log.Message("There are " & (UBound(ss)+1) & " words in the array") Log.Message("The first word is: " & ss(0)) End Sub Sub SplitDemo2 Dim s, ss s = "Better late than never " & Chr(13) & " but better never late." ' Split at line break character. ss = Split(s, Chr(13)) Log.Message("There are " & (UBound(ss)+1) & " words in the array") Log.Message("The first word is: " & ss(0)) End Sub TestComplete has a similar method called aqString.GetListItem. It extracts a substring with the specified index from the input string. It was designed to read items from a string list, see Working with string lists for more information. However, it allows you to redefine the delimiter characters and, like the Split method, it can be used to get sentences, single words and so on. Sub SplitDemo3 Dim s, prevSep s = "Better late than never but better never late." ' Assign list separator to space character prevSep = aqString.ListSeparator aqString.ListSeparator = " " ' Split by spaces Log.Message("There are " & aqString.GetListLength(s) & " words in a string") Log.Message("The first word is: " & aqString.GetListItem(s, 0)) ' Restore previous separator aqString.ListSeparator = prevSep End Sub

    Removing extra spaces from a string

    The aqString object has a special routine, aqString.Trim, that excludes leading and trailing spaces (or both) from a string. VBScript has also the LTrim, RTrim and Trim functions that exclude, leading, trailing and both leading and trailing spaces from the input string. Generally, all these methods are used to remove unnecessary spaces at the beginning or at the end of strings obtained from the user input. Sub TrimDemo Dim str str=" Hallo " Log.Message("'" & aqString.Trim(str, aqString.stLeading) & "'") 'Posts 'Hallo ' Log.Message("'" & aqString.Trim(str, aqString.stTrailing) & "'") 'Posts ' Hallo' Log.Message("'" & aqString.Trim(str, aqString.stAll) & "'") 'Posts 'Hallo' Log.Message("'" & LTrim(str) & "'") ' Posts 'Hallo ' Log.Message("'" & RTrim(str) & "'") ' Posts ' Hallo' Log.Message("'" & Trim(str) & "'") ' Posts 'Hallo' End Sub Another function that can be useful when handling user input strings is excluding extra inner spaces out of the string. This function seems to be similar to Trim, but the latter only removes spaces at the beginning or end of the string and does not affect the spaces inside the string. The general idea of the function is for the string to be parsed into separate words and then a new string is constructed. The new string consists of the same words but is separated with a single space between words. Function TrimInner(Str) Dim WordArray, i WordArray = Split(Str) Str = "" For i = 0 To UBound(WordArray) If WordArray(i) <> "" Then Str = Str & WordArray(i) & " " Next TrimInner = Trim(Str) End Function 'An example of how to use this function Sub TrimInnerDemo Log.Message(TrimInner("Follow the white rabbit")) End Sub

    Replacing characters and substrings

    Quite often we need to find and replace a character or substring within a string. There are two ways to do this: by using the aqString.Replace method or by using the Replace method of a RegExp object. The aqString object method is much easier to use. It can be used when you need to change a certain character or string. It allows you to set whether the search should be case-sensitive or not. Here is an example of how to use this method: Sub StringReplaceDemo Dim str str = "Hi, Bob. Have you seen Bob Robbinson?" str = aqString.Replace(str, "Bob", "Jack") Log.Message(str) End Sub The RegExp.Replace method is a little more complicated, but it offers more flexibility. You can not only change a definite character or string, but all fragments matching the specified regular expression pattern. However you have to create an instance of the RegExp object and set the pattern before replacing. The regular expression pattern is enclosed in double quotation marks ("). Additionally you can specify the following Boolean flags that affect the search procedure: RegExp.Global - performs a global search for all occurrences of a pattern, RegExp.IgnoreCase - searches regardless of the letter case and RegExp.MultiLine - performs a multi-line search. For a full description of how to use regular expressions, refer to the Introduction to Regular Expressions article in the MSDN library. The first sample demonstrates how to change a definite string using the replace method. Sub RegExReplaceDemo1 Dim str, re str = "Hi, Bob. Have you seen Bob Robbinson?" ' Create RegExp instance. Set re = New RegExp ' Define regular expression pattern re.Pattern = "Bob" ' Set global search flag re.Global = True ' Perform replace operation str = re.Replace(str, "Jack") Log.Message(str) End Sub The second example shows how to replace a substring with alternative parts. The patterns of alternative parts are separated by pipe characters (" | "). For instance in the sample below the "ht(ml|m)" pattern matches both html and htm: Sub RegExReplaceDemo2 Dim str, re str = "The html is widely used in Internet. The HTM file is a text file with tags." ' Create RegExp instance. Set re = New RegExp ' Define regular expression pattern. re.Pattern = "ht(ml|m)" ' Set global search flag re.Global = True ' Set ignore letter case flag re.IgnoreCase = True ' Perform replace operation str = re.Replace(str, "hypertext markup language") Log.Message(str) End Sub Furthermore, using regular expressions you can search for the text fragments that match the specified format. In the next sample, all dates written in the DD/MM/YYYY format are substituted with the Some Date string. This operation can be useful, for example, when comparing two reports that contain the generation date. Sub RegExReplaceDemo3 Dim str, re str = "Date of report: 30/04/2005." ' Create RegExp instance. Set re = New RegExp ' Define regular expression pattern. re.Pattern = "\d{1,2}.\d{1,2}.\d{2,4}" ' Set global search flag re.Global = True ' Perform replace operation str = re.Replace(str, "Some Date") Log.Message(str) End Sub

    Changing the letter case

    A string can contain both uppercase and lowercase letters. The TestComplete aqString object and the native String object have methods that convert uppercase letters to lowercase and vice versa. They are: aqString.ToLower, aqString.ToUpper, LCase and UCase. The code below demonstrates how all of these methods are applied. Sub LetterCaseDemo Dim str str = "The word 'Champagne' is of French origin" ' Converting to lower case Log.Message(aqString.ToLower(str)) Log.Message(LCase(str)) ' Converting to upper case Log.Message(aqString.ToUpper(str)) Log.Message(UCase(str)) End Sub

    Working with string lists

    Some scripting objects, generally, controls like ListBoxes, ComboBoxes and Memos, return information about their state or contents as string lists. Individual data elements (or items) in this list are separated by commas, line breaks, carriage returns or some other delimiter characters. The aqString object has a number of specific methods (AddListItem, ChangeListItem, DeleteListItem, GetListItem and GetListLength) that are used to work with such lists. AddListItem and DeleteListItem add an item to or remove if from the list respectively. The GetListItem method retrieves the item with the given index, and ChangeListItem assigns a new value to the given item. The GetListLength method returns the total number of items in the string list. The symbol that is used as the separator between list items is defined by the ListSeparator property. By default, the list separator is a pipe (|), but it can also be a comma, column, line break, carriage return, tabulation, and any other printable and non-printable character, or even several characters. Here is sample code that demonstrates how to work with the string lists returned by scripting objects. Sub ListDialogOptions Dim StrList, prevSep, i ' Get a string with dialog options OptStr = UserForms.UserForm1.SaveDialog1.Options ' Assign a comma as the list separator prevSep = aqString.ListSeparator aqString.ListSeparator = "," ' Get the number of dialog options Log.Message("The dialog has " & aqString.GetListLength(OptStr) & " option(s) enabled:") ' Iterate through the options list For i = 0 To aqString.GetListLength(OptStr)-1 ' Get an option and post it to the log Log.Message("Option No " & (i+1) & " is: " & aqString.GetListItem(OptStr, i)) Next ' Restore the previous separator aqString.ListSeparator = prevSep End Sub Sub ManageMemoText Dim StrList, prevSep ' Get a string with memo lines StrList = UserForms.UserForm1.cxMemo1.Lines.Text ' Post the memo contents to the log Log.Message(UserForms.UserForm1.cxMemo1.Lines.Text) ' Assign a newline character as the list separator prevSep = aqString.ListSeparator aqString.ListSeparator = vbNewLine ' Append one more line StrList = aqString.AddListItem(StrList, "Last Line") Log.Message(StrList) ' Change the value of the first line StrList = aqString.ChangeListItem(StrList, "New First Line", 0) ' Add the memo contents to a new list UserForms.UserForm1.cxMemo1.Lines.Text = StrList ' Post the memo contents to the log Log.Message(UserForms.UserForm1.cxMemo1.Lines.Text) ' Restore the previous separator aqString.ListSeparator = prevSep End Sub

    to dispaly an image

    Set objHtml = CreateObject("InternetExplorer.Application") With objHtml .Navigate "about:blank" .Visible = 1 .Toolbar=False .Statusbar=False .Top=440 .Left=1040 .Height=400 .Width=300 .Document.Body.InnerHTML = "" End With objHtml.navigate(surl) 'Navigate to the website 'Set the browser to fullscreen and theatermode objHtml.Fullscreen=true 'This makes the window not closable until the user exits the page using a script on the html 'page that has a window.close command or they use Alt-F4 'Setting the TheaterMode on and then off makes the object show properly. objHtml.TheaterMode=true objHtml.TheaterMode=false 'Turn off the status bar objHtml.statusbar=false 'Turn off the toolbar objHtml.toolbar=false 'Turn off Resizable objHtml.Resizable=false objHtml.document.focus() 'Set the browser to focus which brings it to the top. ' dont work objHtml.top =0 objHtml.Left=0 'Sets the window to the upper left hand corner

    vbs now function

    The now function returns the current date and time Now = 2/29/2016 1:02:03 PM Date = 2/29/2016 Time = 1:02:03 PM Timer = 78826.31 ' seconds since midnight FormatDateTime(Now) = 2/29/2016 1:02:03 PM FormatDateTime(Now, vbGeneralDate) = 2/29/2016 1:02:03 PM FormatDateTime(Now, vbLongDate) = Monday, February 29, 2016 FormatDateTime(Now, vbShortDate) = 2/29/2016 FormatDateTime(Now, vbLongTime) = 1:02:03 PM FormatDateTime(Now, vbShortTime) = 13:02 FormatDateTime(now, 4) = 08:12 Year(Now) = 2016 Month(Now) = 2 Day(Now) = 29 Hour(Now) = 13 Minute(Now) = 2 Second(Now) = 3 Year(Date) = 2016 Month(Date) = 2 Day(Date) = 29 Hour(Time) = 13 Minute(Time) = 2 Second(Time) = 3 Function LPad (str, pad, length) LPad = String(length - Len(str), pad) & str End Function LPad(Month(Date), "0", 2) = 02 LPad(Day(Date), "0", 2) = 29 LPad(Hour(Time), "0", 2) = 13 LPad(Minute(Time), "0", 2) = 02 LPad(Second(Time), "0", 2) = 03 Weekday(Now) = 2 WeekdayName(Weekday(Now), True) = Mon WeekdayName(Weekday(Now), False) = Monday WeekdayName(Weekday(Now)) = Monday MonthName(Month(Now), True) = Feb MonthName(Month(Now), False) = February MonthName(Month(Now)) = February Set os = GetObject("winmgmts:root\cimv2:Win32_OperatingSystem=@") os.LocalDateTime = 20131204215346.562000-300 Left(os.LocalDateTime, 4) = 2013 ' year Mid(os.LocalDateTime, 5, 2) = 12 ' month Mid(os.LocalDateTime, 7, 2) = 04 ' day Mid(os.LocalDateTime, 9, 2) = 21 ' hour Mid(os.LocalDateTime, 11, 2) = 53 ' minute Mid(os.LocalDateTime, 13, 2) = 46 ' second Dim wmi : Set wmi = GetObject("winmgmts:root\cimv2") Set timeZones = wmi.ExecQuery("SELECT Bias, Caption FROM Win32_TimeZone") For Each tz In timeZones tz.Bias = -300 tz.Caption = (UTC-05:00) Eastern Time (US & Canada) Next There are also separate Time() and Date() functions. Show time in form 24 hours Right("0" & hour(now),2) & ":" & Right("0" & minute(now),2) // 01:35 Right("0" & hour(now),2) //01 Right("0" & minute(now),2) //35 msgbox "month: " & Month(Now) & " day: " & Day(Now) // month: 8 day: 18

    vbs read text file

    Use the method OpenTextFile Set fso = CreateObject("Scripting.FileSystemObject") Set file = fso.OpenTextFile("testfile.txt", 1) content = file.ReadAll msgbox content or line by line with the method ReadLine: Set dict = CreateObject("Scripting.Dictionary") Set file = fso.OpenTextFile ("c:\test.txt", 1) row = 0 Do Until file.AtEndOfStream line = file.Readline dict.Add row, line row = row + 1 Loop file.Close 'Loop over it For Each line in dict.Items WScript.Echo line Next

    VBA Variant

    A VBA Variant is a VBA variable that has not been declared to have a specific data type. It can therefore hold any type of data that VBA variables are able to hold – be it text, numbers, dates, time or objects. Variants use more memory than variables in which the data type is specified, and therefore can slow down the execution of the program that you are running. If you have large procedures or complicated code, this speed can be extremely important in the efficient running of your program. So the rule of the thumb should be to always specify what data is going to be held in your variable by explicitly declaring them. Why would I use a variant then? There may be some occasions where you need to use a variant. When you declare your variables, you are restricted to what type of data is stored in the variable – so if you declare an integer, for example, the data that is stored in that variable has to be between -32768 to 32767. If the number that is going into that variable falls outside of that scope, your code will end up throwing an error. This would be particularly annoying if you were importing data into Excel from a database using VBA code for example – some of the data may need ‘cleaning’ – a number may perhaps have a rogue letter in it and therefore if imported as a number, would end up breaking the program at that point. Using a variant variable could solve this problem. Sub Test1() Dim ProductPrice As Currency Dim Qty As Double Dim TaxAmount as Currency Dim FinalAmount as Currency ProductPrice = "$5.00 " Qty = "10" TaxAmount = "$4.14" FinalAmount = "$54.14" Range("A1 ") = ProductPrice Range("B1 ") = Qty Range("C1 ") = TaxAmount Range("D1 ") = FinalAmount However, when you try to run this code, the following error appears. This is due to the dollar signs that are in the data – the Product Price, Tax Amount and Final Amount have been declared as numbers – yet the data being populated into those variables contains a $ – therefore turning the number into a string – hence an error will occur. However, if you amend your code… Sub Test2() Dim ProductPrice As Variant Dim Qty As Variant Dim TaxAmount as Variant Dim FinalAmount as Variant ProductPrice = "$5.00 " Qty = "10" TaxAmount = "$4.14" FinalAmount = "$54.14" Range("A1 ") = ProductPrice Range("B1 ") = Qty Range("C1 ") = TaxAmount Range("D1 ") = FinalAmount The correct information will then go into your Excel file: So even though you declared your variables as variants, Excel cleverly knew to bring them in as numbers. Things to remember and to watch out for Variant variables take more memory and slow down your program The Variant data type is automatically specified by the type of data it takes in – so in the four variables we created, three of them would have been string variables and one would have been a number variable. Variant variables take in any data – which might make your code more difficult to debug. In summary, if you know what data you are going to be storing in your variable, a good rule to follow is to always EXPLICITLY declare your variables ie as a string, integer, double or single for example. If you are worried about data being stored that it not of a specific type – then declare your variable IMPLICTLY using a VARIANT.

    vbs read file and split

    Set fso = CreateObject("Scripting.FileSystemObject") Set file = fso.OpenTextFile("testfile.txt", 1) content = file.ReadAll msgbox content outputObject = Split(content," ") MsgBox TypeName(outputObject) for each x in outputObject MsgBox x next # the output is not arrange line by line

    vbs read file, split into array and access element

    Set fso = CreateObject("Scripting.FileSystemObject") Set file = fso.OpenTextFile("testfile.txt", 1) Do Until file.AtEndOfStream outputObject = file.Readline MsgBox outputObject output = Split(outputObject," ") 'to access element in array MsgBox "the leading element is: " &output(0) MsgBox "the trailing element is: " &output(1) for each x in output MsgBox "each element is: " & x next Loop

    reading and writing lines to a file

    Set fso = CreateObject("Scripting.FileSystemObject") ' How to write file outFileName="c:\test\autorun.inf" Set outputFile = fso.CreateTextFile(outFileName,True) outputFile.Write "test string" & vbCrLf outputFile.Close 'How to read a file inputFileName = "c:\test\file" Set inputFile = objFS.OpenTextFile(inputFileName) Do Until inputFile.AtEndOfStream strLine = inputFile.ReadLine Wscript.Echo strLine Loop inputFile.Close 'to get file path without drive letter, assuming drive letters are c:, d:, etc strFile="c:\test\file" s = Split(strFile,":") WScript.Echo s(1)

    Accessing array

    https://www.tutorialspoint.com/vbscript/vbscript_arrays.htm https://www.tutorialspoint.com/vbscript/vbscript_object_oriented.htm to create an object: set variablename = CreateObject("objectname") Accessing the properties of an Object, use parentheses: variable = object.property("arguments", "in", "parens") Array Declaration 'Method 1 : Using Dim Dim arr1() 'Without Size 'Method 2 : Mentioning the Size Dim arr2(5) 'Declared with size of 5 'Method 3 : using 'Array' Parameter Dim arr3 arr3 = Array("apple","Orange","Grapes") arr(0) = "1" 'Number as String arr(1) = "VBScript" 'String arr(2) = 100 'Number arr(3) = 2.45 'Decimal Number arr(4) = #10/07/2013# 'Date arr(5) = #12.45 PM# 'Time Multi Dimension Arrays Dim arr(2,3) ' Which has 3 rows and 4 columns arr(0,0) = "Apple" arr(0,1) = "Orange" arr(0,2) = "Grapes" arr(0,3) = "pineapple" arr(1,0) = "cucumber" arr(1,1) = "beans" arr(1,2) = "carrot" arr(1,3) = "tomato" arr(2,0) = "potato" arr(2,1) = "sandwitch" arr(2,2) = "coffee" arr(2,3) = "nuts" Redim Statement used to declare dynamic-array variables and allocate or reallocate storage space. ReDim [Preserve] varname(subscripts) [, varname(subscripts)] Preserve − An Optional parameter used to preserve the data in an existing array when you change the size of the last dimension. varname − A Required parameter, which denotes Name of the variable, which should follow the standard variable naming conventions. subscripts − A Required parameter, which indicates the size of the array. Dim a() i = 0 redim a(5) a(0) = "XYZ" a(1) = 41.25 a(2) = 22 REDIM PRESERVE a(7) For i = 3 to 7 a(i) = i Next 'to Fetch the output For i = 0 to ubound(a) Msgbox a(i) Next Array Methods LBound A Function, which returns an integer that corresponds to the smallest subscript of the given arrays. UBound A Function, which returns an integer that corresponds to the Largest subscript of the given arrays. Split A Function, which returns an array that contains a specified number of values. Splitted based on a Delimiter. Join A Function, which returns a String that contains a specified number of substrings in an array. This is an exact opposite function of Split Method. Filter A Function, which returns a zero based array that contains a subset of a string array based on a specific filter criteria. IsArray A Function, which returns a boolean value that indicates whether or not the input variable is an array. Erase A Function, which recovers the allocated memory for the array variables.

    Run Command Line & Command From VBS

    The problem is on this line: oShell.run "cmd.exe /C copy "S:Claims\Sound.wav" "C:\WINDOWS\Media\Sound.wav" Your first quote next to "S:Claims" ends the string; you need to escape the quotes around your files with a second quote, like this: oShell.run "cmd.exe /C copy ""S:\Claims\Sound.wav"" ""C:\WINDOWS\Media\Sound.wav"" " Set oShell = CreateObject("WScript.Shell") oShell.run "cmd.exe /C copy ""S:Claims\Sound.wav"" ""C:\WINDOWS\Media\Sound.wav"" " Set oShell = CreateObject("WScript.Shell") oShell.run "cmd.exe /C C:\Users\william\Desktop\gravity.html"

    convert text files to Unicode from UTF8

    Unfortunately VBScript doesn't support this kind of conversion by itself. use an ADODB.Stream object: Set stream = CreateObject("ADODB.Stream") stream.Open stream.Type = 2 'text stream.Charset = "utf-8" stream.LoadFromFile "C:\input.txt" text = stream.ReadText stream.Close Set fso = CreateObject("Scripting.FileSystemObject") Set f = fso.OpenTextFile("C:\output.txt", 2, True, True) f.Write text f.Close Or a little more streamlined: Set fso = CreateObject("Scripting.FileSystemObject") Set stream = CreateObject("ADODB.Stream") stream.Open stream.Type = 2 'text stream.Charset = "utf-8" stream.LoadFromFile "C:\input.txt" fso.OpenTextFile("C:\output.txt", 2, True, True).Write stream.ReadText stream.Close If you want to replace the existing file you'll have to use the first version and use the same file for input and output. Use a loop like this to iterate over all files in a folder: Set fso = CreateObject("Scripting.FileSystemObject") Set stream = CreateObject("ADODB.Stream") For Each f In fso.GetFolder("C:\source\folder").Files stream.Open stream.Type = 2 'text stream.Charset = "utf-8" stream.LoadFromFile f.Path text = stream.ReadText stream.Close fso.OpenTextFile(f.Path, 2, True, True).Write text Next

    chinese inside VBScript

    someone said VBScript does not support double byte characters. Use PowerShell instead. but VBScript only understand ansi and Unicode. You cannot use UTF-8 or any other encoding. so to embed doubyte characters in vb script save or convert to unicode, ie utf-16 LE with bom

    ask for input

    + x = InputBox("the input message", "My Input Box title","default input text") msgbox x

    Xmlhttp Web Scrape

    https://officetricks.com/vbscript-extract-data-web-scrape-parse-html/ Xmlhttp Web Scrape https://stackoverflow.com/questions/12217761/vba-vbscripting-automated-web-scraping-looping-w-ie-logon To get website data to using vbscript (.vbs) file, we need to know 2 processes. First one is to extract HTML code from website & then parse required data from HTML elements or tags. To parse data from html, we can use the below commands on a htmlfile object. getElementById(“idname”) getElementsByClassName(“classname”) getElementsByTagName(“tagname – a,p,div,table,td,tr etc.,”) DOMobject.getAttribute(“attributename – title, href,class,id etc.,”) DOMobject.parentElement.NextSibling Objects Used: CreateObject(“MSXML2.XMLHTTP”) 'To sent xmlhttp request to webserver & get html code CreateObject(“htmlfile”) 'To parse data from html tags To parse data from html, we can use the below commands on a htmlfile object. getElementById(“idname”) getElementsByClassName(“classname”) getElementsByTagName(“tagname – a,p,div,table,td,tr etc.,”)DOMobject.getAttribute(“attributename – title, href,class,id etc.,”) DOMobject.parentElement.NextSibling There are plenty of functions like this to traverse through each tags or elements in a valid html file. Now, lets see a working example. To test this code, replace the URL with a valid website address. myURL = "http://URL.com" 'Create XMLHTTP Object & HTML File Set oXMLHttp = CreateObject("MSXML2.XMLHTTP") Set ohtmlFile = CreateObject("htmlfile") 'Send Request To Web Server oXMLHttp.Open "GET", myURL, False oXMLHttp.send 'If Return Status is Success If oXMLHttp.Status = 200 Then 'Get Web Data to HTML file Object ohtmlFile.Write oXMLHttp.responseText ohtmlFile.Close 'Parse HTML File Set oTable = ohtmlFile.getElementsByTagName("table") For Each oTab In oTable MsgBox oTab.Innertext Next End If 'Process Completed WScript.Quit To execute this code, copy paste this code to a text editor & save the file as “testing.vbs”. Then double click on this file, Windows OS will start to execute the commands one by one. Reference: To write the extracted data to a Text file, check this article on how to write to a external file using vbs code.To scrape data from Webpage using Excel VBA, refer this page.

    read chinese from file

    The FSO can read only ASCII text files. So the FSO cannot read Unicode files or to read binary file formats such as Microsoft Word or Microsoft Excel. To read Unicode files, use ADO like this: Dim objStream, strData Set objStream = CreateObject("ADODB.Stream") objStream.CharSet = "utf-8" objStream.Open objStream.LoadFromFile("textfile.txt") strData = objStream.ReadText() objStream.Close Set objStream = Nothing

    GetLocale and setlocale

    MsgBox getLocale() SetLocale(2052) 'set chinese locale MsgBox getLocale() Note: VBScript only understand ansi and Unicode. You cannot use UTF-8 or any other encoding. To hard code utf8 string, convert script file to unicode by notepad

    detect numeric value

    if IsNumeric(v) = False Then v = 0

    write file

    Set objFSO=CreateObject("Scripting.FileSystemObject") ' How to write file outFile="c:\test\autorun.inf" Set objFile = objFSO.CreateTextFile(outFile,True) objFile.Write "test string" & vbCrLf objFile.Close 'How to read a file strFile = "c:\test\file" Set objFile = objFS.OpenTextFile(strFile) Do Until objFile.AtEndOfStream strLine= objFile.ReadLine Wscript.Echo strLine Loop objFile.Close 'to get file path without drive letter, assuming drive letters are c:, d:, etc strFile="c:\test\file" s = Split(strFile,":") WScript.Echo s(1)

    convert vbs file into an executable

    VBScript to an exe There is no way to convert a VBScript (.vbs file) into an executable (.exe file) because VBScript is not a compiled language. Visual Basic 6 is extremely similar in syntax to VBScript, but does support compiling to native code into a native executable. Running the .exe file will require that the user has the VB 6 Run-time libraries installed, but they come built into most versions of Windows that are found now in the wild. Visual Basic .NET similar in syntax to VB 6 and VBScript. VB.NET programs will also compile to an .exe file, but they require the .NET Framework runtime to be installed on the user's computer. Fortunately, this has also become commonplace, and it can be easily redistributed if your users don't happen to have it. Vbsedit is a good application for VBscripter Use VBSedit to convert VBS code to .exe file. Also convert HTML, CSS and JavaScript into Application. download free version http://www.vbsedit.com/

    vbs Read & Write UTF-8 Files

    vbs Read & Write UTF-8 Files FUNCTION saveFile() ' fileContent will be saved outFile="alarmSchedule.txt" Set theFile = CreateObject("ADODB.Stream") theFile.CharSet = "utf-8" theFile.Open theFile.WriteText fileContent theFile.SaveToFile outFile, 2 end FUNCTION

    delete() method for vbScript arrays

    There is no delete() method for vbScript arrays. We write one: Sub delete(idx) ub = UBound(ar) - 1 idx = idx - 1 For i = idx To ub ar(i) = ar(i + 1) Next ReDim Preserve ar(ub) End Sub

    objShell.SendKeys command

    objShell.SendKeys command Automate IE With VBScript 'This is an infinite loop, only disposed of by exiting Wscript.exe or Cscript.exe Do While(true) Dim PageTitleToRefresh, IntervalinSeconds, x, objShell, Success 'Page Titles - NOT the page address - (google.com = NO) (Google = YES) 'Page Titles are normally stored at the top of the browser or in the tab name of the browser. PageTitleToRefresh = "Google" IntervalinSeconds = 10 x = IntervalinSeconds * 1000 Set objShell = WScript.CreateObject("WScript.Shell") Do Until Success = True Success = objShell.AppActivate(PageTitleToRefresh) Wscript.Sleep 1000 Loop wscript.echo "Activated, now refreshing" objShell.SendKeys "^r" Wscript.Sleep IntervalinSeconds Loop

    SendKeys

    WSH » wshshell » SendKeys WSH » wshshell » SendKeys WSH » wshshell » SendKeys Syntax: WshShell.SendKeys (strKeyString) The SendKeys method sends keystrokes to the active window. Similar to VB's SendKeys statement. The SendKeys method sends one or more keystrokes to the active window as if they were typed at the keyboard. This method is similar to VB's SendKeys method. Each ordinary key can be represented by the character of the key itself. For example, the key sequence ABCD can be represented simply by "ABCD". Some special keys, such as the control keys, function keys, '{', '}', '[', ']', etc... are encoded in a string enclosed by braces ({}). The following table shows the list of special characters and their respective encoding for SendKeys.
    KeyCode
    {{{}
    }{}}
    [{[}
    ]{]}
    ~{~}
    +{+}
    ^{^}
    %{%}
    BACKSPACE{BACKSPACE}, {BS}, or {BKSP}
    BREAK{BREAK}
    CAPS LOCK{CAPSLOCK}
    DEL or DELETE{DELETE} or {DEL}
    DOWN ARROW{DOWN}
    END{END}
    ENTER{ENTER} or ~
    ESC{ESC}
    HELP{HELP}
    HOME{HOME}
    INS or INSERT{INSERT} or {INS}
    LEFT ARROW{LEFT}
    NUM LOCK{NUMLOCK}
    PAGE DOWN{PGDN}
    PAGE UP{PGUP}
    PRINT SCREEN{PRTSC}
    RIGHT ARROW{RIGHT}
    SCROLL LOCK{SCROLLLOCK}
    TAB{TAB}
    UP ARROW{UP}
    F1{F1}
    F2{F2}
    F3{F3}
    F4{F4}
    F5{F5}
    F6{F6}
    F7{F7}
    F8{F8}
    F9{F9}
    F10{F10}
    F11{F11}
    F12{F12}
    F13{F13}
    F14{F14}
    F15{F15}
    F16{F16}
    To specify keys combined with any combination of the SHIFT, CTRL, and ALT keys, precede the key code with one or more of the following codes:
    KeyCode
    +SHIFT
    ^CTRL
    %ALT
    For example, the following strKeyString produces the CTRL-ALT-DELETE keystroke combination: "^%{DELETE}"

    Examples

    Code:
    Set WshShell = WScript.CreateObject("WScript.Shell") WshShell.Run "notepad", 9 WScript.Sleep 500 ' Give Notepad some time to load For i = 1 To 10 WshShell.SendKeys "Hello World!" WshShell.SendKeys "{ENTER}" Next
    Explanation:
    This VBScript code creates an instance of Notepad and types the words "Hello World!" ten times into Notepad.
    Language(s): VBScript

    checks Chrome browser is closed

    This piece of code checks every few minutes to open it if the Chrome browser is closed. But the problem is that I want to check a specific profile, not the whole Chrome browser. And I do not know what the code is. Set objShell = CreateObject("WScript.Shell") i = 1 strProfile = objShell.ExpandEnvironmentStrings("%LOCALAPPDATA%") strPath = strProfile & "\Google\Chrome\Application\chrome.exe" Set objWMIService = GetObject("winmgmts:{impersonationLevel=impersonate}!\\" & "." & "\root\cimv2") Do While i = 1 booChrome = False Set colProcesses = objWMIService.ExecQuery _ ("Select * From Win32_Process") For Each objItem in colProcesses strProcessName = objItem.Caption 'msgbox strProcessName If strProcessName = "chrome.exe" Then booChrome = True end if Next If booChrome = False Then objShell.Run(Chr(34) & strPath & Chr(34)) WScript.Sleep 300000 Loop

    The WshShell object

    wshshell The WshShell object makes it easy to creates shortcuts, access the environment variables, run applications, access system registry, and more. Methods AppActivate Syntax: WshShell.AppActivate (strTitle) The AppActivate method activates an application. CreateShortcut Syntax: WshShell.CreateShortcut (strPathName) The CreateShortcut method creates and returns a WshShortcut object. ExpandEnvironmentStrings Syntax: WshShell.ExpandEnvironmentStrings (strString) The ExpandEnvironmentStrings method expands the environment variables in a string and returns the resulting string. LogEvent Syntax: WshShell.LogEvent (intType, strMessage [,strTarget]) The LogEvent method logs an event in the Windows NT event log or WSH.log file. Popup Syntax: WshShell.Popup [,intSecondsToWait] [,strTitle] [,intType] The Popup method displays a pop-up message box. some of the values that can be used for intType. Value Button 0 OK 1 OK, Cancel 2 Abort, Ignore, Retry 3 Yes, No, Cancel 4 Yes, No 5 Retry, Cancel 16 Critical 32 Question 48 Exclamation 64 Information RegDelete Syntax: WshShell.RegDelete (strName) The RegDelete method removes a registry entry based on strName. RegRead Syntax: WshShell.RegRead (strName) The RegRead method reads and returns a registry entry based on strName. RegWrite Syntax: WshShell.RegWrite (strName, varValue [,strType]) The RegWrite method writes a new entry into the registry. Run Syntax: WshShell.Run (strCommand [,intWindowStyle] [,bWaitOnReturn]) The Run method runs an application in a new process. SendKeys Syntax: WshShell.SendKeys (strKeyString) The SendKeys method sends keystrokes to the active window. Similar to VB's SendKeys statement. VBScript guides and examples

    Run a VBScript file

    To run a VBScript from within another VBScript: Dim objShell Set objShell = WScript.CreateObject("WScript.Shell") objShell.Run "cscript c:\batch\demo.vbs" Run a CMD batch file To run a CMD batch file from VBScript: Dim objShell Set objShell = WScript.CreateObject("WScript.Shell") objShell.Run "c:\batch\test.cmd" Run a PowerShell script To run a PowerShell script from VBScript: Dim objShell Set objShell = WScript.CreateObject("WScript.Shell") objShell.Run "powershell -file ""c:\batch\demo.ps1""" Hybrid Batch and VBscript, to run both a batch file and a VBScript

    get Quotient & Remainder

    Quotient = 5 \ 3. Notice we use integer division, \ vs /. This results in a value of 1 Remainder = 5 - (Quotient * 3). This results in a value of 2

    sort arrays using vbscript

    for a = UBound(ArrayOfTerms) - 1 To 0 Step -1 for j = 0 to a if ArrayOfTerms(j) > ArrayOfTerms(j+1) then temp = ArrayOfTerms(j+1) ArrayOfTerms(j+1) = ArrayOfTerms(j) ArrayOfTerms(j) = temp end if next next

    convert string to datetime format classic

    https://www.w3schools.com/asp/func_datediff.asp adate=CDate("May 6, 2020") response.write(d) 4/22/2010 d=CDate("3:18:40 AM") MsgBox IsDate(d) https://www.w3schools.com/asp/func_formatdatetime.asp FormatDateTime(date,format) d=CDate("2019-05-31 13:45") response.write(FormatDateTime(d) & "
    ") Format contains following constants: 0 = vbGeneralDate - Default. Returns date: mm/dd/yy and time if specified: hh:mm:ss PM/AM. 1 = vbLongDate - Returns date: weekday, monthname, year 2 = vbShortDate - Returns date: mm/dd/yy 3 = vbLongTime - Returns time: hh:mm:ss PM/AM 4 = vbShortTime - Return time: hh:mm https://www.vbsedit.com/html/fe4e5302-9602-4e0f-8496-559c7f58c8fa.asp Syntax DateDiff(interval,date1,date2[,firstdayofweek[,firstweekofyear]]) Parameter Description interval Required. The interval you want to use to calculate the differences between date1 and date2 Can take the following values: yyyy - Year q - Quarter m - Month y - Day of year d - Day w - Weekday ww - Week of year h - Hour n - Minute s - Second date1,date2 Required. Date expressions. Two dates you want to use in the calculation firstdayofweek Optional. Specifies the day of the week. Can take the following values: 0 = vbUseSystemDayOfWeek - Use National Language Support (NLS) API setting 1 = vbSunday - Sunday (default) 2 = vbMonday - Monday 3 = vbTuesday - Tuesday 4 = vbWednesday - Wednesday 5 = vbThursday - Thursday 6 = vbFriday - Friday 7 = vbSaturday - Saturday firstweekofyear Optional. Specifies the first week of the year. Can take the following values: 0 = vbUseSystem - Use National Language Support (NLS) API setting 1 = vbFirstJan1 - Start with the week in which January 1 occurs (default) 2 = vbFirstFourDays - Start with the week that has at least four days in the new year 3 = vbFirstFullWeek - Start with the first full week of the new year Example How many weeks (start on Monday), between December 31 2009 and December 31 2012: fromDate=CDate("2009/12/31") toDate=CDate("2012/12/31") DateDiff("w",fromDate,toDate,vbMonday) The difference between January 31 2009, and January 31 2010: fromDate="31-Jan-09 00:00:00" toDate="31-Jan-10 23:59:00" DateDiff("yyyy",fromDate,toDate) DateDiff("q",fromDate,toDate) DateDiff("m",fromDate,toDate) DateDiff("y",fromDate,toDate) DateDiff("d",fromDate,toDate) DateDiff("w",fromDate,toDate) DateDiff("ww",fromDate,toDate) DateDiff("h",fromDate,toDate) DateDiff("n",fromDate,toDate) DateDiff("s",fromDate,toDate) VBS get the Date & Time FormatDateTime(now, 4) 08:12 Format(Now(),"HH:mm:ss") There are also separate Time() and Date() functions. Here's various date and time information you can pull in vbscript running under Windows Script Host (WSH): Now = 2/29/2016 1:02:03 PM Date = 2/29/2016 Time = 1:02:03 PM Timer = 78826.31 ' seconds since midnight FormatDateTime(Now) = 2/29/2016 1:02:03 PM FormatDateTime(Now, vbGeneralDate) = 2/29/2016 1:02:03 PM FormatDateTime(Now, vbLongDate) = Monday, February 29, 2016 FormatDateTime(Now, vbShortDate) = 2/29/2016 FormatDateTime(Now, vbLongTime) = 1:02:03 PM FormatDateTime(Now, vbShortTime) = 13:02 Year(Now) = 2016 Month(Now) = 2 Day(Now) = 29 Hour(Now) = 13 Minute(Now) = 2 Second(Now) = 3 Year(Date) = 2016 Month(Date) = 2 Day(Date) = 29 Hour(Time) = 13 Minute(Time) = 2 Second(Time) = 3 ' Usage: > cscript.exe /nologo datetime.vbs Dim wmi : Set wmi = GetObject("winmgmts:root\cimv2") Dim n : n = #2/29/2016 1:02:03 PM# Dim d : d = #2/29/2016# Dim t : t = #1:02:03 PM# WScript.Echo "Now = " & n WScript.Echo "Date = " & d WScript.Echo "Time = " & t WScript.Echo "Timer = " & Timer & " ' seconds since midnight" WScript.Echo ' http://msdn.microsoft.com/en-us/library/office/gg251489.aspx 'Const vbGeneralDate = 0 'Const vbLongDate = 1 'Const vbShortDate = 2 'Const vbLongTime = 3 'Const vbShortTime = 4 WScript.Echo "FormatDateTime(Now) = " & FormatDateTime(n) WScript.Echo "FormatDateTime(Now, vbGeneralDate) = " & FormatDateTime(n, vbGeneralDate) WScript.Echo "FormatDateTime(Now, vbLongDate) = " & FormatDateTime(n, vbLongDate) WScript.Echo "FormatDateTime(Now, vbShortDate) = " & FormatDateTime(n, vbShortDate) WScript.Echo "FormatDateTime(Now, vbLongTime) = " & FormatDateTime(n, vbLongTime) WScript.Echo "FormatDateTime(Now, vbShortTime) = " & FormatDateTime(n, vbShortTime) WScript.Echo WScript.Echo "Year(Now) = " & Year(n) WScript.Echo "Month(Now) = " & Month(n) WScript.Echo "Day(Now) = " & Day(n) WScript.Echo "Hour(Now) = " & Hour(n) WScript.Echo "Minute(Now) = " & Minute(n) WScript.Echo "Second(Now) = " & Second(n) WScript.Echo WScript.Echo "Year(Date) = " & Year(d) WScript.Echo "Month(Date) = " & Month(d) WScript.Echo "Day(Date) = " & Day(d) WScript.Echo WScript.Echo "Hour(Time) = " & Hour(t) WScript.Echo "Minute(Time) = " & Minute(t) WScript.Echo "Second(Time) = " & Second(t) WScript.Echo Function LPad (str, pad, length) ' http://www.vbforums.com/showthread.php?676463-Right-Pad-and-Left-Pad-in-VBScript LPad = String(length - Len(str), pad) & str End Function WScript.Echo "Function LPad (str, pad, length)" WScript.Echo " LPad = String(length - Len(str), pad) & str" WScript.Echo "End Function" WScript.Echo WScript.Echo "LPad(Month(Date), ""0"", 2) = " & LPad(Month(d), "0", 2) WScript.Echo "LPad(Day(Date), ""0"", 2) = " & LPad(Day(d), "0", 2) WScript.Echo "LPad(Hour(Time), ""0"", 2) = " & LPad(Hour(t), "0", 2) WScript.Echo "LPad(Minute(Time), ""0"", 2) = " & LPad(Minute(t), "0", 2) WScript.Echo "LPad(Second(Time), ""0"", 2) = " & LPad(Second(t), "0", 2) WScript.Echo WScript.Echo "Weekday(Now) = " & Weekday(n) WScript.Echo "WeekdayName(Weekday(Now), True) = " & WeekdayName(Weekday(n), True) WScript.Echo "WeekdayName(Weekday(Now), False) = " & WeekdayName(Weekday(n), False) WScript.Echo "WeekdayName(Weekday(Now)) = " & WeekdayName(Weekday(n)) WScript.Echo WScript.Echo "MonthName(Month(Now), True) = " & MonthName(Month(n), True) WScript.Echo "MonthName(Month(Now), False) = " & MonthName(Month(n), False) WScript.Echo "MonthName(Month(Now)) = " & MonthName(Month(n)) WScript.Echo ' http://msdn.microsoft.com/en-us/library/aa394239%28v=vs.85%29.aspx ' http://include.wutils.com/wmi/ROOT%5Ccimv2/CIM_ManagedSystemElement/CIM_LogicalElement/CIM_OperatingSystem/Win32_OperatingSystem.html WScript.Echo "Set os = GetObject(""winmgmts:root\cimv2:Win32_OperatingSystem=@"")" Dim os : Set os = GetObject("winmgmts:root\cimv2:Win32_OperatingSystem=@") WScript.Echo "os.LocalDateTime = " & os.LocalDateTime WScript.Echo "Left(os.LocalDateTime, 4) = " & Left(os.LocalDateTime, 4) & " ' year" WScript.Echo "Mid(os.LocalDateTime, 5, 2) = " & Mid(os.LocalDateTime, 5, 2) & " ' month" WScript.Echo "Mid(os.LocalDateTime, 7, 2) = " & Mid(os.LocalDateTime, 7, 2) & " ' day" WScript.Echo "Mid(os.LocalDateTime, 9, 2) = " & Mid(os.LocalDateTime, 9, 2) & " ' hour" WScript.Echo "Mid(os.LocalDateTime, 11, 2) = " & Mid(os.LocalDateTime, 11, 2) & " ' minute" WScript.Echo "Mid(os.LocalDateTime, 13, 2) = " & Mid(os.LocalDateTime, 13, 2) & " ' second" WScript.Echo ' http://msdn.microsoft.com/en-us/library/aa394498.aspx ' http://include.wutils.com/wmi/ROOT%5Ccimv2/CIM_Setting/Win32_TimeZone.html#vbscript WScript.Echo "Set timeZones = wmi.ExecQuery(""SELECT Bias, Caption FROM Win32_TimeZone"")" Dim timeZones: Set timeZones = wmi.ExecQuery("SELECT Bias, Caption FROM Win32_TimeZone") WScript.Echo "For Each tz In timeZones" For Each tz In timeZones WScript.Echo " tz.Bias = " & tz.Bias WScript.Echo " tz.Caption = " & tz.Caption Next

    To return a value from a VBScript function

    assign the value to the name of the function, like this: Function getNumber getNumber = "423" End Function A function can only return one value. In the function definition you assign the value to function name. You can use "Exit Function" statements to make the function return with different values at different points. For example: Function Example(strValue) If (strValue = "A") Then Example = 1 Exit Function End If If (strValue = "B") Then Example = 2 Exit Function End If Example = 3 End Function

    Vb script restarts another vbs script

    use Exec method to run another VB Script, but you are likely to get a console window flash. Dim WshShell Set WshShell = WScript.CreateObject("WScript.Shell") WshShell.Exec("CMD /C Test_To_Block.vbs") A-Z Index of Windows VBScript commands Dim WshShell, oExec Set WshShell = CreateObject("WScript.Shell") Set oExec = WshShell.Exec("Test_To_Block.vbs") Do If NOT WshShell.Status = 1 then WScript.Exec("Test_To_Block.vbs") End If WScript.Sleep(100) Loop Here is a VBScript that uses WMI to start and stop a service. 'Start Service strServiceName = "Alerter" Set objWMIService = GetObject("winmgmts:{impersonationLevel=impersonate}!\\.\root\cimv2") Set colListOfServices = objWMIService.ExecQuery ("Select * from Win32_Service Where Name ='" & strServiceName & "'") For Each objService in colListOfServices objService.StartService() Next 'Stop Service strServiceName = "Alerter" Set objWMIService = GetObject("winmgmts:{impersonationLevel=impersonate}!\\.\root\cimv2") Set colListOfServices = objWMIService.ExecQuery("Select * from Win32_Service Where Name ='" & strServiceName & "'") For Each objService in colListOfServices objService.StopService() Next

    : the colon just a statement separator

    the code would work exactly the same on two lines Dim g_oSB : Set g_oSB = CreateObject("System.Text.StringBuilder")

    CreateDate

    Description: Creates date and time from its individual components. var tDate = Pm.CreateDate(2018, 3, 22, 12, 30, 30, 500); // Returns date 22.3.2018 12:30:30.500 (43181.5211863426)

    vbs Do While Loop

    If you do not know the number of times you need to execute a block of code, then you will be using Do While loops. Dim x x=1 Do While x<5 document.write("Welcome.") x=x+1 Loop Do While loop Dim x x=7 Do document.write("Welcome.") x=x+1 Loop While x<5 Do Until Loop ‘Do Until’ loop is also used when you do not know the number of time you need to execute a block of code. Dim x x=1 Do Until x=5 document.write("Welcome.") x=x+1 Loop to exit a Do While or Do Until loop in between, then you can use Exit Do statement. Dim x x=1 Do Until x=5 If x=3 Then Exit Do document.write("Welcome.") x=x+1 Loop While Loop While…Wend loop is similar to Do While loop though not used commonly. As Do While is more structured than While…..Wend loop, programmers usually use Do While statements. Dim x x = 1 While x < 5 document.write("Welcome.") x=x+1 Wend For-Next Loop The For-Next loop can be used to execute a block of code for a specific number of times. For i = 1 To 5 document.write("The number is " & i & " ") Next For-Step-Next Loop By default, the counter variable is incremented by one. If you want to increase or decrease the counter variable by the value you specify, then you can use For….Step….Next loop. For i = 1 To 5 Step 2 document.write("The number is " & i & "
    ") Next to exit a For Next or For Step Next loop in between, then you can use Exit for the statement. For i = 1 To 5 Step 2 If i=3 Then Exit For document.write("The number is " & i & "
    ") Next For-Each-Next Loop If you want to repeat a block of code for each item in a collection or for each element of a VBS array Dim students(4) students(0)="John" students(1)="Hanah" students(2)="Sarah" students(3)="Kevin" students(4)="Emma" For Each x In students document.write(x & "
    ") Next

    for each loop

    'fruits is an array fruits = Array("apple","orange","cherries") Dim fruitnames 'iterating using For each loop. For each item in fruits fruitnames = fruitnames & item & vbnewline Next msgbox fruitnames

    list battery details

    ' List Battery Information On Error Resume Next strComputer = "." Set objWMIService = GetObject("winmgmts:" & "{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2") Set colItems = objWMIService.ExecQuery("Select * from Win32_Battery") report = "" For Each objItem in colItems report = report & "Availability: " & objItem.Availability & vbcrlf report = report & "Battery Status: " & objItem.BatteryStatus & vbcrlf report = report & "Chemistry: " & objItem.Chemistry & vbcrlf report = report & "Description: " & objItem.Description & vbcrlf report = report & "Design Voltage: " & objItem.DesignVoltage & vbcrlf report = report & "Device ID: " & objItem.DeviceID & vbcrlf report = report & "Estimated Run Time: " & objItem.EstimatedRunTime & vbcrlf report = report & "Name: " & objItem.Name & vbcrlf report = report & "Power Management Capabilities: " & vbcrlf For Each objElement In objItem.PowerManagementCapabilities report = report & vbTab & objElement & vbcrlf Next report = report & "Power Management Supported: " & objItem.PowerManagementSupported & vbcrlf Next msgbox report

    vbs Do While Loop

    If you do not know the number of times you need to execute a block of code, then you will be using Do While loops. Dim x x=1 Do While x<5 document.write("Welcome.") x=x+1 Loop Do While loop Dim x x=7 Do document.write("Welcome.") x=x+1 Loop While x<5 Do Until Loop ‘Do Until’ loop is also used when you do not know the number of time you need to execute a block of code. Dim x x=1 Do Until x=5 document.write("Welcome.") x=x+1 Loop to exit a Do While or Do Until loop in between, then you can use Exit Do statement. Dim x x=1 Do Until x=5 If x=3 Then Exit Do document.write("Welcome.") x=x+1 Loop While Loop While…Wend loop is similar to Do While loop though not used commonly. As Do While is more structured than While…..Wend loop, programmers usually use Do While statements. Dim x x = 1 While x < 5 document.write("Welcome.") x=x+1 Wend For-Next Loop The For-Next loop can be used to execute a block of code for a specific number of times. For i = 1 To 5 document.write("The number is " & i & " ") Next For-Step-Next Loop By default, the counter variable is incremented by one. If you want to increase or decrease the counter variable by the value you specify, then you can use For….Step….Next loop. For i = 1 To 5 Step 2 document.write("The number is " & i & "
    ") Next to exit a For Next or For Step Next loop in between, then you can use Exit for the statement. For i = 1 To 5 Step 2 If i=3 Then Exit For document.write("The number is " & i & "
    ") Next For-Each-Next Loop If you want to repeat a block of code for each item in a collection or for each element of a VBS array Dim students(4) students(0)="John" students(1)="Hanah" students(2)="Sarah" students(3)="Kevin" students(4)="Emma" For Each x In students document.write(x & "
    ") Next

    for each loop

    'fruits is an array fruits = Array("apple","orange","cherries") Dim fruitnames 'iterating using For each loop. For each item in fruits fruitnames = fruitnames & item & vbnewline Next msgbox fruitnames

    list battery details

    ' List Battery Information On Error Resume Next strComputer = "." Set objWMIService = GetObject("winmgmts:" & "{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2") Set colItems = objWMIService.ExecQuery("Select * from Win32_Battery") report = "" For Each objItem in colItems report = report & "Availability: " & objItem.Availability & vbcrlf report = report & "Battery Status: " & objItem.BatteryStatus & vbcrlf report = report & "Chemistry: " & objItem.Chemistry & vbcrlf report = report & "Description: " & objItem.Description & vbcrlf report = report & "Design Voltage: " & objItem.DesignVoltage & vbcrlf report = report & "Device ID: " & objItem.DeviceID & vbcrlf report = report & "Estimated Run Time: " & objItem.EstimatedRunTime & vbcrlf report = report & "Name: " & objItem.Name & vbcrlf report = report & "Power Management Capabilities: " & vbcrlf For Each objElement In objItem.PowerManagementCapabilities report = report & vbTab & objElement & vbcrlf Next report = report & "Power Management Supported: " & objItem.PowerManagementSupported & vbcrlf Next msgbox report

    two functions to enable or disable IE security warning

    Basically, modified certain registry values to enable and disable the IE security warning. Sub EnableActiveXWarning () Dim SHL Dim sReg Set SHL = CreateObject ("WScript.Shell") sReg = "HKCU\Software\Microsoft\Windows\CurrentVersion\Internet Settings\Zones\0\1201" If SHL.RegRead (sReg) = 1 Then MsgBox "ActiveX Warning is already enabled!",vbExclamation Else SHL.RegWrite sReg,1,"REG_DWORD" If SHL.RegRead (sReg) = 1 Then MsgBox "The ActiveX Warning was successfully enabled.",vbInformation Else MsgBox "An unknown error has occured !!",vbCritical End If End If Set SHL = Nothing End Sub Sub DisableActiveXWarning () Dim SHL Dim sReg Set SHL = CreateObject ("WScript.Shell") sReg = "HKCU\Software\Microsoft\Windows\CurrentVersion\Internet Settings\Zones\0\1201" If SHL.RegRead (sReg) = 0 Then MsgBox "ActiveX Warning is already disabled!",vbExclamation Else SHL.RegWrite sReg,0,"REG_DWORD" If SHL.RegRead (sReg) = 0 Then MsgBox "The ActiveX Warning was successfully disabled.",vbInformation Else MsgBox "An unknown error has occured !!",vbCritical End If End If Set SHL = Nothing End Sub

    to see what's available CreateObject() object List for vbs

    to see what's available is by looking under Tools> References in the VBA editor within Word or other Office products. Then include a reference, and go to the Object Browser to see its methods and properties. If you don't have Office installed, there are other ways to list the COM interfaces on your machine using VBScript. Take a look at VBScript Scripting Techniques where describes some programs that provide an object browser. also a script that shows how to list ProgIds from your registry. I have over 3000 on my machine. Not all will have scriptable interfaces, but many will. .NET alone has hundreds of useful objects, and all are documented on MSDN. Once you have an interesting looking ProgId, do a Google search to find more about it. https://www.robvanderwoude.com/vbstech_objectbrowsers.php

    CreateObject Create an automation object

    That means to run an external command Set objShell = CreateObject("Wscript.Shell") CreateObject("WScript.Shell").Run "Your-VBScript-Here" Set WshShell = WScript.CreateObject("WScript.Shell") WshShell.Run "notepad", 9 Set objPlayer = CreateObject( "WMPlayer.OCX" ) With CreateObject("WMPlayer.OCX") Set objWMPlayer = CreateObject( "WMPlayer.OCX.7" ) Set objExcel = CreateObject("Excel.Application") Set app = WScript.CreateObject("Excel.Application") set DOCAppl = CreateObject("Word.Application") set pptAppl = CreateObject("Powerpoint.Application") Set lstProgID = CreateObject( "System.Collections.ArrayList" ) Set objSortList = CreateObject( "System.Collections.SortedList" ) Set speech = CreateObject("SAPI.SpVoice") Set IE = CreateObject("InternetExplorer.Application") Set objIE = WScript.CreateObject("InternetExplorer.Application") Set objShell = CreateObject("Shell.Application") For Each w In CreateObject("Shell.Application").Windows Set theFile = CreateObject("ADODB.Stream") 'To sent xmlhttp request to webserver & get html code Set oXMLHttp = CreateObject("MSXML2.XMLHTTP") Set req = CreateObject("Msxml2.XMLHttp.6.0") Set xml2Doc = CreateObject( "Msxml2.DOMDocument.5.0" ) 'To parse data from html tags Set ohtmlFile = CreateObject("htmlfile") ' to create an instance of FileSystemObject. Set FSO = CreateObject("Scripting.FileSystemObject") Dim StdOut : Set StdOut = CreateObject("Scripting.FileSystemObject").GetStandardStream(1) Set dict = CreateObject("Scripting.Dictionary") set oLocator = CreateObject("WbemScripting.SWbemLocator") Set objEmail = CreateObject( "CDO.Message" ) Set objIE = CreateObject( "InternetExplorer.Application" ) Set objInet = CreateObject( "InetCtls.Inet.1" ) Set objHTTP = CreateObject( "WinHttp.WinHttpRequest.5.1" ) Set objExcel = CreateObject( "Excel.Application" ) Set objOutlook = CreateObject( "Outlook.Application" ) Set objPpt = CreateObject( "PowerPoint.Application" ) Set objWord = CreateObject( "Word.Application" ) Set objCal = CreateObject( "MSCAL.Calendar" ) Set objQPro = CreateObject( "QuattroPro.PerfectScript" ) Set objWP = CreateObject( "WordPerfect.PerfectScript" ) Set objConn = CreateObject( "ADODB.Connection" ) Set objRecSet = CreateObject( "ADODB.Recordset" ) Set objDic = CreateObject( "Scripting.Dictionary" ) Set objFSO = CreateObject( "Scripting.FileSystemObject" ) Set wshNetwork = CreateObject( "WScript.Network" ) Set wshShell = CreateObject( "WScript.Shell" ) Set objRandom = CreateObject( "System.Random" ) Set objArrList = CreateObject( "System.Collections.ArrayList" ) Set xmlDoc = CreateObject( "Microsoft.XmlDom" ) Set objiTunes = CreateObject( "iTunes.Application" ) Set objReal = CreateObject( "rmocx.RealPlayer G2 Control.1" ) Set objFSDialog = CreateObject( "SAFRCFileDlg.FileSave" ) Set objFODialog = CreateObject( "SAFRCFileDlg.FileOpen" ) Set objDialog = CreateObject( "UserAccounts.CommonDialog" ) Set SOAPClient = CreateObject( "MSSOAP.SOAPClient" ) Set objWOL = CreateObject( "UltraWOL.ctlUltraWOL" ) Set objSearcher = CreateObject( "Microsoft.Update.Searcher" ) Set objShell = CreateObject( "Shell.Application" ) Set myConn = CreateObject("ADODB.Connection") Set myCommand = CreateObject("ADODB.Command" ) Set AdCn = CreateObject("ADODB.Connection") Set AdRec = CreateObject("ADODB.Recordset") Dim g_oSB : Set g_oSB = CreateObject("System.Text.StringBuilder") Set objEmail= CreateObject( "CDO.Message" ) The following VBScript code can be used to list all available ProgIDs: Option Explicit Const HKEY_CLASSES_ROOT = &H80000000 Dim arrProgID, lstProgID, objReg, strMsg, strProgID, strSubKey, subKey, subKeys() Set lstProgID = CreateObject( "System.Collections.ArrayList" ) Set objReg = GetObject( "winmgmts://./root/default:StdRegProv" ) ' List all subkeys of HKEY_CLASSES_ROOT\CLSID objReg.EnumKey HKEY_CLASSES_ROOT, "CLSID", subKeys ' Loop through the list of subkeys For Each subKey In subKeys ' Check each subkey for the existence of a ProgID strSubKey = "CLSID\" & subKey & "\ProgID" objReg.GetStringValue HKEY_CLASSES_ROOT, strSubKey, "", strProgID ' If a ProgID exists, add it to the list If Not IsNull( strProgID ) Then lstProgID.Add strProgID Next ' Sort the list of ProgIDs lstProgID.Sort ' Copy the list to an array (this makes displaying it much easier) arrProgID = lstProgID.ToArray ' Display the entire array WScript.Echo Join( arrProgID, vbCrLf ) Don't try to load these objects all at once, it might crash your computer. https://www.reliance-scada.com/en/support/articles/technical/vbscript-tip-working-with-an-object-list VBScript tip: Working with an object list https://www.informit.com/articles/article.aspx?p=29570&seqNum=3 Windows Scripting and Objects https://www.itprotoday.com/devops-and-software-development/understanding-vbscript-object-management VBScript Object Management

    GetObject

    Set objExcelFile = GetObject("C:\Scripts\Test.xls") WScript.Echo objExcelFile.Name objExcelFile.Close This code will get you the Excel Workbook object contained in C:\Scripts\Test.xls. You can use TypeName() to confirm that: Set objExcelFile = GetObject("C:\Scripts\Test.xls") WScript.Echo objExcelFile.Name WScript.Echo TypeName(objExcelFile) objExcelFile.Close The output will be: test.xls Workbook If the specified Excel workbook doesn't exist the script will return an error. If an instance of Excel is already running you can use this code to get a reference to it: Set objExcel = GetObject( , "Excel.Application") For Each objWorkbook In objExcel.Workbooks WScript.Echo objWorkbook.Name Next objExcel.Quit Notice the comma before 'Excel.Application'. The script gets a reference to a running Excel application, lists open workbooks names and quits Excel. If there is no Excel instance running you will receive an error. This is also why you couldn't use GetObject() to get an instance of Scripting.FileSystemObject - there was no running instance. You could use GetObject if there is an instance og Scripting.FileSystemObject already running in memory. Try this code: Set objFso = CreateObject("Scripting.FileSystemObject") Set objFso1 = GetObject("", "Scripting.FileSystemObject") WScript.Echo TypeName(objFso) WScript.Echo TypeName(objFso1) You can see that you first need to use CreateObject() to and when FileSystemObject is running it is possible to get a reference to it, but this doesn't make much sense because you already have a reference to it (objFso). So, use CreateObject() to create an instance of FileSystemObject.

    Scripting.FileSystemObject

    The following code illustrates how the FileSystemObject object is used to return a TextStream object that can be read from or written to: Set fs = CreateObject("Scripting.FileSystemObject") Set a = fs.CreateTextFile("c:\testfile.txt", True) a.WriteLine("This is a test.") a.Close In the example code: The CreateObject function returns the FileSystemObject (fs). The CreateTextFile method creates the file as a TextStream object (a). The WriteLine method writes a line of text to the created text file. The Close method flushes the buffer and closes the file. Methods METHODS Method Description BuildPath Appends a name to an existing path. CopyFile Copies one or more files from one location to another. CopyFolder Copies one or more folders from one location to another. CreateFolder Creates a new folder. CreateTextFile Creates a text file and returns a TextStream object that can be used to read from, or write to the file. DeleteFile Deletes one or more specified files. DeleteFolder Deletes one or more specified folders. DriveExists Checks if a specified drive exists. FileExists Checks if a specified file exists. FolderExists Checks if a specified folder exists. GetAbsolutePathName Returns the complete path from the root of the drive for the specified path. GetBaseName Returns the base name of a specified file or folder. GetDrive Returns a Drive object corresponding to the drive in a specified path. GetDriveName Returns the drive name of a specified path. GetExtensionName Returns the file extension name for the last component in a specified path. GetFile Returns a File object for a specified path. GetFileName Returns the file name or folder name for the last component in a specified path. GetFolder Returns a Folder object for a specified path. GetParentFolderName Returns the name of the parent folder of the last component in a specified path. GetSpecialFolder Returns the path to some of Windows' special folders. GetTempName Returns a randomly generated temporary file or folder. Move Moves a specified file or folder from one location to another. MoveFile Moves one or more files from one location to another. MoveFolder Moves one or more folders from one location to another. OpenAsTextStream Opens a specified file and returns a TextStream object that can be used to read from, write to, or append to the file. OpenTextFile Opens a file and returns a TextStream object that can be used to access the file. WriteLine Writes a specified string and new-line character to a TextStream file. PROPERTIES Property Description Drives Returns a collection of all Drive objects on the computer. Name Sets or returns the name of a specified file or folder. Path Returns the path for a specified file, folder, or drive. Size For files, returns the size, in bytes, of the specified file; for folders, returns the size, in bytes, of all files and subfolders contained in the folder. Type Returns information about the type of a file or folder (for example, for files ending in .TXT, "Text Document" is returned).

    CreateObject function

    The CreateObject function creates an object Syntax CreateObject(servername.typename[,location]) Parameter Description servername Required. The name of the application that provides the object typename Required. The type/class of the object location Optional. Where to create the object Example Creating a regular expression object: txt = "This is a beautiful day" Set objReg = CreateObject("vbscript.regexp") objReg.Pattern = "i" response.write(objReg.Replace(txt,"##")) The output of the code above will be: Th##s is a beautiful day

    Visual Basic Functions

    https://github.com/MicrosoftDocs/VBA-Docs/blob/master/Language/Reference/functions-visual-basic-for-applications.md Functions (Visual Basic for Applications) Conversion functions Asc Chr CVErr Format Hex Oct Str Val Math functions Abs Atn Cos Derived math Exp Int, Fix Log Rnd Sgn Sin Sqr Tan Other functions Array CallByName Choose Command CreateObject CurDir Date DateAdd DateDiff DatePart DateSerial DateValue Day DDB Dir DoEvents Environ EOF Error FileAttr FileDateTime FileLen Filter FormatCurrency FormatDateTime FormatNumber FormatPercent FreeFile FV GetAllSettings GetAttr GetObject GetSetting Hour IIf IMEStatus Input InputBox InStr InStrRev IPmt IRR IsArray IsDate IsEmpty IsError IsMissing IsNull IsNumeric IsObject Join LBound LCase Left Len Loc LOF LTrim, RTrim, and Trim MacID MacScript Mid Minute MIRR Month MonthName MsgBox Now NPer NPV Partition Pmt PPmt PV QBColor Rate Replace RGB Right Round Second Seek Shell SLN Space Spc Split StrComp StrConv String StrReverse Switch SYD Tab Time Timer TimeSerial TimeValue TypeName UBound UCase VarType Weekday WeekdayName Year

    connect to SQL Server

    Const DB_CONNECT_STRING = "Provider=SQLOLEDB.1;Data Source=sql14\qw;Initial Catalog=fret;user id ='admin';password='pass'" Set myConn = CreateObject("ADODB.Connection") Set myCommand = CreateObject("ADODB.Command" ) myConn.Open DB_CONNECT_STRING Set myCommand.ActiveConnection = myConn myCommand.CommandText = "UPDATE lookup SET Col1 = 'Hello'" myCommand.Execute myConn.Close First, you have to define the connection and recordset that you'll be using: Set AdCn = CreateObject("ADODB.Connection") Set AdRec = CreateObject("ADODB.Recordset") After that, it's all about the connection string: connstr="Provider=SQLOLEDB.1;Data Source=" & server & ";Initial Catalog=" & database & ";user id = '" & uid & "';password='" & pwd & "'" The string consists of a few parts: Provider: the type of connection you are establishing, in this case SQL Server. Data Source: The server you are connecting to. Initial Catalog: The name of the database. user id: your username. password: um, your password. ;) Note that if you want to use your Windows login credentials and are running the script locally then you can substitute the following for the username and password fields: Integrated Security=SSPI Of course, this won't work if you're using your script on a website, so you'll have to explicitly use username and password. Then, making sure your connection is open, you just open the recordset, hand over the SQL query, and capture the returned data as an array. SQL="Select @@version as name" AdCn.Open connstr AdRec.Open SQL, AdCn,1,1 queryReturn=Adrec("name") Just remember that the data is being returned as an array (often two dimensional, where the results you want are actually in the second dimension of the array!) and that you may need to either Trim to kill blank spaces at the end of results or parse the results with string functions like Left. Personally, I always Trim() a result while assigning it to a variable as I've been bitten by hidden blanks more times than I can count.

    What is a VBA module?

    VBScript does not have a module system A VBA module is where you type your computer code. The code you type in a module when run can perform tasks in Excel like format worksheet data, process data, create charts, command databases...etc. VBA code is typed and viewed in the VBA Editor in what are called modules. A collection of modules is called a VBA project. In the VBA Editor, a VBA module when viewed resembles and behaves like a Word document in both basic organization and typing. When viewed, a VBA module will appear in its own window within the VBA Editor. Think of modules as organizational units for your code, you add VBA modules as needed to a project to organize and run code. VBA modules come in three different flavors: Standard modules, Object modules, and Class modules. A Standard module is where you will be typing most of your code when starting off in Excel VBA. Think of it as the town square, everybody can easily get to you and talk to you. You can assign shape buttons to procedures in these modules to easily run them. An Object module belongs to an Excel element like a workbook, chart, worksheet or a VBA element like a userform. You create events in them which are just Sub procedures that run when something occurs like pressing enter in a cell, opening a workbook, or clicking on a worksheet tab. These procedures can be used in place of clicking buttons to run code which is really cool but they require a lot of logic and programming know how to bring them under control. They tend to run when you do not want them to run. A Class module is used to create a class for an object. Classes are what you will be using to command Excel, Word, PowerPoint..., but these are already made, you will just learn to run them. Object oriented programming involves advanced programming concepts which are better left to investigate till after you learn the programming fundamentals. All of the modules just discussed appear in the Project Explorer window as icons. They are organized as follows: Standard modules are found under the Modules folder, Object modules are found under the Excel Objects folder, and Class modules are found under the Class Modules folder. One note here, they all do look alike so you have to look at the name of the module and then locate it in the Project Explorer tree to tell what type it is. VBA Module

    open webpage in VBS

    Dim URL,WshShell,i URL = "www.yahoo.com" Set WshShell = CreateObject("WScript.shell") For i = 0 to 50 WshShell.SendKeys(chr(175)) Next WshShell.run "CMD /C start chrome.exe " & URL & "",0,False

    Keep a VBScript window on top

    ' as well as adding a logoff button Dim Title,ws,nMinutes,nSeconds,sMessage,Command,Executer Title = "Session Timer" Set ws = CreateObject("wscript.Shell") nMinutes = 0 nSeconds = 10 sMessage = "<font color=Red size=2><b>You have" 'Open a chromeless window with message with HTABox("lightBlue",130,300,1070,600) .document.title = "Session Timer" .msg.innerHTML = sMessage do until .done.value or (nMinutes + nSeconds < 1) .msg.innerHTML = sMessage & "<br>" & nMinutes & ":" & Right("0"&nSeconds, 2) _ & " minutes of session time remaining</b></font><br>" wsh.sleep 1000 ' milliseconds nSeconds = nSeconds - 1 if nSeconds < 0 then if nMinutes > 0 then nMinutes = nMinutes - 1 nSeconds = 59 end if end if loop .done.value = true .close end with ws.Popup "Your session time has finished. You will now be logged off.","5",Title,0+48 'Command ="cmd /c Shutdown.exe -l -f" 'Executer = WS.Run(Command,0,False) '***************************************************************** Function HTABox(sBgColor,h, w, l, t) Dim IE, HTA, sCmd, nRnd randomize : nRnd = Int(1000000 * rnd) sCmd = "mshta.exe ""javascript:{new " _ & "ActiveXObject(""InternetExplorer.Application"")" _ & ".PutProperty('" & nRnd & "',window);" _ & "window.resizeTo(" & w & "," & h & ");" _ & "window.moveTo(" & l & "," & t & ")}""" with CreateObject("WScript.Shell") .Run sCmd, 1, False do until .AppActivate("javascript:{new ") : WSH.sleep 10 : loop end with 'WSHShell For Each IE In CreateObject("Shell.Application").windows If IsObject(IE.GetProperty(nRnd)) Then set HTABox = IE.GetProperty(nRnd) IE.Quit HTABox.document.title = "HTABox" HTABox.document.write _ "<HTA:Application contextMenu=no border=thin " _ & "minimizebutton=no maximizebutton=no sysmenu=no SHOWINTASKBAR=no >" _ & "<body scroll=no style='background-color:" _ & sBgColor & ";font:normal 10pt Arial;" _ & "border-Style:inset;border-Width:3px'" _ & "onbeforeunload='vbscript:if not done.value then " _ & "window.event.cancelBubble=true:" _ & "window.event.returnValue=false:" _ & "done.value=true:end if'>" _ & "<input type=hidden id=done value=false>" _ & "<center><span id=msg> </span><br>" _ & "<input type=button id=btn1 value=' Log Off ' "_ & "onclick=done.value=true><center></body>" HTABox.btn1.focus Exit Function End If Next MsgBox "HTA window not found." wsh.quit End Function

    VBS InternetExplorer.Application的屬性和方法介紹

    示例程式碼 Set ie = CreateObject("InternetExplorer.Application") ie.Navigate "//www.jb51.net" Wscript.Sleep 1000 ie.Toolbar = 0 ie.visible=False ie.Document.f1.word.value = kw If ie.Document.f1.word.value="" Then Wscript.Quit 上面是在網上看到的,Navigate Toolbar visible 等都是怎麼用的?? 怎麼網上找不到它們的用法? 下面是一些屬性說明: Set ie=WScript.CreateObject(“internetexplorer.application”) ie.menubar=0 ‘不顯示IE物件選單欄 ie.AddressBar=0 ‘不顯示IE物件位址列 ie.ToolBar=0 ‘不顯示IE物件工具欄 ie.StatusBar=0 ‘不顯示IE物件狀態列 ie.FullScreen=1 ‘全屏化IE物件 ie.Width=800 ‘設定IE物件寬度 ie.Height=600 ‘設定IE物件高度 ie.Resizable=0 ‘設定IE物件大小是否可以被改動 ie.visible=1 ‘設定是否可見 ie.Navigate “//www.jb51.net” ‘設定IE物件預設指向的頁面 目的留個備份,方便我以後去MSDN上找用法。 InternetExplorer Object 42 out of 82 rated this helpful Rate this topic Controls an instance of Windows Internet Explorer through automation. Members Table The following table lists the members exposed by the InternetExplorer object. Events EventDescription BeforeNavigateFires before navigation occurs in the given object (on either a window or frameset element). BeforeNavigate2Fires before navigation occurs in the given object (on either a window element or a frameset element). CommandStateChangeFires when the enabled state of a command changes. DocumentCompleteFires when a document is completely loaded and initialized. DownloadBeginFires when a navigation operation begins. DownloadCompleteFires when a navigation operation finishes, is halted, or fails. FileDownloadFires to indicate that a file download is about to occur. If a file download dialog box can be displayed, this event fires prior to the appearance of the dialog box. NavigateCompleteFires after a navigation to a link is completed on either a window element or a frameSet element. NavigateComplete2Fires after a navigation to a link is completed on a window element or a frameSet element. NavigateErrorFires when an error occurs during navigation. NewProcessCreates a new process to handle the navigation. NewWindowFires when a new window is to be created. NewWindow2Fires when a new window is to be created. NewWindow3Raised when a new window is to be created. Extends NewWindow2 with additional information about the new window. OnFullScreenFires when the FullScreen property is changed. OnMenuBarFires when the MenuBar property is changed. OnQuitFires before the Internet Explorer application quits. OnStatusBarFires when the StatusBar property is changed. OnTheaterModeFires when the TheaterMode property is changed. OnToolBarFires when the ToolBar property is changed. OnVisibleFires when the Visible property of the object is changed. PrintTemplateInstantiationFires when a print template is instantiated. PrintTemplateTeardownFires when a print template is destroyed. PrivacyImpactedStateChangeFired when an event occurs that impacts privacy, or when a user navigates away from a URL that has impacted privacy. ProgressChangeFires when the progress of a download operation is updated on the object. PropertyChangeFires when the PutProperty method of the object changes the value of a property. RedirectXDomainBlockedFired when a cross-domain redirect request is blocked. SetPhishingFilterStatusFires to indicate the progress and status of Microsoft Phishing Filter analysis of the current webpage. SetSecureLockIconFires when there is a change in encryption level. StatusTextChangeFires when the status bar text of the object has changed. ThirdPartyUrlBlockedFired when a third-party URL is blocked. TitleChangeFires when the title of a document in the object becomes available or changes. UpdatePageStatusNot implemented. WindowActivateNot implemented. WindowMoveNot implemented. WindowResizeNot implemented. WindowStateChangedFires when the visibility state of a content window, such as the browser window or a tab, changes. Methods MethodDescription ClientToWindowComputes the full size of the browser window when given the specified width and height of the content area. ExecWBExecutes a command and returns the status of the command execution using the IOleCommandTarget interface. GetPropertyGets the value associated with a user-defined property name. GoBackNavigates backward one item in the history list. GoForwardNavigates forward one item in the history list. GoHomeNavigates to the current home or start page. GoSearchNavigates to the current search page. NavigateNavigates to a resource identified by a URL or to a file identified by a full path. Navigate2Navigates the browser to a location that might not be expressed as a URL, such as a pointer to an item identifier list (PIDL) for an entity in the Windows Shell namespace. PutPropertyAssociates a user-defined name/value pair with the object. QueryStatusWBQueries the object for the status of commands using the IOleCommandTarget interface. QuitCloses the object. RefreshReloads the file that is currently displayed in the object. Refresh2Reloads the file that is currently displayed with the specified refresh level. ShowBrowserBarShows or hides a specified browser bar. StopCancels a pending navigation or download, and stops dynamic page elements, such as background sounds and animations. Properties PropertyDescription AddressBarSets or gets a value that indicates whether the address bar of the object is visible or hidden. ApplicationGets the automation object for the application that is hosting the WebBrowser Control. BusyGets a value that indicates whether the object is engaged in a navigation or downloading operation. ContainerGets an object reference to a container. DocumentGets the automation object of the active document, if any. FullNameRetrieves the fully qualified path of the Internet Explorer executable. FullScreenSets or gets a value that indicates whether Internet Explorer is in full-screen mode or normal window mode. HeightSets or gets the height of the object. HWNDGets the handle of the Internet Explorer main window. LeftSets or gets the coordinate of the left edge of the object. LocationNameRetrieves the path or title of the resource that is currently displayed. LocationURLGets the URL of the resource that is currently displayed. MenuBarSets or gets a value that indicates whether the Internet Explorer menu bar is visible. NameRetrieves the frame name or application name of the object. OfflineSets or gets a value that indicates whether the object is operating in offline mode. ParentGets the parent of the object. PathRetrieves the system folder of the Internet Explorer executable. ReadyStateGets the ready state of the object. RegisterAsBrowserSets or gets a value that indicates whether the object is registered as a top-level browser window. RegisterAsDropTargetSets or gets a value that indicates whether the object is registered as a drop target for navigation. ResizableSets or gets a value that indicates whether the object can be resized. SilentSets or gets a value that indicates whether the object can display dialog boxes. StatusBarSets or gets a value that indicates whether the status bar for the object is visible. StatusTextSets or gets the text in the status bar for the object. TheaterModeSets or gets whether the object is in theater mode. ToolBarSets or gets whether toolbars for the object are visible. TopSets or gets the coordinate of the top edge of the object. TopLevelContainerGets a value that indicates whether the object is a top-level container. TypeGets the user type name of the contained document object. VisibleSets or gets a value that indicates whether the object is visible or hidden. WidthSets or gets the width of the object. Remarks
    Internet Explorer 8. On Windows Vista, to create an instance of Internet Explorer running at a medium integrity level, pass CLSID_InternetExplorerMedium (defined in exdisp.idl) to CoCreateInstance. The resulting InternetExplorerMedium object supports the same events, methods, and properties as the InternetExplorer object.
    Examples
    The following example uses CreateObject in Microsoft Visual Basic to launch an instance of Internet Explorer.
    Dim IE As SHDocVw.InternetExplorer Set IE = CreateObject("InternetExplorer.Application") The following C# example launches an instance of Internet Explorer and navigates to a Web page. The code also demonstrates how to create an event handler to listen for the BeforeNavigate2 event. The project requires a reference to the Microsoft Internet Controls (SHDocVw) type library. using System; using System.Collections.Generic; using System.Text; namespace ConsoleApplication1 { class EventHandlers { public void OnBeforeNavigate2(object sender, ref object URL, ref object Flags, ref object Target, ref object PostData, ref object Headers, ref bool Cancel) { Console.WriteLine("BeforeNavigate2 fired!"); } } class Program { static void Main(string[] args) { EventHandlers e = new EventHandlers(); SHDocVw.InternetExplorer IE = new SHDocVw.InternetExplorer(); object Empty = 0; object URL = "http://www.live.com"; // override BeforeNavigate2 event IE.BeforeNavigate2 = new SHDocVw.DWebBrowserEvents2_BeforeNavigate2EventHandler( e.OnBeforeNavigate2); IE.Visible = true; IE.Navigate2(ref URL, ref Empty, ref Empty, ref Empty, ref Empty); System.Threading.Thread.Sleep(5000); IE.Quit(); } } }

    Better Than Batch: A Windows Scripting Host Tutorial

    If you've been working in the computer world for a while then you're probably pretty familiar with batch jobs. IT professionals around the world utilized them to run all sorts of automated computer processing jobs and personal tasks. In fact Paul recently covered how to write such a file. The problem with batch jobs is that they were very limited. The command set was somewhat short and didn't allow for very much functionality when it came to structured logic using if-then, for, next and while loops. Later, Windows Scripting Host came along. The MS Windows Scripting Host is a multi-language script utility that Microsoft started installing as standard on all PCs from Windows 98 onward. By the second generation of the tool, it was renamed to Microsoft Script Host (MSH).

    A Microsoft Scripting Host Tutorial

    Here at MUO, we love computer automation. For example, Varun covered Sikuli, a tool to write automation scripts, and Guy showed you how to use AutoIt to automate tasks. The cool thing about MSH is that if you have any post-Win 98 PC, you can write a "batch" script in a variety of languages. Available languages include JScript, VBA, and VBscript. It's also possible to write scripts in Perl, Python, PHP, Ruby or even Basic if you have the right implementation with the right scripting engine. Personally, I know Visual Basic well, so I usually opt for VBScript. The beauty here is that you don't need any special programming software or compiler. Just open up Notepad and write your script, just like how you wrote your batch jobs. Without installing anything, you can write scripts in VB. The simplest script is printing text to a pop-up window, like this: windows scripting host tutorial Save the file as a .vbs and Windows will recognize and run it. This is what happens when you double click on the file above: windows scripting You can write more advanced scripts utilizing the languages you're accustomed to. For the most flexibility, place <job> and <script language="VBScript"> (or whatever language you choose) around each segment of code in your file, and save it as a .wsf file. This way, so long as you enclose the code in the defined script language tags, you can use multiple languages in the same file. To show you how cool this can be, I decided to write a script that would reach out to the NIST atomic clock to check the current time. If morning, it automatically opens my Thunderbird email client. If noon, it would open my browser to CNN.com. This conditional script gives you the ability to make your computer much more intelligent. If you run this script when your PC starts up, you can make it automatically launch whatever you like depending what time of day it is. windows scripting The first part of the script goes out to the time server "http://time.nist.gov:13" and gets the current time. After formatting it correctly, it sets the computer time. Credit where credit is due, this script was adapted from TomRiddle's excellent script over at VisualBasicScript.com. To save time, always find the example code you need online, and then tweak it to your needs. Here's what the script does with just the code above implemented so far. windows scripting Now that the script is working and will sync my PC every time it's launched, it's time to have it determine what to automatically launch depending on the time of day. In Windows Scripting Host, this task is as easy as an If-Then statement checking the hour of the day in the "Now" function, and then launching the appropriate software. windows scripting host When launched between 8 to 10 in the morning, this script will start up my Thunderbird email client. When run between 11am to 1pm, it'll launch CNN.com in a browser. As you can see, just by being creating and adding a little bit of intelligence to a script file, you can do some pretty cool computer automation. By the way, it's a very good idea to have a reference of scripting commands handy when you write these scripts. If you're into VBScript like me, a great resources is ss64.com, which lists all VBScript commands alphabetically on one page. windows scripting host Writing scripts alone isn't going to automate anything, because you'll still have to manually launch them. So to complete your automation using the Windows Script Host, go into the Task Scheduler in the control panel (administrator area) and select to create a task. windows scripting host The scheduler lets you launch your script upon a whole assortment of events, such as time of day or on a specific schedule, when a system event takes place, or when the computer is first booted or logged into. Here, I'm creating a scheduled task to launch my script above every time the PC starts. windows scripting host tutorial This is only a very brief Windows Scripting Host tutorial. Considering the number of commands and functions available in any of these scripting languages, the possibilities to automate all sorts of cool tasks on your PC are pretty much only limited by your imagination. Some of the best sites to find pre-written scripts that you can use or customize include the following: Have you ever used the Windows Script Host? Do you have any cool tips or examples to share? Offer your insight and share your experiences in the comments section below.

    fso.OpenTextFile

    fso.OpenTextFile( filename, [ iomode, [ create, [ format ]]] ) https://analystcave.com/vba-filesystemobject-fso-in-excel/vba-opentextfile/ filename Name of the text file to open. iomode Optional. One of three options: Option Value Description ForReading 1 Open the file as read only ForWriting 2 Open file for write only ForAppending 8 Open for appending only. Does not allow to overwrite existing text only writing to the end of the file create Optional. If True will allow to create a new file if no such file exists. If False file will not be created and an error will be raised. format Defines the coding of the text file: Option Value Description TristateUseDefault -2 Default system coding TristateTrue -1 Unicode coding TristateFalse 0 ASCII coding The following code illustrates the use of the OpenTextFile method to open a file for appending text: Sub OpenTextFileTest Const ForReading = 1, ForWriting = 2, ForAppending = 8 Dim fs, f Set fs = CreateObject("Scripting.FileSystemObject") Set f = fs.OpenTextFile("c:\testfile.txt", ForAppending, TristateFalse) f.Write "Hello world!" f.Close End Sub

    Win32-ComputerSystemProduct - WMI VBScript sample

    The foundations for Manageability in Windows 2019/2016/2012/2008 and Windows 10/7/XP are Windows Management Instrumentation (WMI; formerly WBEM) and WMI extensions for Windows Driver Model (WDM). ActiveXperts Network Monitor provides the ability to build monitor check routines based on WMI. ActiveXperts has collected more than a hundred WMI samples. You can use these samples as a base for new check routines you can write yourself. The Win32_ComputerSystemProduct WMI class can be used in ActiveXperts Network Monitor to monitor your servers. Win32-ComputerSystemProduct Description The Win32_ComputerSystemProduct WMI class represents a product. This includes software and hardware used on this computer system. Example(s) On Error Resume Next strComputer = "." Set objWMIService = GetObject("winmgmts:\\" & strComputer & "\root\cimv2") Set colItems = objWMIService.ExecQuery("Select * from Win32_ComputerSystemProduct",,48) For Each objItem in colItems Wscript.Echo "Caption: " & objItem.Caption Wscript.Echo "Description: " & objItem.Description Wscript.Echo "IdentifyingNumber: " & objItem.IdentifyingNumber Wscript.Echo "Name: " & objItem.Name Wscript.Echo "SKUNumber: " & objItem.SKUNumber Wscript.Echo "UUID: " & objItem.UUID Wscript.Echo "Vendor: " & objItem.Vendor Wscript.Echo "Version: " & objItem.Version Next

    to uniquely identify a computer

    UUID good way to uniquely identify a computer use wmic DISKDRIVE get SerialNumber use MAC address ' get MAC address dim WMI: set WMI = GetObject("winmgmts:\\.\root\cimv2") dim Nads: set Nads = WMI.ExecQuery("Select * from Win32_NetworkAdapter where physicaladapter=true") dim nad for each Nad in Nads if not isnull(Nad.MACAddress) then Wscript.Echo Nad.description, Nad.MACAddress next use uuid 'get uuid 'use the uuID attributes of the Win32_ComputerSystemProduct class 'to get the machine's GUID, which is read from the BIOS strComputer ="." ' -------------------------------------------- Set objWMIService = GetObject("winmgmts:\\" & strComputer & "\root\CIMV2") Set colItems = objWMIService.ExecQuery ("SELECT * FROM Win32_ComputerSystemProduct") ' On Error Resume Next For Each objComputer In colItems Wscript.Echo "uuID: " & objComputer.uuID Next WScript.Quit PowerShell/VBScript example scripts for connecting/modifying AD or managing Windows machines PowerShell Universal tutorial powershell-universal Powershell Tutorial

    Time function

    To output a script's execution time, include this at the beginning: dtmStartTime = Timer And include this at the end: Wscript.Echo "Script execution time: " & Round(Timer - dtmStartTime, 2) & " seconds" The Timer Jump function returns the number of seconds that have elapsed since midnight (12:00 a.m.). The Round Jump function controls the number of decimal places displayed. Here is a function that will convert seconds to days, hours, and minutes. Function GetElapsedTime Const SECONDS_IN_DAY = 86400 Const SECONDS_IN_HOUR = 3600 Const SECONDS_IN_MINUTE = 60 Const SECONDS_IN_WEEK = 604800 dtmEndTime = Timer seconds = Round(dtmEndTime - dtmStartTime, 2) If seconds < SECONDS_IN_MINUTE Then GetElapsedTime = seconds & " seconds " Exit Function End If If seconds < SECONDS_IN_HOUR Then minutes = seconds / SECONDS_IN_MINUTE seconds = seconds MOD SECONDS_IN_MINUTE GetElapsedTime = Int(minutes) & " minutes " & seconds & " seconds " Exit Function End If If seconds < SECONDS_IN_DAY Then hours = seconds / SECONDS_IN_HOUR minutes = (seconds MOD SECONDS_IN_HOUR) / SECONDS_IN_MINUTE seconds = (seconds MOD SECONDS_IN_HOUR) MOD SECONDS_IN_MINUTE GetElapsedTime = Int(hours) & " hours " & Int(minutes) & " minutes " & seconds & " seconds " Exit Function End If If seconds < SECONDS_IN_WEEK Then days = seconds / SECONDS_IN_DAY hours = (seconds MOD SECONDS_IN_DAY) / SECONDS_IN_HOUR minutes = ((seconds MOD SECONDS_IN_DAY) MOD SECONDS_IN_HOUR) / SECONDS_IN_MINUTE seconds = ((seconds MOD SECONDS_IN_DAY) MOD SECONDS_IN_HOUR) MOD SECONDS_IN_MINUTE GetElapsedTime = Int(days) & " days " & Int(hours) & " hours " & Int(minutes) & " minutes " & seconds & " seconds " Exit Function End If End Function Here is a sample script using the function that prints "Hello World!" to the screen, waits for 1 second, then outputs the script execution time. dtmStartTime = Timer Wscript.Echo "Hello, World!" Wscript.Sleep 1000 Wscript.Echo "Script completed in " & GetElapsedTime Function GetElapsedTime Const SECONDS_IN_DAY = 86400 Const SECONDS_IN_HOUR = 3600 Const SECONDS_IN_MINUTE = 60 Const SECONDS_IN_WEEK = 604800 dtmEndTime = Timer seconds = Round(dtmEndTime - dtmStartTime, 2) If seconds < SECONDS_IN_MINUTE Then GetElapsedTime = seconds & " seconds " Exit Function End If If seconds < SECONDS_IN_HOUR Then minutes = seconds / SECONDS_IN_MINUTE seconds = seconds MOD SECONDS_IN_MINUTE GetElapsedTime = Int(minutes) & " minutes " & seconds & " seconds " Exit Function End If If seconds < SECONDS_IN_DAY Then hours = seconds / SECONDS_IN_HOUR minutes = (seconds MOD SECONDS_IN_HOUR) / SECONDS_IN_MINUTE seconds = (seconds MOD SECONDS_IN_HOUR) MOD SECONDS_IN_MINUTE GetElapsedTime = Int(hours) & " hours " & Int(minutes) & " minutes " & seconds & " seconds " Exit Function End If If seconds < SECONDS_IN_WEEK Then days = seconds / SECONDS_IN_DAY hours = (seconds MOD SECONDS_IN_DAY) / SECONDS_IN_HOUR minutes = ((seconds MOD SECONDS_IN_DAY) MOD SECONDS_IN_HOUR) / SECONDS_IN_MINUTE seconds = ((seconds MOD SECONDS_IN_DAY) MOD SECONDS_IN_HOUR) MOD SECONDS_IN_MINUTE GetElapsedTime = Int(days) & " days " & Int(hours) & " hours " & Int(minutes) & " minutes " & seconds & " seconds " Exit Function End If End Function

    execution time

    StartTime = Timer() .... EndTime = Timer() Wscript.Echo "Seconds to 2 decimal places: " & FormatNumber(EndTime - StartTime, 2) use of left, right and mid If (Right("0" & hour(now),2) + Right("0" & Minute(now),2)) > endTime then freq = 0

    Create a Userform in Excel VBA

    Step 1 − Navigate to VBA Window by pressing Alt+F11 and Navigate to "Insert" Menu and select "User Form". Upon selecting, the user form is displayed as shown in the following screenshot. Step 2 − Design the forms using the given controls. Step 3 − After adding each control, the controls have to be named. Caption corresponds to what appears on the form and name corresponds to the logical name that will be appearing when you write VBA code for that element. Step 4 − Following are the names against each one of the added controls. Control Logical Name Caption From frmempform Employee Form Employee ID Label Box empid Employee ID firstname Label Box firstname First Name lastname Label Box lastname Last Name dob Label Box dob Date of Birth mailid Label Box mailid Email ID Passportholder Label Box Passportholder Passport Holder Emp ID Text Box txtempid NOT Applicable First Name Text Box txtfirstname NOT Applicable Last Name Text Box txtlastname NOT Applicable Email ID Text Box txtemailid NOT Applicable Date Combo Box cmbdate NOT Applicable Month Combo Box cmbmonth NOT Applicable Year Combo Box cmbyear NOT Applicable Yes Radio Button radioyes Yes No Radio Button radiono No Submit Button btnsubmit Submit Cancel Button btncancel Cancel Step 5 − Add the code for the form load event by performing a right-click on the form and selecting 'View Code'. Step 6 − Select ‘Userform’ from the objects drop-down and select 'Initialize' method as shown in the following screenshot. Step 7 − Upon Loading the form, ensure that the text boxes are cleared, drop-down boxes are filled and Radio buttons are reset.
    Private Sub UserForm_Initialize()
       'Empty Emp ID Text box and Set the Cursor 
       txtempid.Value = ""
       txtempid.SetFocus
       
       'Empty all other text box fields
       txtfirstname.Value = ""
       txtlastname.Value = ""
       txtemailid.Value = ""
       
       'Clear All Date of Birth Related Fields
       cmbdate.Clear
       cmbmonth.Clear
       cmbyear.Clear
       
       'Fill Date Drop Down box - Takes 1 to 31
       With cmbdate
          .AddItem "1"
          .AddItem "2"
          .AddItem "3"
          .AddItem "4"
          .AddItem "5"
          .AddItem "6"
          .AddItem "7"
          .AddItem "8"
          .AddItem "9"
          .AddItem "10"
          .AddItem "11"
          .AddItem "12"
          .AddItem "13"
          .AddItem "14"
          .AddItem "15"
          .AddItem "16"
          .AddItem "17"
          .AddItem "18"
          .AddItem "19"
          .AddItem "20"
          .AddItem "21"
          .AddItem "22"
          .AddItem "23"
          .AddItem "24"
          .AddItem "25"
          .AddItem "26"
          .AddItem "27"
          .AddItem "28"
          .AddItem "29"
          .AddItem "30"
          .AddItem "31"
       End With
       
       'Fill Month Drop Down box - Takes Jan to Dec
       With cmbmonth
          .AddItem "JAN"
          .AddItem "FEB"
          .AddItem "MAR"
          .AddItem "APR"
          .AddItem "MAY"
          .AddItem "JUN"
          .AddItem "JUL"
          .AddItem "AUG"
          .AddItem "SEP"
          .AddItem "OCT"
          .AddItem "NOV"
          .AddItem "DEC"
       End With
       
       'Fill Year Drop Down box - Takes 1980 to 2014
       With cmbyear
          .AddItem "1980"
          .AddItem "1981"
          .AddItem "1982"
          .AddItem "1983"
          .AddItem "1984"
          .AddItem "1985"
          .AddItem "1986"
          .AddItem "1987"
          .AddItem "1988"
          .AddItem "1989"
          .AddItem "1990"
          .AddItem "1991"
          .AddItem "1992"
          .AddItem "1993"
          .AddItem "1994"
          .AddItem "1995"
          .AddItem "1996"
          .AddItem "1997"
          .AddItem "1998"
          .AddItem "1999"
          .AddItem "2000"
          .AddItem "2001"
          .AddItem "2002"
          .AddItem "2003"
          .AddItem "2004"
          .AddItem "2005"
          .AddItem "2006"
          .AddItem "2007"
          .AddItem "2008"
          .AddItem "2009"
          .AddItem "2010"
          .AddItem "2011"
          .AddItem "2012"
          .AddItem "2013"
          .AddItem "2014"
       End With
       
       'Reset Radio Button. Set it to False when form loads.
       radioyes.Value = False
       radiono.Value = False
    
    End Sub
    
    Step 8 − Now add the code to the Submit button. 
    
    Upon clicking the submit button, the user should be able to add the values into the worksheet.
    Private Sub btnsubmit_Click()
    Dim emptyRow As Long
    
    'Make Sheet1 active
    Sheet1.Activate
    'Determine emptyRow
    
    emptyRow = WorksheetFunction.CountA(Range("A:A")) + 1
    'Transfer information
    Cells(emptyRow, 1).Value = txtempid.Value
    
    Cells(emptyRow, 2).Value = txtfirstname.Value
    Cells(emptyRow, 3).Value = txtlastname.Value
    Cells(emptyRow, 4).Value = cmbdate.Value & "/" & cmbmonth.Value & "/" & cmbyear.Value
    
    Cells(emptyRow, 5).Value = txtemailid.Value
    If radioyes.Value = True Then
    Cells(emptyRow, 6).Value = "Yes"
    
    Else
    Cells(emptyRow, 6).Value = "No"
    End If
    
    End Sub
    Step 9 − Add a method to close the form when the user clicks the Cancel button.
    Private Sub btncancel_Click()
    
    Unload Me
    End Sub
    Step 10 − Execute the form by clicking the "Run" button. 
    
    Enter the values into the form and click the 'Submit' button. 
    Automatically the values will flow into the worksheet as shown in the following screenshot.
    
    
    
    

    opening PDF to send some keys to it

    Sub Sample() ActiveWorkbook.FollowHyperlink "C:\MyFile.pdf" End Sub assuming that some pdf reader installed.

    VBA execute a shell command

    retVal = Shell("C:\Temp\gc.exe 1", vbNormalFocus) Link: Shell Invoked from VBA

    VBA open workbook

    Steps to Open a Workbook using VBA To start the code, use the “Workbooks” object. Type a dot (.) after that and select the Open method from the list. Specify the file path in the first argument and make sure to enclose it in double quotation marks. In the end, run the code to open the workbook. Sub vba_open_workbook() Workbooks.Open "C:UsersDellDesktopmyFile.xlsx" End Sub

    VBScript CreateObject Function

    CreateObject(servername.typename[,location]) Parameter Description servername Required. Name of the application typename Required. The type/class of the object location Optional. Where to create the object Example Creating a regular expression object: txt="This is a beautiful day" Set objReg=CreateObject("vbscript.regexp") objReg.Pattern="i" response.write(objReg.Replace(txt,"##")) The output of the code above will be: Th##s is a beautiful day

    give list of running processes

    Option Explicit Call KillProcessbyName("common-api.jar") '* Sub KillProcessbyName(FileName) On Error Resume Next Dim WshShell,strComputer,objWMIService,colProcesses,objProcess Set WshShell = CreateObject("Wscript.Shell") strComputer = "." Set objWMIService = GetObject("winmgmts:{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2") Set colProcesses = objWMIService.ExecQuery("SELECT * FROM Win32_Process") For Each objProcess in colProcesses If InStr(objProcess.CommandLine,FileName) > 0 Then If Err <> 0 Then MsgBox Err.Description,VbCritical,Err.Description Else objProcess.Terminate(0) End if End If Next End Sub

    vbscript view all running processes

    Using TaskList Command TaskList Command can be used to display a list of all running applications and services with their details and Process IDs(PIDs). Dim ProTFPath, ProTF, StrPrInfo, StrPrInfoA, PrInfo Set WshShell = WScript.CreateObject("Wscript.Shell") Set FSO = WScript.CreateObject("Scripting.FileSystemObject") ProTFPath = "C:\Users\User\Desktop\PROCESSES.txt" WshShell.Run "CMD /C TASKLIST /V /FO LIST > """ + ProTFPath + """", 0, True ' Here Run is used instead Exec to avoid console window flashes. If FSO.FileExists(ProTFPath) Then Set ProTF = FSO.OpenTextFile(ProTFPath, 1, False) End If StrPrInfoA = ProTF.ReadAll PrInfo = Split(StrPrInfoA, VbCrLf + VbCrLf) For I = 0 To UBound(PrInfo) WScript.Echo PrInfo(I) Next Erase PrInfo ProTF.Close If you no longer need this file, add following lines to the end of the script: If FSO.FileExists(ProTFPath) Then FSO.DeleteFile(ProTFPath, True) End If by another answer EXE_Process = AllProcessRunningEXE(".") Vbs_Process = AllProcessRunningVBS (".") Function AllProcessRunningEXE( strComputerArg ) strProcessArr = "" Dim Process, strObject strObject = "winmgmts://" & strComputerArg For Each Process in GetObject( strObject ).InstancesOf( "win32_process" ) strProcessArr = strProcessArr & ";" & vbNewLine & Process.name Next AllProcessRunningEXE = Mid(strProcessArr,3,Len(strProcessArr)) End Function Function AllProcessRunningVBS (strComputerArg) strProcessArr = "" Set objWMIService = GetObject("winmgmts:{impersonationLevel=impersonate}!\\" & strComputerArg & "\root\cimv2") Set colItems = objWMIService.ExecQuery ("Select * from Win32_Process Where Name = 'cscript.exe' OR Name = 'wscript.exe'") For Each objItem in colItems strProcessArr = strProcessArr & ";" & vbNewLine & objItem.CommandLine Next AllProcessRunningVBS = Mid(strProcessArr,3,Len(strProcessArr)) Set objWMIService = Nothing Set colItems = Nothing End Function VBScript via WMI This is straightforward script. We are only querying the local workstation. You could conceivably get a list of processes on machine B from machine A, and even stop/start those processes. All remotely. Option Explicit Dim objWMIService, objProcess, colProcess Dim strComputer, strList strComputer = "." Set objWMIService = GetObject("winmgmts:{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2") Set colProcess = objWMIService.ExecQuery ("Select * from Win32_Process") For Each objProcess in colProcess strList = strList & vbCr & objProcess.Name Next WSCript.Echo strList

    用 VBScript 创建一个定时闹钟

    使用 Windows Script Host (WSH) 对象模型中的计时器对象来实现。 以下是一个示例脚本,它可以设置多个定时器并具有重复响铃功能: vbscript Set objShell = CreateObject("WScript.Shell") ' 定义闹钟列表 Dim alarms(2) alarms(0) = "08:00:00" ' 第一个闹钟时间 alarms(1) = "12:30:00" ' 第二个闹钟时间 ' 定义重复响铃的次数 Dim repeatCount repeatCount = 3 ' 每个闹钟响铃3次 ' 处理每个闹钟 For Each alarm In alarms ' 获取当前时间和闹钟时间 currentTime = Time alarmTime = CDate(alarm) ' 计算下一个闹钟时间 If alarmTime < currentTime Then nextAlarm = DateAdd("d", 1, Date) & " " & alarm Else nextAlarm = Date & " " & alarm End If ' 计算闹钟触发时间间隔(毫秒) interval = DateDiff("s", Now, CDate(nextAlarm)) * 1000 ' 设置定时器并触发闹钟 Set objTimer = CreateObject("WScript.Timer") objTimer.Interval = interval WScript.Sleep interval For i = 1 To repeatCount objShell.Popup "闹钟时间:" & alarm & vbCrLf & "响铃次数:" & i, , "闹钟" WScript.Sleep 1000 ' 1秒钟的延迟 Next Next Set objTimer = Nothing 这个脚本使用一个数组来存储闹钟时间,您可以根据需要添加或修改闹钟。 每个闹钟的重复响铃次数由 repeatCount 变量控制,您可以根据需要进行调整。 脚本中的 objShell.Popup 语句用于显示弹出窗口,以模拟闹钟的铃声。 您可以根据需要修改弹出窗口的内容和样式。 要运行这个 VBScript 脚本,您可以将其保存为后缀名为 .vbs 的文件,然后双击运行。 脚本将按照设置的闹钟时间触发弹出窗口并进行重复响铃。

    设置定时闹钟的日期,而不仅仅是时间

    Set objShell = CreateObject("WScript.Shell") ' 定义闹钟列表 Dim alarms(2) alarms(0) = "2023-11-13 08:00:00" ' 第一个闹钟日期和时间 alarms(1) = "2023-11-14 12:30:00" ' 第二个闹钟日期和时间 ' 定义重复响铃的次数 Dim repeatCount repeatCount = 3 ' 每个闹钟响铃3次 ' 处理每个闹钟 For Each alarm In alarms ' 获取当前日期和时间 currentDateTime = Now alarmDateTime = CDate(alarm) ' 计算下一个闹钟日期和时间 If alarmDateTime < currentDateTime Then nextAlarm = DateAdd("d", 1, alarm) Else nextAlarm = alarm End If ' 计算闹钟触发时间间隔(毫秒) interval = DateDiff("s", Now, CDate(nextAlarm)) * 1000 ' 设置定时器并触发闹钟 Set objTimer = CreateObject("WScript.Timer") objTimer.Interval = interval WScript.Sleep interval For i = 1 To repeatCount objShell.Popup "闹钟日期和时间:" & alarm & vbCrLf & "响铃次数:" & i, , "闹钟" WScript.Sleep 1000 ' 1秒钟的延迟 Next Next Set objTimer = Nothing 在这个修改后的脚本中,闹钟的日期和时间被存储在 alarms 数组中。您可以按照 "YYYY-MM-DD HH:mm:ss" 的格式设置日期和时间。如果闹钟的日期早于当前日期和时间,脚本将自动将其设置为下一天。 请注意,为了在日期和时间之间进行比较和计算,脚本使用了 Now 函数获取当前日期和时间,以及 CDate 函数将字符串转换为日期和时间类型。 保存并运行修改后的脚本,它将按照设置的日期和时间触发弹出窗口并进行重复响铃。

    从文本文件中读取闹钟的日期和时间

    使用 VBScript 中的文件操作功能。 Set objShell = CreateObject("WScript.Shell") ' 读取闹钟日期和时间的文本文件路径 Dim filePath filePath = "C:\Path\to\alarms.txt" ' 打开文本文件并读取闹钟日期和时间 Set objFSO = CreateObject("Scripting.FileSystemObject") Set objFile = objFSO.OpenTextFile(filePath, 1) ' 1 表示以只读模式打开文件 ' 存储闹钟日期和时间的数组 Dim alarms() i = 0 ' 逐行读取文本文件并存储闹钟日期和时间 Do Until objFile.AtEndOfStream alarm = objFile.ReadLine() ReDim Preserve alarms(i) alarms(i) = alarm i = i + 1 Loop ' 关闭文件 objFile.Close Set objFile = Nothing Set objFSO = Nothing ' 定义重复响铃的次数 Dim repeatCount repeatCount = 3 ' 每个闹钟响铃3次 ' 处理每个闹钟 For Each alarm In alarms ' 获取当前日期和时间 currentDateTime = Now alarmDateTime = CDate(alarm) ' 计算下一个闹钟日期和时间 If alarmDateTime < currentDateTime Then nextAlarm = DateAdd("d", 1, alarm) Else nextAlarm = alarm End If ' 计算闹钟触发时间间隔(毫秒) interval = DateDiff("s", Now, CDate(nextAlarm)) * 1000 ' 设置定时器并触发闹钟 Set objTimer = CreateObject("WScript.Timer") objTimer.Interval = interval WScript.Sleep interval For i = 1 To repeatCount objShell.Popup "闹钟日期和时间:" & alarm & vbCrLf & "响铃次数:" & i, , "闹钟" WScript.Sleep 1000 ' 1秒钟的延迟 Next Next Set objTimer = Nothing 在这个示例脚本中,您需要将 filePath 变量设置为包含闹钟日期和时间的文本文件的路径。 脚本将打开该文件并逐行读取闹钟的日期和时间,然后存储在 alarms 数组中。 注意,文本文件中的每一行应包含一个闹钟的日期和时间,按照您希望的格式进行存储,例如 "YYYY-MM-DD HH:mm:ss"。 每个闹钟的日期和时间应占据单独的一行。 保存并运行修改后的脚本,它将从文本文件中读取闹钟的日期和时间,并根据设置的日期和时间触发弹出窗口并进行重复响铃。

    To split a string by a tab regular expressions

    use the Split function along with a regular expression pattern. Dim regex, inputString, splitArray ' Input string with tabs inputString = "Hello" & vbTab & "World" & vbTab & "123" ' Create a regular expression pattern for matching tabs Set regex = New RegExp regex.Pattern = vbTab ' Split the string using the regular expression pattern splitArray = Split(regex.Replace(inputString, ";"), ";") ' Display the split values For Each item In splitArray WScript.Echo item Next The regex.Replace method is used to replace all occurrences of tabs with a semicolon ;. Then, the Split function is used to split the modified string using the semicolon as the delimiter. The result is stored in the splitArray variable. Finally, you can iterate over the splitArray to display each individual split value.

    .Popup method

    Dim WshShell, answer Set WshShell = WScript.CreateObject("WScript.Shell") answer = WshShell.Popup("Do you feel alright?", 7, "Answer This Question:", 4 + 32) Select Case answer case 6 WScript.Echo "Glad to hear you feel alright." case 7 WScript.Echo "Hope you're feeling better soon." case -1 WScript.Echo "Is there anybody out there?" End Select While WshShell.Popup("popup 2 secs without buttons", 2, "Title", buttonType) <> -1 WEnd

    the purpose of the colon

    e. g. Dim objConn : Set objConn = OpenConnection() the colon used to combine the two statements into one line the code would work exactly the same on two lines; the colon's just a statement separator.

    CreateObject

    CreateObject Create an automation object / run an external command CreateObject (strProgid [,strPrefix]) Depending on what software you've installed, you will already have hundreds if not thousands of COM objects available to play with. One way to see what's available such list is by looking under Tools> References in the VBA editor within Word or other Office products. Then include a reference, and go to the Object Browser to see its methods and properties. If you don't have Office installed, there are other ways to list the COM interfaces on your machine using VBScript. Take a look at Rob van der Woude's VBScript Scripting Techniques - Editors, IDEs & Object Browsers page where he describes some programs that provide an object browser. He also gives a script that shows how to list ProgIds from your registry. I have over 3000 on my machine. Not all will have scriptable interfaces, but many will. .NET alone has hundreds of useful objects, and all are documented on MSDN. Once you have an interesting looking ProgId, do a Google search to find more about it.

    example CreateObject() object List for vbs

    CreateObject("ADODB.Command") CreateObject("ADODB.Connection") CreateObject("ADODB.Recordset") CreateObject("ADODB.Stream") CreateObject("Excel.Application") WScript.CreateObject("Excel.Application") CreateObject("InternetExplorer.Application") WScript.CreateObject("InternetExplorer.Application") CreateObject("iTunes.Application") CreateObject("Outlook.Application") CreateObject("Powerpoint.Application") CreateObject("Shell.Application") CreateObject("Word.Application") For Each IE In CreateObject("Shell.Application").windows CreateObject("CDO.Message") CreateObject("htmlfile") 'To parse data from html tags CreateObject("InetCtls.Inet.1") CreateObject("Microsoft.Update.Searcher") CreateObject("Microsoft.XmlDom") CreateObject("MSCAL.Calendar") CreateObject("MSSOAP.SOAPClient") CreateObject("Msxml2.DOMDocument.5.0") CreateObject("MSXML2.XMLHTTP") 'To sent xmlhttp request to webserver & get html code CreateObject("Msxml2.XMLHttp.6.0") CreateObject("objectname") CreateObject("QuattroPro.PerfectScript") CreateObject("rmocx.RealPlayer G2 Control.1") CreateObject("SAFRCFileDlg.FileOpen") CreateObject("SAFRCFileDlg.FileSave") CreateObject("sapi.spvoice") CreateObject("Scripting.Dictionary") CreateObject("Scripting.FileSystemObject") CreateObject("Scripting.FileSystemObject").GetStandardStream(1) CreateObject("System.Collections.ArrayList") CreateObject("System.Collections.SortedList") CreateObject("System.Random") CreateObject("System.Text.StringBuilder") CreateObject("UltraWOL.ctlUltraWOL") CreateObject("UserAccounts.CommonDialog") CreateObject("vbscript.regexp") CreateObject("WbemScripting.SWbemLocator") CreateObject("WinHttp.WinHttpRequest.5.1") CreateObject("WMPlayer.OCX") CreateObject("WMPlayer.OCX.7") CreateObject("WordPerfect.PerfectScript") CreateObject("Wscript.Network") CreateObject("Wscript.Shell") CreateObject("WScript.Shell").Run "Your-VBScript-Here" CreateObject("WScript.Timer") CreateObject(servername.typename[,location]) Set colItems = objWMIService.ExecQuery ("Select * from Win32_Process Where Name = 'cscript.exe' OR Name = 'wscript.exe'") taskkill /F /IM wscript.exe /T taskkill /fi "imagename eq cscript.exe" (change to wscript.exe as needed) With CreateObject("WMPlayer.OCX") with CreateObject("WScript.Shell") Wscript.ConnectObject oMyObject, "eventhandler_" WScript.CreateObject("WSCript.shell") Wscript.Createobject("MyObject.MyClass") Wscript.Createobject("MyObject.MyClass","eventhandler_") WScript.CreateObject("Scripting.FileSystemObject") WScript.CreateObject("WScript.Shell") WScript.CreateObject("WScript.Shell") WshShell.Run "notepad", 9 Wscript.DisconnectObject(oMyObject) Wscript.Echo "Cool" WScript.Echo Escape(VbCrLf) WScript.Echo item WScript.Echo Join( arrProgID, vbCrLf ) wscript.exe C:\Scripts\helloworld.js WScript.Exec("Test_To_Block.vbs") WScript.GetObject Wscript.GetObject(strPathname [,strProgID] ], [strPrefix]) Wscript.Quit WScript.ScriptName Wscript.Shell WScript.Sleep 100 WScript.Sleep interval WScript.Sleep timerDuration WScript.Sleep(100) WScript.StdOut Wscript.StdOut.Write "Your name is: " & Wscript.StdIn.ReadLin WScript.StdOut.Write Chr(7) WScript.StdOut.Write("text string to display") WScript.StdOut.WriteLine "Hello" Wscript.Timer WSHNetwork = CreateObject("Wscript.Network") WSHshell = CreateObject("Wscript.Shell") WshShell.Run "%windir%\notepad " & WScript.ScriptFullName WshShell.Run "taskkill /f /im wscript.exe", , True WshShell.Run "notepad", 9

    debug stand-alone VBScript script

    Run cscript.exe for full command args cscript //X scriptfile.vbs MyArg1 MyArg2 will run the script in a debugger In order to debug vbs file, specify "//D //X" options in script host. Both Windows-based script host (wscript.exe) and Command-based script host (cscript.exe) supports the same options. When //D //X options are specified, Visual Studio debugger will be launched and start debugging for the VB script. Microsoft Script Debugger relatively minimal debugger for Windows Script Host-supported scripting languages, such as VBScript and JScript. Its user interface allows the user to set breakpoints and/or step through execution of script code line by line, and examine values of variables and properties after any step. Microsoft considers it to be deprecated. The Microsoft Script Editor (MSE or "MSE.EXE" or "mse7.exe" in Office 2003) is an optional tool included in Microsoft Office

    VBA爬网页数据

    方法1 :CreateObject(“InternetExplorer.Application”)

    Sub 方法1() url = "https://www.csdn.net/" Set ie = CreateObject("InternetExplorer.Application") With ie .Visible = False .navigate url Do Until .readystate - 4 DoEvents Loop Set oDom = .document End With Debug.Print oDom.getElementsByTagName("p")(0).innertext End Sub PS:此方法会打开浏览器读取数据,虽然我们看不到打开浏览器是因为设置的:.Visible = False不可见,实际在后台操作。 并且需要等待浏览器返回数据的时间,不然可能会跳出错误。

    方法2 :CreateObject(“WinHttp.WinHttpRequest.5.1”)

    Sub 方法2() url = "https://www.csdn.net/" Set xmlHttp = CreateObject("WinHttp.WinHttpRequest.5.1") Set oDom = CreateObject("htmlFile") With xmlHttp .Open "GET", url, False .send oDom.body.innerHTML = .ResponseText End With Debug.Print oDom.getElementsByTagName("p")(0).innertext End Sub PS: 1、此方法如果P标签内为汉字,返回的为乱码, 2、使用WPS用户访问外部网站会跳出安全频道的错误,局域网网址并不会出现,此问题暂时无解。

    方法3:CreateObject(“msxml2.xmlhttp”)

    Sub 方法3() Dim oDom As Object url = "https://www.csdn.net/" Set oDom = CreateObject("htmlFile") Set ms = CreateObject("msxml2.xmlhttp") With ms .Open "GET", url, True .send oDom.body.innerHTML = .responseText End With Debug.Print oDom.getElementsByTagName("p")(1).innertext End Sub PS: 1、msxml2可以自动适应字符乱码问题,兼容性较强。 2、缺点对于对于已经访问的 网站,如果网站内更新的内容,仍然是以前的老数据。 原因msxml2是读取的上次缓存的数据才造成的。 解决方案:程序运行前先清空浏览器缓存。 使用:Shell "RunDll32.exe InetCpl.cpl,ClearMyTracksByProcess 8 "。 如果不行,请自行测试下其他方式,注释及方法纯个人理解,难免有差错。 Sub Clear_Temp_Files() Shell "RunDll32.exe InetCpl.cpl,ClearMyTracksByProcess 8 " '清除临时文件 End Sub Sub Clear_Cookies() Shell "RunDll32.exe InetCpl.cpl,ClearMyTracksByProcess 2" '清除Cookies End Sub Sub Clear_History() Shell "RunDll32.exe InetCpl.cpl,ClearMyTracksByProcess 1" '清除历史记录 End Sub Sub Clear_Form_Data() Shell "RunDll32.exe InetCpl.cpl,ClearMyTracksByProcess 16" '清除表单数据 End Sub Sub Clear_Saved_Passwords() Shell "RunDll32.exe InetCpl.cpl,ClearMyTracksByProcess 32" '清除记住的账号密码 End Sub Sub Clear_All() Shell "RunDll32.exe InetCpl.cpl,ClearMyTracksByProcess 255" '清除所有 End Sub Sub Clear_Clear_Add_ons_Settings() Shell "RunDll32.exe InetCpl.cpl,ClearMyTracksByProcess 4351" '清除创建默认设置 End Sub

    方法4: CreateObject(“Msxml2.ServerXMLHTTP”)

    Sub 方法3() Dim oDom As Object url = "https://www.csdn.net/" Set oDom = CreateObject("htmlFile") Set ms = CreateObject("Msxml2.ServerXMLHTTP") With ms .Open "GET", url, False .send oDom.body.innerHTML = .responseText End With Debug.Print oDom.getElementsByTagName("p")(1).innertext End Sub PS: 1、与方法3基本一致,唯一不同是加上此方法不会造成数据缓存的问题,保证读取的数据都是最新的。 2、和方法2问题一样WPS用户访问外部网站会跳出安全频道的错误,局域网网址并不会出现,此问题暂时无解

    解决CreateObject(“WinHttp.WinHttpRequest.5.1”)乱码问题

    Function UrlFile(Url, Ucode) '获取网页源文件(网址,编码) Dim oServerXmlHttp, ObjStream, oStream Set oServerXmlHttp = CreateObject("WinHttp.WinHttpRequest.5.1") oServerXmlHttp.Open "GET", Url, False oServerXmlHttp.send oStream = oServerXmlHttp.responseBody If Not IsEmpty(oStream) Then If InStr(1, oServerXmlHttp.getResponseHeader("content-type"), "charset", 1) Then '通过判断"content-type"是否有"charset"字符串来决定是否根据参数2转码(文本比较——不区分大小写) UrlFile = oServerXmlHttp.responseText Else Set ObjStream = CreateObject("Adodb.Stream") 'With...end with省略对象不可写在判断内 ObjStream.Type = 1 ObjStream.Mode = 3 ObjStream.Open ObjStream.Write oStream ObjStream.Position = 0 ObjStream.Type = 2 ObjStream.Charset = Ucode UrlFile = ObjStream.ReadText End If Else UrlFile = "" End If Set ObjStream = Nothing: Set oServerXmlHttp = Nothing End Function Sub 读取整个网页() tex = UrlFile("https://www.csdn.net/", "UTF-8") Debug.Print tex End Sub

    其他问题(获取某个标签的值)

    使用以下方法时有时会出现自动打开网页问题:
    方法2 :CreateObject(“WinHttp.WinHttpRequest.5.1”)
    方法3:CreateObject(“msxml2.xmlhttp”)
    方法4: CreateObject(“Msxml2.ServerXMLHTTP”)
    后来发现是oDom在作怪,在oDom.body.innerHTML = .ResponseText数据转换时会发生。 解决方案: 不使用oDOM,使用正则表达式取值,假如我要取所有P标签的值,如下 Part = .responseText Set re = CreateObject("VBScript.RegExp") re.Pattern = "<p.*>(.*?)</p>" 're.Pattern = "p>.*[\s\S]*</p" re.Global = True re.IgnoreCase = False Set matchs = re.Execute(OrgStr) For Each m In matchs Debug.Print m.submatches(0) Next 完结

    change CurrentDirectory

    Set objShell = CreateObject("Wscript.Shell") Wscript.Echo objShell.CurrentDirectory objShell.CurrentDirectory = "C:\Windows" Wscript.Echo objShell.CurrentDirectory shell.currentdirectory = "c:\Deploy\" shell.Run("""c:\Deploy\MainForm.exe""") Dim oShell : Set oShell = CreateObject("WScript.Shell") oShell.CurrentDirectory = ".\backup" Set fso = CreateObject("Scripting.FileSystemObject") currentPath = fso.GetAbsolutePathName(".") Set fso = CreateObject("Scripting.FileSystemObject") Set f1 = fso.GetFolder(".") ' Returns the current directory Set f2 = fso.GetFolder(".\backup") ' Returns the "backup" directory under the current directory

    Download a file with VBS

    https://stackoverflow.com/questions/2973136/download-a-file-with-vbs using XMLHTTP and leverage an ADO stream to write the binary data; dim xHttp: Set xHttp = createobject("Microsoft.XMLHTTP") dim bStrm: Set bStrm = createobject("Adodb.Stream") xHttp.Open "GET", "http://example.com/someimage.png", False xHttp.Send with bStrm .type = 1 '//binary .open .write xHttp.responseBody .savetofile "c:\temp\someimage.png", 2 '//overwrite end with The above answer threw the error Write to file failed. Code: 800A0BBC, however this worked: HTTPDownload "http://www.emagcloud.com/europeansealing/FSA_ESA_Compression_Packing_Technical_Manual_v3/pubData/source/images/pages/page10.jpg", "C:\" Where Sub HTTPDownload( myURL, myPath ) ' This Sub downloads the FILE specified in myURL to the path specified in myPath. ' ' myURL must always end with a file name ' myPath may be a directory or a file name; in either case the directory must exist ' ' Written by Rob van der Woude ' http://www.robvanderwoude.com ' ' Based on a script found on the Thai Visa forum ' http://www.thaivisa.com/forum/index.php?showtopic=21832 ' Standard housekeeping Dim i, objFile, objFSO, objHTTP, strFile, strMsg Const ForReading = 1, ForWriting = 2, ForAppending = 8 ' Create a File System Object Set objFSO = CreateObject( "Scripting.FileSystemObject" ) ' Check if the specified target file or folder exists, ' and build the fully qualified path of the target file If objFSO.FolderExists( myPath ) Then strFile = objFSO.BuildPath( myPath, Mid( myURL, InStrRev( myURL, "/" ) + 1 ) ) ElseIf objFSO.FolderExists( Left( myPath, InStrRev( myPath, "\" ) - 1 ) ) Then strFile = myPath Else WScript.Echo "ERROR: Target folder not found." Exit Sub End If ' Create or open the target file Set objFile = objFSO.OpenTextFile( strFile, ForWriting, True ) ' Create an HTTP object Set objHTTP = CreateObject( "WinHttp.WinHttpRequest.5.1" ) ' Download the specified URL objHTTP.Open "GET", myURL, False objHTTP.Send ' Write the downloaded byte stream to the target file For i = 1 To LenB( objHTTP.ResponseBody ) objFile.Write Chr( AscB( MidB( objHTTP.ResponseBody, i, 1 ) ) ) Next

    display an image in vbscript

    Dim iURL Dim objShell iURL = "https://storage.googleapis.com/pai-images/6fd3acaec2c241e6b1a2076003a5b260.jpeg" set objShell = CreateObject("WScript.Shell") objShell.run(iURL) if chrome is not default: set objShell = CreateObject("Shell.Application") objShell.ShellExecute "chrome.exe", iURL, "", "", 1

    Web Scraping Demo Script

    'Web Scraping Demo Script option Explicit dim myBrowser, i, s, allData, data, line ' The SeeShell Browser for Web Automation ' https://ui.vision/download/seeshell-browser set myBrowser = CreateObject ("seeshell.browser") If myBrowser Is Nothing Then msgbox ("API not installed") i = myBrowser.open(true) if i < 0 then msgbox ("Start error: " + cstr(i) +" " +myBrowser.getLastError()) i = myBrowser.echo ("Processing...") i = myBrowser.Play("demo-webscraping") if i < 0 then msgbox "Error playing macro: " + cstr(i) + vbCrLf + vbCrLf +"Text: "+myBrowser.getLastError() 'Stop here i = myBrowser.close() WScript.Quit(i) end if i = myBrowser.echo ("Done!") 'Display all data allData = myBrowser.GetExtractImageData() s = "Extraction done - this is how the raw returned data looks like:"+vbCrLf+vbCrLf s = s+ allData+vbCrLf+vbCrLf s = s + "Press OK to display the exchange rates." msgbox s 'The data is separated by [REC] for each line, and by [DATA] for each line (if there is more than one pink frame) 'http://stackoverflow.com/questions/14103510/split-function-on-an-array data = Split(allData, "[DATA]") 'In this case we ignore all the extracted HTML and URLs, this is only in the macro for demo purposes 'In this script, we only care and display the extracted TEXT data - the exchange rate 'line 0 - BTC HTML code 'line 1 - BTC Text... we need this 'line 2 - BTC Link... not needed 'line 3 - OCR'ed result (here the same as the text, but OCR works even with images and PDF) 'line 4 - Currency rates - needed msgbox "Today's Bitcoin/US$ exchange rate is "+data(0) 'FIRST element has index = 0 s= "Today's currency exchange rates are"+vbCrLf+vbCrLf dim iStartPos iStartPos = 6 s = s+"USD/EUR: "+data(iStartPos+1)+vbCrLf s = s+ "USD/GBP: "+data(iStartPos+3)+vbCrLf s = s+ "USD/CNY: "+data(iStartPos+5)+vbCrLf s = s+ "EUR/GBP: "+data(iStartPos+4)+vbCrLf s = s+ "EUR/CNY: "+data(iStartPos+0)+vbCrLf s = s+ "GBP/CNY: "+data(iStartPos+2) +vbCrLf+vbCrLf s= s+ "In the next step, the data will be saved (appended) to a CSV file." msgbox s 'SAVE TO CSV FILE Dim sOut, fso, objFile Const ForAppending = 8 sOut = "./exchangerates.txt" Set fso = CreateObject("Scripting.fileSystemObject") Set objFile = fso.OpenTextFile( sOut, ForAppending, True ) 'Same "Today's exchange rates" to a file in CSV format s = FormatDateTime(Now) + ","+ data(iStartPos+0) + "," + data(iStartPos+1) + "," + data(iStartPos+2) + "," + data(iStartPos+3) + "," + data(iStartPos+4) + "," + data(iStartPos+5) objFile.WriteLine(s) objFile.Close Set fso = Nothing msgbox ("Data saved. Press OK to close the SeeShell Browser.") i = myBrowser.close() WScript.Quit(i)

    run a VBS script from R and pass arguments

    write the VBS as follows: Dim Msg_Text Msg_Text = WScript.Arguments(0) MsgBox("Hello " & Msg_Text) create a system command in R like this: system_command <- paste("WScript", '"Msg_Script.vbs"', '"World"', sep = " ") system(command = system_command, wait = TRUE) Using named arguments: Dim Msg_Text Msg_Text = WScript.Arguments.Named.Item("Msg_Text") MsgBox("Hello " & Msg_Text) create a system command in R like this: system_command <- paste("WScript", '"Msg_Script.vbs"', '/Msg_Text:"World"', sep = " ") system(command = system_command, wait = TRUE)

    Adding a GUI to VBScript

    VBScript has dialogs, only not many and no checkboxes, you would need a COM object to do so (and there are). Dim WshShell, BtnCode Set WshShell = WScript.CreateObject("WScript.Shell") BtnCode = WshShell.Popup("Do you feel alright?", 7, "Answer This Question:", 4 + 32) Select Case BtnCode case 6 WScript.Echo "Glad to hear you feel alright." case 7 WScript.Echo "Hope you're feeling better soon." case -1 WScript.Echo "Is there anybody out there?" End Select However, the best way to have more dialogs in vbscript is using HTA which is rubbish too. Take a look at Ruby, the start is easy to learn an it is FUN. Here an example of u ruby script using shoes as GUI require 'green_shoes' Shoes.app{ button("Click me!"){alert("You clicked me.")} } EDIT: since my Ruby alternative rises some questions, here a more traditionel way closer to Vbscript uses of the same sample. The sample above is used more for a functional chained way of programming. require 'green_shoes' Shoes.app do button("Click me!") do alert("You clicked me.") end end

    vbscript Looping through a form to get field names and filed values

    For Each Item In Request.Form fieldName = Item fieldValue = Request.Form(Item) Response.Write(""& fieldName &" = Request.Form("""& fieldName &""")") Next To test receiving correct input, change Response.Write to Response.Write fieldName & " = " & fieldValue & "
    " Here's a Dictionary Object to put field names and field values together: Dim Item, fieldName, fieldValue Dim a, b, c, d Set d = Server.CreateObject("Scripting.Dictionary") For Each Item In Request.Form fieldName = Item fieldValue = Request.Form(Item) d.Add fieldName, fieldValue Next ' Rest of the code is for going through the Dictionary a = d.Keys ' Field names ' b = d.Items ' Field values ' For c = 0 To d.Count - 1 Response.Write a(c) & " = " & b(c) Response.Write "
    " Next VBScript code to add validation functionality to a Web page Paste the following code in a new text file, save the file with an .htm extension, and then double-click the file to view it in a browser. The HTML code is for a text box and a button. Return result will be submitted to a server. <html> <head><title>Simple Validation</title> <SCRIPT LANGUAGE="VBScript"> <!-- Sub Validate Dim TheForm Set TheForm = Document.forms("ValidForm") If IsNumeric(TheForm.Text1.Value) Then If TheForm.Text1.Value < 1 Or TheForm.Text1.Value > 10 Then MsgBox "Please enter a number between 1 and 10." Else MsgBox "Thank you." End If Else MsgBox "Please enter a numeric value." End If End Sub--> </script> </head> <body> <H3>Simple Validation</H3> <form id="ValidForm" action="nothing.asp" onsubmit="Validate(); return false;" language="jscript"> Enter a value between 1 and 10: <input name="Text1" TYPE="TEXT" SIZE="2"> <input name="Submit" TYPE="Submit" VALUE="Submit"> </form> </body> </html>

    Clipboard in vbscript

    html object to retrieve the contents of the clipboard ' Get clipboard text Set objHTML = CreateObject("htmlfile") text = objHTML.ParentWindow.ClipboardData.GetData("text") 'use this snippet to put text back on the clipboard, but it needs third party software; a standalone executable clip.exe which can be found on Windows 2003 Server or just on the internet ' Do something with the text text = replace(text, "you ", "you and your dog ") ' Put it back to the clipboard Set WshShell = CreateObject("WScript.Shell") Set oExec = WshShell.Exec("clip") Set oIn = oExec.stdIn oIn.WriteLine text oIn.Close Here's a code snippit (Outp. is a text stream) VBScript doesn't support the clipboard. Most hosts host vbscript, therefore vbscript running in IE or an HTA can use IE's clipboard support. The scripting hosts do not give clipboard support. You can use a vbs file to start IE through COM automation, navigate to a local page (to bypass security warnings), then use IE's clipboard. Set ie = CreateObject("InternetExplorer.Application") ie.Visible = 0 ie.Navigate2 "C:\Users\David Candy\Desktop\Filter.html" Do wscript.sleep 100 Loop until ie.document.readystate = "complete" txt=ie.document.parentwindow.clipboardData.GetData("TEXT") ie.quit If IsNull(txt) = true then outp.writeline "No text on clipboard" else outp.writeline txt End If 'TO CLEAR ClipBoard("") 'TO SET ClipBoard("Hello World!") 'TO GET Result = ClipBoard(Null) Function ClipBoard(input) '@description: A quick way to set and get your clipboard. '@author: Jeremy England (SimplyCoded) If IsNull(input) Then ClipBoard = CreateObject("HTMLFile").parentWindow.clipboardData.getData("Text") If IsNull(ClipBoard) Then ClipBoard = "" Else CreateObject("WScript.Shell").Run _ "mshta.exe javascript:eval(""document.parentWindow.clipboardData.setData('text','" _ & Replace(Replace(Replace(input, "'", "\\u0027"), """","\\u0022"),Chr(13),"\\r\\n") & "');window.close()"")", _ 0,True End If End Function For the equivalent of a "paste" operation I would run a command-line utility like ClipOut or paste, redirect output to a file and read the file contents. return = WshShell.Run("cmd /c clipout.exe > output.txt", 0, true) Set fso = CreateObject("Scripting.FileSystemObject") Set file = fso.OpenTextFile("output.txt", 1) text = file.ReadAll file.Close You can get ClipOut here: http://jasonfaulkner.com/ClipOut.aspx You can get paste here: https://www.c3scripts.com/tutorials/msdos/paste.html For the equivalent of a "copy" operation I would use the clip command line utility that actually comes with Windows and similar code as above. About the clip utility: https://blogs.msdn.microsoft.com/oldnewthing/20091110-00/?p=16093

    list of useful WScript properties

    Properties of the WScript object: WScript.Application This property is read only and returns a reference to the current WScript instance. WScript.BuildVersion This property is read only and returns a Long value which is the build version number of cscript (or wscript). WScript.FullName This property returns the full path to cscript (or wscript). This property is read only. WScript.Interactive [= True|False] The Interactive property returns a Boolean that indicates if cscript (or wscript) was invoked in interactive mode. This property is read/write and can be used to change the mode of the currently executing script at runtime. When this property is False, the interactive commands Echo, MsgBox and InputBox have no effect. WScript[.Name] The Name property is read only and returns the name of the WScript object (usually "Windows Script Host"). This is the default property of the WScript object. WScript.Path This property is read only and returns the full path to the directory containing cscript (or wscript). WScript.ScriptFullName This property is read only and returns the full path to the script currently being executed. WScript.ScriptName This property is read only and returns the filename of the script currently being executed. WScript.StdErr This property returns a TextStream object that outputs text to the Standard Error stream. This property is read only and can only be used when cscript is the host executable. WScript.StdIn The StdIn property returns a TextStream object that reads text from the Standard Input stream. This property is read only and can only be used when cscript is the host executable. WScript.StdOut This property returns a TextStream object that outputs text to the Standard Output stream. This property is read only and can only be used when cscript is the host executable. WScript.Timeout[ = lngTimeout] This property is used to set or get the timeout period (in seconds) for the currently executing script. The script will automatically be terminated after the number of seconds specified by this property, which is of type Long. WScript.Version This property is read only and returns a string that is the version number of the host executable. Examples 'Output the version of Microsoft Windows Script Host. strVer = WScript.Version WScript.Echo strVer 'Output the full path-name of the currently running script. strFull = WScript.ScriptFullName WScript.Echo strFull 'The Application property returns a reference to the current instance of the WScript object. Set objWScript = WScript.Application If WScript = objWScript Then WScript.Echo "This proves they refer to the same thing" End If

    VB Lectures



    https://staff.cdms.westernsydney.edu.au/~jianhua/SAP_300165/lectures/Lecture___1.html

    Lecture 1 Scripting Concepts

    Key words WSH (Windows Script Host), VBScript (short for Visual Basic Scripting Edition). Download the script: Sample1.vbs. Save it in any folder and double click it. By the way, you have to work with Windows (hopefully the version is no earlier than Windows 2000). You will see "I am Jamie Yang!" in a small window. Otherwise, you might have to reinstall your operating system. Of course, you are not 'Jamie Yang'. Right click the file and choose Edit. You will open it in Notepad. Change 'Jamie Yang' to your name. Run it again - does it display your name? If succeeded, try on another one: Sample2.vbs. What do we mean by scripting? "For the purposes of this book, scripting refers to the act of creating, executing, and utilizing small computer programs that are written in a high-end scripting language, specifically, VBScript." Not really. VBScript is just one of the many scripting languages. There are plenty of others, some for unix, some for Windows, and some for both. Examples of scripting languages are Perl, php, shell script, JScript, JavaScript, .... In this subject, we will use VBScript for Windows and Perl for Unix. By the way, is there any link between VBScript and Visual Basic, also JavaScript and Java? Yes, there is. VBScript can be viewed as a lightweight version of VB and JavaScript can be viewed as a lightweight version of Java. If you do not agree, think in this way - they are similar in syntax at least. However, unlike C and C++, none of the pairs is compatible. What about JavaScript and JScript? JScript is Windows' version of JavaScript. It is more C style. VB is one of the simplest programming languages, compared to Java, C, and C++. VBScript is even simpler. Therefore we are learning probably the simplest programming language in the world. Common characteristics of scripting languages: 1. Interpreted: the scripting engine reads each line of script, one at a time, and executes it. 2. Text-based: program itself is a text file. 3. Native: mostly a scripting language can only be used for certain purposes or with certain operating systems. 4. Easy to deploy: lightweight. The environment running VBScript programs Like VB and Java, VBScript is an interpreted language, which means that the program itself is not runnable. It needs another program to execute it. This program is Windows Script Host (WSH). The WSH architecture is shown in the figure below: WSH is a built-in component of Windows 2000, Windows XP, Windows Server 2003, Windows Vista, and later versions of Windows. If you have an early version of Windows, you need to download a file WScript.exe or CScript.exe from Microsoft. WScript.exe is window-based WSH environment, and CScript.exe sets up a command-line style of WSH interpreter. Try this: 1.Open a command-line window. 2.Change directory to the folder where the script sample1.vbs is. 3.Enter: CScript sample1.vbs. You will see the same message appears in the command-line window as you have seen by double clicking the program. Trust me. CScript.exe is useful when you debug a program. We can do more things using VBScript VBScript is completely capable of utilizing COM, the Component Object Model, which makes VBScript powerful. You can get a COM object by using the function: GetObject(). As such you can use almost all Windows' functionalities as well as other Microsoft applications' functionalities packaged in COM. Try this: Download the script, SerialNoOS.vbs, and execute it. This script tells you the serial number of your Windows operating system. Of course, you need a good knowledge of Windows systems to know where the information is stored. At least, you now know where it is. So try more, know more. Here is another one. Download the script, WhoOpened.vbs, and execute it. The language itself isn't complicated, is it? However, to do a better job, we need to use some appropriate functionalities/services of the operating system. How to locate the relevant functionalities for carrying out a task? This could be the scary point of learning VBScript. A good thing is that you don't have to know everything about the operating system. Most administrative tasks are quite routine. You only need to know a few facts. Then you use them every day. Or once a job is done, it works forever. This is what we want to achieve with this subject. I have to remind you that the power of VBScript can be used not only for beneficial administrative tasks, but also for malicious hacking, and many viruses are based on VBScript or other AcvtiveX scripting languages. That's all for today. Now have a cup of tea?

    Lecture 2 VBScript Basics

    Did you enjoy the first lecture? Trust you did - at least you enjoyed your coffee. VBScript is powerful and mostly used by computing professionals. While you can write some fairly simple scripts, you can also write sophisticated scripting code. In this lecture, we will learn the basics of VBScript - working with variables, calling functions, controlling structures etc. Key words Variable, Function, Procedure/Subroutine, Control Structure Another common practice is referencing to online VBScript tutorials if necessary. This is very handy, and there are heaps of tutorial lessons over the Web - why don't we share the experience? In fact, the lecture notes cannot cover everything in details. I just pick the most important issues and explain them with examples. Since you have done at least Programming Fundamentals, you know C++. What you need to know are the differences of the language basics between C++ and VBScript. Variables Variables are used to store data. Note that data can be anything from characters, strings, integers to encapsulated objects. Different from the general purpose languages, such as C, C++, and Java, VBScript is not a strongly typed language, which means that you don't have to tell the interpreter what type of data you are going to store in the variable you define. You can simply use Dim to declare any variables: Dim myInteger Dim myDouble Dim myObject The rules for variable names are similar to other languages but they are not case sensitive (see Textbook page 80). Strange enough, you even don't have to declare a variable. Download the script, variables1.vbs, and run it. Also Download the script, variables2.vbs, and run it. However, good scripts are planned. It's better to declare the variables that you are going to use. VBScript provides a simple statement 'Option Explicit' to tighten up your scripts, which says that: if a variable is not declared, then you cannot use it. (see Textbook page 81). A variable can also store an array of elements. See the following example. Please pay attention to the declaration of an array variable and assignment of elements to the array. Dim aList(3) aList(0) = "Monday" aList(1) = "Tuesday" aList(2) = "Wednesday" aList(3) = "Thursday" In this code, Dim aList(3) defines an array with Four members. If you do not believe that you can store four members in it, Download the script, array1.vbs, and execute it. Alternatively, we do the same thing as follows: Dim aList aList = Array("Monday","Tuesday","Wednesday","Thursday") Practice it with array2.vbs. You can even resize an array after you have defined it. Download the script, array3.vbs, and execute it. Functions As for all other programming languages, VBScript allows you to create functions to modularize your code. Functions are isolated bits of code that are called to perform specific or repetitive operations. The following piece of code shows you how to create a function: function sum(a,b) sum = a + b end function Note that we don't have a return statement. We use the function name to return the value of the function. So convenient, isn't it? Use the following code for practice. Download the script, functions.vbs, and execute it. Procedures/Subroutines Procedures/Subroutines are functions without return values. Therefore it is like a void function. However, the syntax used to define a subroutine is different from that used to define a function (sub vs. function), and the way calling a subroutine is also different from calling functions. Dim sum a = 10 b = 20 calculate_sum a, b MsgBox sum sub calculate_sum( a, b) sum = a + b end sub Note that all variables used here are global, except that defined inside functions or subroutines. Display messages There are two built-in functions available for us to output messages: WScript.echo and MsgBox. The former can work in both a window-based scripting host and a command-line scripting host. The latter can only work in the Windows environment but is more versatile. Download the script, output1.vbs, and execute it. There is only one line in the code: MsgBox "Are you sure?",4,"Check" The function MsgBox takes three arguments. The first one is the message you want displayed. The third one gives the title of the message box. The most tricky one, the second one, specifies the type of the message box. For instance, "4" indicates that the box contains 'Yes' and 'No' buttons. Change it to 1 to see what will happen. See details from the following webpage to learn about the MsgBox function: http://msdn.microsoft.com/en-us/library/sfw6660x.aspx Download the script, output2.vbs, and execute it. This code shows you how to get a return value from MsgBox function. Asking for input To get input from users, you can simply use the built-in function InputBox. The following code illustrates its usage: Dim vInput vInput = InputBox("Enter a server name", "Server") MsgBox "You entered " & vInput The function returns an empty string if the cancel button is pressed. It returns -1 if esc key is pressed. Controlling the flow of execution As a powerful programming language, VBSript provides enough controlling structures for you. The following summarize the syntax of these structures. Most of them have been used in my example code. Conditional execution: If condition_expression Then statement1 ElseIf statement2 else statement3 End if Selection execution: Select Case caseNumber Case 1 statement1 Case 2 statement1 ... Case Else statementn End Select Loops: Do While condition statement Loop or Do statement Loop While condition or Do Until condition statement Loop or Do statement Loop Until or For counter = start To end statement Next or For counter = start To end Step number statement Next or For Each element In collection statement Next If you are a good C++ or Java programmer, it should be easy for you to get used to these structures. Otherwise, you need extra practice. That's all for today. You may have spent more than two hours on this lecture. Thanks for your attention.

    Lecture 3 Logon Scripts

    From language point of view, VBScript is not a difficult programming language. Indeed, it is much less complicated than those popular general purpose programming languages, such as C, C++, and Java. However, use of the language requires knowledge of the operating system. From this lecture we start to learn Windows scripting techniques by performing a set of administrative tasks. The first task we are going to do today is to write a logon script to allocate network resources to users when they login. Key words WSH Object, WScript.Network, Network User, Network Drive, User Group, WMI WSH objects Download the script userName.vbs and run it. The main part of the code is: Dim objNetwork Set objNetwork = WScript.CreateObject("WScript.Network") Dim strComputer, strDomain, strUser strComputer = objNetwork.ComputerName strDomain = objNetwork.UserDomain strUser = objNetwork.UserName The first statement declares a variable objNetwork. The second statement assigns an object to the variable. Microsoft operating system, more accurately the WSH (Windows Script Host), provides a few objects for typical scripting purposes of performing administrative tasks. WScript.Network is one of most useful WSH Objects (also called WScript Objects). The following is the hierarchy of WSH objects: Learn more about WSH Objects and Associated Tasks from Microsoft website. The Network object WScript.Network is an object that provides network information, such as computer name, domain name and username, as well as the functions of mapping drives and printers. We use the following statement to create an instance of the object: WScript.CreateObject("WScript.Network") WScript.Network has a set of properties and methods (See msdn online documents or textbook page 174-179): ComputerName Property UserDomain Property UserName Property AddPrinterConnection Method AddWindowsPrinterConnection Method EnumNetworkDrives Method EnumPrinterConnections Method MapNetworkDrive Method RemoveNetworkDrive Method RemovePrinterConnection Method SetDefaultPrinter Method Using these properties or methods is not hard. For instance, suppose you assign the object WScript.Network to variable objNetwork, i.e., objNetwork = WScript.CreateObject("WScript.Network") Please note that the real name which corresponds to the WScript.WshNetwork object is "WScript.Network". There is no a property of the WScript object that we can use to return the WScript.WshNetwork object, but using CreateObject("WScript.Network"). To get the computer name you are using, you can simply write WScript.echo objNetwork.ComputerName or assign objNetwork.ComputerName to a variable as we did in userName.vbs. Map a network drive Whenever you login to a lab computer, you automatically get a U: drive. Obviously it is not a local drive. In fact it is a network drive that is mapped to a file folder located on a remote computer to which you have access. As a network user, you might not know which file folder is available to you. However, if you are an administrator, you have control over your network storage. Suppose that you are an administrator, and jamie is one of the network users. You have allocated a network folder to jamie as follows: \\server\users\jamie Now, you want to map X: drive of the machine to the network folder above so that whenever jamie logs on to one of the computers in the network he can access the network folder through X: drive. You can use the following script for the job: Dim objNetwork Set objNetwork = WScript.CreateObject("WScript.Network") objNetwork.MapNetworkDrive "X:", "\\server\user\jamie" Of course you can't test the above code on your computer unless you have a network folder "\\server\user\jamie". If you want to test the program now on your computer, follow the instructions here to find a shared network folder provided that your computer is connected to a network (you can do this in a SCM lab). To disconnect a network drive, use the following code: Dim objNetwork Set objNetwork = WScript.CreateObject("WScript.Network") objNetwork.RemoveNetworkDrive "X:" See msdn online documents for more details of the task. To check the information about all connected network drives, use the following code: Dim objNetwork Set objNetwork = WScript.CreateObject("WScript.Network") Set objDrives = objNetwork.EnumNetworkDrives For i =0 to objDrives.count - 1 Step 2 WScript.echo objDrives.Item(i) & ":" & objDrives.Item(i+1) Next Map a network printer Assume that you have two networked computers at home but have only one network-ready printer. If you want to share the printer between the two computers, the following script can help you to do this job: Dim objNetwork Set objNetwork = WScript.CreateObject("WScript.Network") objNetwork.AddWindowsPrinterConnection "\\server\\printerName" Similarly, you can remove a network printer connection and list the information of all connected printers. Get user's groups Gaining group information is a bit harder because the same user can belong to different groups. The following code, GetGroup.vbs, can list all the groups a user belongs to: Set oNetwork = CreateObject("WScript.Network") sDomain = oNetwork.UserDomain sUser = oNetwork.UserName Set oUser = GetObject("WinNT://" & sDomain & "/" & sUser & ",user") For Each oGroup In oUser.Groups MsgBox oGroup.Name Next GetObject is a built-in method of VBScript, which returns user a reference to an object, given the user domain and user name. The property Groups of the object contains all the roles of the user. Get IP address The following script can get IP address: Set oWMI = GetObject("winmgmts:" & "\\.\root\cimv2") Set resultObj = oWMI.ExecQuery("select IPAddress from " & _ "Win32_NetworkAdapterConfiguration" & " where IPEnabled = TRUE") For Each IPAddress in resultObj If IPAddress.IPAddress(0) <> "0.0.0.0" Then myIP = IPAddress.IPAddress(0) Exit For End If Next MsgBox myIP Note that we have used a WMI query to get the IP address (see Chapter 18). We will learn more about it later. The information we have collected is now enough for writing a simple logon script. Try to write your logon script now. Don't be shy away from searching on the Web.

    Lecture 4 Objects in VBScript

    VBScript is a kind of Object-Oriented programming language. However, we do not write any class definition in VBScript. Instead, we use the objects that are provided by Windows Script Host Object Model. In this lecture, we will discuss how to use these objects in a script. Key words WSH, WSH Object, WSH Object Model The WScript Object WScript is the root object of the Windows Script Host (WSH). You can use all its properties and methods directly, for instance WScript.echo. The WScript object allows you to: create objects via CreateObject Method connect to objects via ConnectObject Method disconnect from objects via DisconnectObject Method sync events via Sleep Method stop a script's execution programmatically via Quit Method output information to the default output device via Echo Method Follow the above links to learn how to use these methods. We have known how to use WScript.echo for message output. We have also used CreateObject method to create WScript.network object in last lecture. Here is another example to use WScript object. WScript.echo "Wait me for 5 minutes" WScript.Sleep 300000 WScript.echo "I am ready now, let's go" WScript.Quit Copy and paste this code and run it on your computer. The Shell Object The Shell object is used to execute external applications, work with special folders and shortcuts, manipulate environment variables, write to the event log, read and write to the Registry, create timed dialog boxes, and even send keystrokes to another application. Just like the Network object, the Shell object must be explicitly created and assigned to a variable. 'Create shell object Set objShell = CreateObject("WScript.Shell") WSH Shell run method WSH Shell is so powerful that it can do whatever you can do with command line. In fact, WSH Shell object allows you to execute applications within your script. There are two shell methods to execute applications: Exec and Run. Let's try the script dirRun.vbs first: Dim objShell Set objShell = CreateObject("WScript.Shell") objShell.Run "cmd /c dir > test.txt" where ¡°cmd /c dir > test.txt¡± is a command that lists the current directory and output the result to a text file (the option "/C" means "Carries out the command specified by string and then terminates"). The Run method can take two more parameters in addition to the specified command. The following code runNotepad.vbs starts the notepad.exe program, and waits for you to complete and display a message: 'Create shell object Dim objShell Set objShell = CreateObject("WScript.Shell") 'call Notepad program objShell.Run "notepad.exe",1,true MsgBox "I know what you wrote :-)" Read Microsoft VBScript WSH reference for more details. WSH Shell Exec method The Exec method is more advanced. It returns a WSHScriptExec object, which wraps the standard stream objects stdIn, StdOut, and StdErr services. This enables the script to read the output directly from the application without first having to save the output to a file. The following script execPing.vbs illustrates how to use Shell Exec method to check network using command line Ping: WScript.Echo("Check Network using command line Ping") Set objShell = CreateObject("WScript.Shell") Set objWshScriptExec = objShell.Exec("cmd /c ping 127.0.0.1") Set objStdOut = objWshScriptExec.StdOut While Not objStdOut.AtEndOfStream strLine = objStdOut.ReadLine strOutput=strOutput & strLine & vbcrlf Wend WScript.Echo(strOutput) In this code, the Exec method returns a WSHScriptExec object, named objWshScriptExec, which outputs the outcome of the command line to a standard stream object. The loop simply reads each line from the standard stream and puts it into a string. Note that vbcrlf is a VB constant for a new line (like \n in C++). WSH Shell SendKeys method You can use the SendKeys method to type keystrokes to applications that have no automation interface. Most keyboard characters are represented by a single keystroke. Some keyboard characters are made up of combinations of keystrokes (CTRL+SHIFT+HOME, for example). To send a single keyboard character, send the character itself as the string argument. For example, to send the letter x, send the string argument "x". Run the following script for fun: Dim objShell Set objShell = CreateObject("WScript.Shell") objShell.Run "notepad.exe" WScript.Sleep 5000 objShell.AppActivate "Notepad" objShell.SendKeys "Ghost writing is fun." Learn more about SendKeys method from Microsoft VBScript WSH reference. Practice with this code calculator.vbs Learn more about WSH Shell methods from Microsft VBScrip WSH reference. The Shortcut object Shortcut object allows you to create a shortcut programmatically. Learn how to use the object by using the following script shortcut.vbs. set WshShell = WScript.CreateObject("WScript.Shell") strDesktop = WshShell.SpecialFolders("Desktop") set oShellLink = WshShell.CreateShortcut(strDesktop & "\IE.lnk") with oShellLink .TargetPath = "C:\Program Files\Internet Explorer\IEXPLORE.EXE" .WindowStyle = 1 .Hotkey = "Ctrl+Alt+I" .IconLocation = "C:\Program Files\Internet Explorer\IEXPLORE.EXE, 0" .Description = "Internet Explorer" .WorkingDirectory = strDesktop .Save end with set oUrlLink = WshShell.CreateShortcut(strDesktop & "\Script Programming.url") oUrlLink.TargetPath = "http://www.scm.uws.edu.au/~jianhua/SAP10/" oUrlLink.Save The script firstly creates a WSH Shell object and calls its method SpecialFolders to get the actual path of your Desktop folder (different user has difference path). The second part creates a shortcut for Internet Explorer and puts it on your Desktop. The third part of the code creates a shortcut for the unit webpage of Systems Administration Programming. Summary In this lecture, we learnt how to use WSH built-in objects, such as WScript, Shell and Shortcut. In fact, the Windows Script Host object model provides a logical, systematic way to perform many administrative tasks. The following is the hierarchy of WSH objects: Learn more about WSH objects from Microsoft website. Microsoft's Philosophy: Create a minimal core WSH structure that can interact with any number of separate object models for extention. For instance, Windows Management Instrumentation (WMI, See Lecture 5), the FileSystemObject (FSO, See Lecture 6), Active Directory Service Interfaces (ADSI, See Lecture 7), Collaboration Data Objects (CDO, See Lecture 8) object models are separate from the WSH object model (i.e. WMI, FSO, ADSI, and CDO are not built in WSH). What's the time now? Have a kit-kat. ... Pring page

    Lecture 5 Getting access to remote machines

    (WMI Basics) In this lecture, we learn how to get access to remote computers via WMI in order to remotely control a network computer. Nowadays, computer security has become extremely complicated. The way to access a remote computer depends heavily on the security settings and the Internet settings of both computers. Therefore, you should not expect that all the code listed in this lecture can be run straight away on your computer. You have to try your luck and set up your network and computers properly before you test the scripts. Key words Windows Management, WMI (Windows Management Instrumentation), WMI class, WMI service, WMI query, WMI Scripting Library, CIM (Common Information Model), CIM Repository, Namespace, WBEM (Web-Based Enterprise Management), Security Settings, Internet/Network Settings Shutting down remote computers: an introductory script Dim sMachine sMachine = InputBox("Shut down which computer?") Dim sWMI sWMI = "SELECT * FROM Win32_OperatingSystem WHERE Primary = true" Dim oOS Set oOS = GetObject("winmgmts://" & sMachine & "/root/cimv2").ExecQuery(sWMI) Dim oItem For Each oItem in oOS oItem.Shutdown Next In the above script, the first two statements are used to input the name of a remote computer. Win32_OperatingSystemis a WMI class, containing the information about the Windows operating systems installed on that computer. The string, sWMI, defines a WMI query to get all instances of Win32_OperatingSystem that are the primary operating system on the remote machine. Cimv2 is a namespace under the root of the computer (root\cimv2 namespace) that contains all of the Win32 classes, including the Win32_OperatingSystem class. The third group of statements executes the WMI query. Finally, the script shutting down all Windows operating systems that are running on the computer (the existing windows systems up to date can only allow one primary windows operating system running at the same time but Microsoft leaves the possibility for the future that more than one windows operating systems can be run at the same time). With similar code, we can also reboot, logoff, or power off a remote computer by changing the statement: oItem.Shutdown. See more details from Win32Shutdown Method of the Win32_OperatingSystem Class. What is WMI? The above script actually uses windows WMI services. Windows Management Instrumentation (WMI) is the primary infrastructure for management data and operations on Windows operating systems. We can utilize the facilities of WMI to write scripts for administrative tasks on local but mainly remote computers. WMI also supplies management data to other parts of the operating system and products, for example, System Center Operations Manager, formerly Microsoft Operations Manager (MOM), or Windows Remote Management. WMI enables consistent and uniform management, control, and monitoring of systems throughout your enterprise. It allows system administrators to query, change, and monitor configuration settings on desktop and server systems, applications, networks, and other enterprise components. System administrators can write scripts that use the WMI Scripting Library to work with WMI and create a wide range of systems management and monitoring scripts. Connecting to WMI on a Remote Computer You might consider that remotely controlling a computer is not that hard once we have the above script. But in reality, the remote access is not straight forward. If you don't believe that, download the code shutdown.vbs and run it. Unless you leave your firewall open you will encounter problems when trying to run the script. A large amount of work on security setting is needed. Assume that you are working on Computer A and you are going to remotely control Computer B. There are a few necessary conditions: 1. You have an account on Computer B which is in the Administrator group. 2. The password of your account on Computer A is not blank. 3. Both Computer A and Computer B must be running IPv6 if the computer is running under Vista. Either computer may be running IPv4. For more details of how to set up the computers, see Connecting to WMI on a Remote Computer. Understanding WMI You can check whether the WMI setting works on a computer by running the following program (WbemTest) in the command line: wbemtest You will see a window called Windows Management Instrumentation Tester. The eBook Chapter 3 shows you all the details of this tool. Try first to connect to the remote computer you set. If no luck, you can connect to the local WMI to learn more about WMI. Suppose that you have successfully connected to a WMI (either remotely or locally). WMI contains large groups of classes in different hierarchy, dealing with: Computer System Hardware Operating System Installed Applications WMI Service Management Performance Counter The most useful classes are Win32_OperatingSystem, Win32_LogicalDisk, Win32_NetworkAdapterConfiguration and so on. WMI Reference gives a complete list of all WMI classes. There are more than 100 WMI classes and may be more in the upgraded windows versions. WbemTest can show your all the instances of these classes that are running on the computer to which you have connected (the remote computer or local machine). More importantly, you can retrieve data from these running objects by using a SQL-like query language - WMI Query Language (WQL). For instance, to get information about the Windows operating systems that are running on the machine, you can make the the following query in the query menu (click "query button"): SELECT * FROM Win32_OperatingSystem WHERE Primary = true You will likely see the following outcome or something similar: Win32_OperatingSystem.Name="Microsoft Windows XP Professional|C:\\WINDOWS|\\Device\\Harddisk0\\Partition1" You may also remember how we get the IP address (See Lecture 3): SELECT IPAddress FROM Win32_NetworkAdapterConfiguration WHERE IPEnabled = TRUE" Learn more on WQL from http://msdn.microsoft.com/en-us/library/aa392902(VS.85).aspx. Write WMI Scripts If the connection is ok, you can write your WMI script for any remote tasks. First, let¡¯s get the other computer¡¯s IP address and MAC address with the checkIPnMAC.vbs: Dim computer_B Dim objWMIService Dim colItems 'the remote computer's name, here means local computer_B = "." Set objWMIService = getObject("winmgmts://" & _ computer_B & "\root\cimv2") Set colItems = objWMIService.ExecQuery( _ "SELECT * FROM Win32_NetworkAdapterConfiguration", , 48) For Each objItem in colItems WScript.Echo "IP Address: " & objItem.IPAddress(0) WScript.Echo "MAC Adress: " & objItem.MACAddress Next You can use this code as a template to perform more complicated tasks. Most WMI scripts follow a simple three-step pattern. In general, WMI scripts: 1. Connect to the WMI service. 2. Retrieve a WMI object or collection of objects. 3. Perform some sort of task on the object or objects. How do you feel - comfortable or had a headache? I suggest you search on the Web using the key words provided here for an in-depth understanding, for instance, WMI Architecture. Of course, have a break first:)

    Lecture 6 Manage Folders/Files Using FSO

    Welcome to our Lecture 6:) When writing scripts for Windows Script Host, Active Server Pages, or other applications where scripting can be used, it often requires to operate folders/files, such as adding, moving, changing, creating, or deleting folders and files. In this lecture, we will learn how to use the FileSystemObject (FSO) Library to operate drives, folders and files. Key words FSO (FileSystemObject), FSO library, Scripting Runtime Library, WBEM (Web-Based Enterprise Management), File System, Folder Manipulation, File Manipulation The FileSystemObject Library FSO library contains a set of objects for variety of file operations, which allows you to create, delete, gain information about, and generally manipulate drives, folders, and files. Before we get into any details, let's practise the following script createFile.vbs. Dim oFSO Set oFSO = CreateObject("Scripting.FileSystemObject") Set a = oFSO.CreateTextFile("c:\\testfile.txt", true) a.WriteLine "This is a test." a.Close The code simply creates a text file and writes a message to the file. In general, to program with the FileSystemObject (FSO) object library, we need to consider the following three scripting steps: use the CreateObject method to create a FileSystemObject object use the appropriate method on the newly created object access the object's properties. To create a FileSystemObject object, simply use the following statement. CreateObject("Scripting.FileSystemObject") Note that you need to use Set to assign the object to a variable. Once you get the object, you can use the following method to create text files, create folders, delete files, and delete folders: CreateTextFile, CreateFolder GetFile, GetFolder, GetDrive MoveFile, MoveFolder CopyFile, CopyFolder DeleteFile, DeleteFolder See Working with Drives and Folders from Micrisoft Developer Network for the details of how to use these methods. See FileSystemObject Methods for a full list of the methods. Operating Drives The following code shows you how to get drive information programmatically: Dim oFSO, oDrive Set oFSO = WScript.CreateObject("Scripting.FileSystemObject") For Each oDrive In oFSO.Drives IF oDrive.isReady THEN MsgBox "Drive " & oDrive.DriveLetter & _ " has a capacity of " & oDrive.TotalSize & " bytes " & _ " and is drive type " & oDrive.DriveType END IF Next Note that oFSO.Drives contains all the drive objects mounted by the operating system that is running. Drive objects represent the logical drives attached to your system, including network drives, CD-ROM drives, and so forth. Therefore they can be many. Each drive object contains the following data members: AvailableSpace DriveLetter DriveType FileSystem FreeSpace IsReady Path RootFolder SerialNumber ShareName TotalSize VolumeName The following code shows you how to operate a particular drive by providing a drive path drvPath. Dim fso, d, s, drvPath 'give your drive path drvPath = ??? Set fso = CreateObject("Scripting.FileSystemObject") Set d = fso.GetDrive(fso.GetDriveName(drvPath)) s = "Drive " & UCase(drvPath) & " - " s = s & d.VolumeName & s = s & "Free Space: " & FormatNumber(d.FreeSpace/1024, 0) s = s & " Kbytes" MsgBox s Drives also provide an entry point into each drive's file system, starting with the root folder of the file system hierarchy. Because the Drive object represents one of the simplest aspects of the file system, it's one of the simplest objects in the FSO. Operating Folders FSO offers more methods to the Folder object for manipulating folders than the Drive object: CopyFolder: copies a folder. CreateFolder: creates a new folder. DeleteFolder: removes a folder permanently. Note that the deleted folder doesn't ever make it to the Recycle Bin, and there's no "Are you sure?" prompt. FolderExists:, like DriveExists, returns a True or False indicating whether the specified folder exists. GetFolder: accepts a complete folder path and, if the folder exists, returns a Folder object that represents the folder. GetParentFolderName: accepts a complete folder path and returns the name of its parent folder. GetSpecialFolder: returns the complete path to special operating system folders. MoveFolder: moves a file a folder. Download the program FolderOperation.vbs to practice. Similar to drive objects, once you call GetFolder method of FSO, you get a folder object. Each folder object have the following methods: Copy Delete Move CreateTextFile Using these methods is straightforward. You can also use FSO to retrieve attribute information about folders. Operating Files: File operation is also similar. Download the program fileOperatrion.vbs to practice. Note that a file object contains the following properties: Attributes DateCreated DateLastAccessed DateLastModified Drive Name ParentFolder Path ShortName Size Type Surprisingly, not only can you get the information about a file's or folder's attributes but also change these attributes. Dim fso, f1, f2, s Set fso = CreateObject("Scripting.FileSystemObject") Set f = fso.GetFile("c:\test.txt") f.attributes = 1 This code changes the attribute of C:\test.txt to read-only. See Attributes Property for the meaning of the attribute values. Microsoft provides a comprehensive example code FileOperationCollection.vbs which can be run directly. It is very useful. We will practice it in the practical tasks. At the end, I'd like to remind you again of Microsoft's Philosophy: Create a minimal core WSH structure that can interact with any number of separate object models for extention. For instance, Windows Management Instrumentation (WMI, See Lecture 5), the FileSystemObject (FSO, See Lecture 6), Active Directory Service Interfaces (ADSI, See Lecture 7), Collaboration Data Objects (CDO, See Lecture 8) object models are separate from the WSH object model (i.e. WMI, FSO, ADSI, and CDO are not built in WSH).

    Lecture 7 Working with ADSI

    Welcome to Lecture 7. Domain, group and user maintenance is probably one of the top administrative tasks that we want to automate. Administering a directory service often involves numerous repetitive tasks such as creating, deleting, and modifying users, groups, organizational units, computers, and other directory resources. Performing these steps manually by using graphical user interface (GUI) tools is time-consuming, tedious, and error prone. Active Directory Service Interfaces (ADSI) is the technology that allows you to create custom scripts to automate such repetitive tasks. In this lecture we will learn how to manipulate domains, groups and users via ADSI. Unfortunately if you do not have a network or system administrative role on the computer or network you are using, you will be unable to perform all the tasks we discuss in this lecture. However, all the programs provided in this lecture can be run with an Administrator user account, therefore you should be able to run them at home. Key words Directory Service, ADSI (Active Directory Service Interfaces), Network Resources, Distributed Computing, Domain, Group, User Manipulation, Domain Name, Domain Object, Domain Component, Group Name, Group Object, User Name, User Object, Organization Unit, Common Name, Administrative Role Active Directory Services Interface (ADSI): basic concepts Active Directory (AD) is a directory service used to store information about the network resources across a domain and user information on the local computer. Microsoft provides many tools to enumerate, diagnose, and manage AD, and more and more commercial tools are also available. ADSI is one of the most useful tools. Similar to WMI, Active Directory Service Interfaces (ADSI) is an object library. It can be used in a distributed computing environment for managing network resources from different network providers. Administrators and developers can use ADSI services to enumerate and manage the resources in a directory service, no matter which network environment contains the resource. The tasks that ADSI can perform: creating, deleting, and modifying users, groups, organizational units, computers; managing printers, and locating resources in a distributed computing environment. Like WMI, you can write ADSI client applications in many languages, such as Visual Basic, C++, JScript, VBScript. Note that Active Directory runs on Windows Server 2008, Microsoft Windows Server 2003, and Windows 2000 Server domain controllers. Only client applications using ADSI may run on Windows Vista, Windows XP, Windows 2000, Windows NT 4.0. ADSI providers ADSI provides a well-defined set of objects, methods, and properties to interact with supported directories. Abstracted access to an independent directory resource is via an ADSI provider. Surprisingly, we can use several ADSI service providers to access same information. The commonly used ADSI providers are WinNT, LDAP, NDS, and NWCOMPAT. In this lecture, we mainly discuss the use of the WinNT provider. The WinNT provider can connect to any NT-compatible domain, therefore can be used in any Windows NT compatible operating systems, such as Windows 2000 or above. The following code is a typical ADSI program using WinNT provider. Remember that we ever use WinNT ADSI in lecture three: Set oNetwork = CreateObject("WScript.Network") sDomain = oNetwork.UserDomain sUser = oNetwork.UserName Set oUser = GetObject("WinNT://" & sDomain & "/" & sUser & ",user") For Each oGroup In oUser.Groups MsgBox oGroup.Name Next The fourth line of the code gets an ADSI object from WinNT with specified a WinNT ADsPath. This object contains the information of the user who's currently logging in. In general, in order to get a WinNT provided ADSI object, you have to specify a WinNT ADsParh. The syntax of WinNT ADsPath is the following: WinNT: WinNT://<domain name> WinNT://<domain name>/<server> WinNT://<domain name>/<object path> WinNT://<domain name>/<object name> WinNT://<domain name>/<object name>,<object class> WinNT://<server> WinNT://<server>/<object name> WinNT://<server>/<object name>,<object class> The domain name can be either a NETBIOS name or a DNS name, which can be retrieved through WScript.Network object. The server is the name of a specific server within the domain. The object path is the path of an object, such as "printserver1/printer2". The object name is the name of a specific object. The object class is the class name of the named object. The information about an object can also be retrieved through WScript.Network object. With my computer, for the user object of my account, the ADsPath will be "WinNT://jamie-win/jamie,user", where "jamie-win" is the domain name and "jamie" is the object name and "user" is the specified class. Another more commonly used but more complicated ADSI provider is LDAP Provider. LDAP stands for Lightweight Directory Access Protocol. The LDAP provider implements a set of ADSI objects that support various ADSI interfaces, therefore it can work with any LDAP compatible directory, not just Active Directory. Similar to WinNT ADSI provider, to access an ADSI LDAP object, we need to specify a LDAP ADsPath. The syntax is slightly different from the one for WinNT ADsPath. ' Bind to the root of the LDAP namespace. LDAP: ' Bind to a specific server. LDAP://server01 ' Bind to a specific server using the specified port number. LDAP://server01:390 ' Bind to a specific object. LDAP://CN=Jeff Smith,CN=users,DC=fabrikam,DC=com ' Bind to a specific object through a specific server. LDAP://server01/CN=Jeff Smith,CN=users,DC=fabrikam,DC=com We have to follow the following conventions when we specify a LDAP ADsPath: Use DC when specifying any portion of a domain name. Always list the domain name components in their regular order. For example, a domain named scm.uws.edu.au would have an LDAP path of "dc=scm,dc=uws,dc=edu,dc=au". DC stands for "Domain Component". Use OU when specifying an "Organizational Unit". Use CN when specifying a "Common Name", such as a user, group, or any of the built-in AD containers. With the ADSI LDAP provider, you can only create a global user account. Local accounts reside in the SAM database and must be created using the WinNT provider. Since I don't have a network administrative credentials in my office network, I can't create a global user. Therefore I can't run any LDAP query in my computer. If you have a network environment at home, please try the code listed in the textbook Chapter 15. Manipulating domains If you have administrative credentials of your network, you can access and change the setting of the network domain. To query domain information by using the WinNT provider, simply do the following (specifying your domain name; the domain name can be retrieved through WScript.Network object): Dim objDomain Set objDomain = GetObject("WinNT://MyDomain") Then you can get the information about your domain by using get method. For instance, objDomain.Get("MinPasswordAge") will give you the minimum number of days a user must keep this password. To set this this property, simply do something like this: objDomain.put("MinPasswordAge", 10) The properties of a domain you can operate by using the WinNT provider are: MinPasswordLength MinPasswordAge MaxPasswordAge MaxBadPasswordsAllowed PasswordHistoryLength AutoUnlockInterval LockoutObservationInterval See WinNT Schema's Mandatory and Optional Properties from Microsoft. For settings of Organization Units, please refer to the textbook pages 260-263. Manipulating users and groups To manipulate users and groups, we first get an domain object as we did above (objDomain). Then you can call Create method to create a new user or group: Set oNetwork = WScript.CreateObject("WScript.Network") sDomain = oNetwork.UserDomain sUser = oNetwork.UserName msgbox "User domain: " & sDomain & " User name: " & sUser Set oDomain = GetObject("WinNT://" & sDomain) Set oUser = oDomain.Create("user", "Daniel") oUser.Description = "Test user" Set oGroup = oDomain.Create("group", "TestGroup") oGroup.Description = "Test group" oUser.SetInfo oGroup.SetInfo oUser.GetInfo oGroup.GetInfo WScript.echo "User name: " & oUser.Name WScript.echo "User description: " & oUser.Description WScript.echo "Group name: " & oGroup.Name WScript.echo "Group description: " & oGroup.Description This code (CreateUserGroup.vbs) can explain itself. It creates a new user "Daniel", a new group "TestGroup" and display the related information. You might be curious about the methods GetInfo and SetInfo. GetInfo method is used to load into the cache of ADSI object properties from the underlying directory store. SetInfo method saves the cached property values of the ADSI objects to the underlying directory store. Note that any property value changes made by Create or Put methods will be lost if GetInfo (or GetInfoEx) is invoked before SetInfo is called. If you have an administrative role in a Windows system, you can test the program CreateUserGroup.vbs without needing any change. If a user name or a group name already exist, you can create a user object or a group object from their names by calling GetObject method: Set oNetwork = WScript.CreateObject("WScript.Network") sDomain = oNetwork.UserDomain Set oDomain = GetObject("WinNT://" & sDomain) Set oUser1 = GetObject("WinNT://" & sDomain & "/Daniel,user") WScript.echo oUser1.Description Set oGroup1 = GetObject("WinNT://" & sDomain & "/TestGroup,group") WScript.echo oGroup1.Description The above code (UserGroupMore.vbs) must be run after CreateUserGroup.vbs has been run. The following code (SetPassword.vbs) demonstrates how to change password programmatically: Set oNetwork = WScript.CreateObject("WScript.Network") sDomain = oNetwork.UserDomain Set oDomain = GetObject("WinNT://" & sDomain) Set oUser = GetObject("WinNT://" & sDomain & "/Daniel,user") oUser.SetPassword "12345" oUser.SetInfo WScript.echo "Password changed" For more information for user and group manipulation, read Microsoft references IADsUser Interface, IADsGroup Interface or more generally ADSI Objects of WinNT. Microsoft also provides a few examples for User Account Management. Please read these examples carefully because a few quiz questions might be based on some of the examples. All in all, Active Directory Service is a complicated and powerful facility. It takes a while to get familiar with its internal structure and usage. Hope you had an easy time.

    Lecture 8 E-Mail Automation

    In the previous lectures, we have learnt the basic language components of VBScript and the key scripting technologies for Windows. In this and the next lectures we apply the scripting technologies to extended Windows system administration. Nowadays almost all of us send emails using email softwares, such as Office Outlook, Thunderbird, Pine, Webmail and etc. These popular email softwares have to be used manually. Assume that we are going to send monthly bills to thousands of our customers via emails. Most email softwares cannot do the job efficiently. In this lecture, we introduce the techniques for generating and delivering emails automatically. Key words CDO (Collaboration Data Objects), SMTP (Simple Mail Transfer Protocol), Local SMTP Server, Remote SMTP Server, TCP/IP, Port Number The email automation is not covered by the textbook. Part of the materials of this lecture were taken from Jeff Fellinge's book "IT Administrator's Top 10 Introductory Scripts for Windows" and Paul Sadowski's website "http://www.paulsadowski.com/" (unformtunately the link is no longer active). However, you can find plenty of related scripts from the Internet. Email scripts If you have installed SMTP service on your computer, sending an email programmatically is extremely easy: Set objMsg = CreateObject("CDO.Message") objMsg.Subject = "subject of the message here" objMsg.From = "your email address here" objMsg.To = "addressee's email address here" objMsg.TextBody = "the message text here" objMsg.Send Download the code mail1.vbs and try to run it. If it is not runnable, most likely you do not have a local SMTP or it has not been configured properly (See How to install and Configure SMTP Virtual Servers ). In such a case, the best way to go is specify a remote SMTP server to deliver your message (say the school email server). Try the following script mail2.vbs: Dim objMsg, objConfiguration, objConfigFields Set objConfiguration = CreateObject("CDO.Configuration") Set objConfigFields = objConfiguration.Fields objConfigFields.Item("http://schemas.microsoft.com/cdo/" & _ "configuration/sendusing") = 2 objConfigFields.Item("http://schemas.microsoft.com/cdo/" & _ "configuration/smtpserverport") = 25 'replace the SMPT server address with your SMTP address objConfigFields.Item("http://schemas.microsoft.com/cdo/" & _ "configuration/smtpserver") = "mail.westernsydney.edu.au" 'or try SCEM's remote SMTP server "mail.scem.westernsydney.edu.au" objConfigFields.Update Set objMsg = CreateObject("CDO.Message") objMsg.Configuration = objConfiguration objMsg.Subject = "subject of the message here" objMsg.From = "your email address here" objMsg.To = "addressee's email address here" objMsg.TextBody = "the message text here" objMsg.Send Note that if you use WSU' or SCEM's remote SMTP server, your computer needs to be connected to the school network (you can use vpn if you are working at home). Simple Mail Transfer Protocol (SMTP) and Collaboration Data Objects (CDO) There are two basic concepts that are crucial for the understanding of the above code: CDO and SMTP. Firstly, let's see how an email message is delivered. Typically an email message is delivered across the Internet under the Simple Mail Transfer Protocol (SMTP). Delivery of a message is initiated by transferring the message to a designated SMTP server. Based on the domain name of the recipient e-mail address, the SMTP server initiates communications with a Domain Name System (DNS) server, which looks up and then returns the host name of the destination SMTP server for that domain. The originating SMTP server communicates with the destination SMTP server directly through Transmission Control Protocol/Internet Protocol (TCP/IP) on port 25. If the user name of the recipient e-mail address matches one of the authorized user accounts on the destination server, the original e-mail message is transferred to that server, waiting for the recipient to pick up the message through a client program. In the case where the originating SMTP server cannot communicate directly with the destination server, the SMTP service can transfer messages through one or more intermediate relay SMTP servers. A relay server receives the original message and then delivers it to the destination server, or redirects it to another relay server. This process is repeated until the message is delivered or a designated timeout period passes. Next, let's see how to compose an email message. An email message consists of the following components: To: receiver's email address. From: sender's email address Subject: a brief description of the message Cc: carbon copy Bcc: blind carbon copy Attachments: attached files In the example code above, we use Microsoft Collaboration Data Objects (CDO) to create an email message and specify a SMTP service. Collaboration Data Objects are a high-level set of COM objects that allow, among other functionalities, easily access of the email system embedded in the Microsoft Windows products. CDO Configuration In order to use CDO to send a message, we first need to create a CDO configuration object: Set objConfiguration = CreateObject("CDO.Configuration") A CDO Configuration object contains information such as the method used to deliver messages, the paths to the pickup directories for SMTP and Network News Transfer Protocol (NNTP) servers, a user's mailbox Uniform Resource Identifier (URI), and so forth. The following setting specifies the SMTP server we are going to use for sending our message: [Take a break ...] Set objConfigFields = objConfiguration.Fields objConfigFields.Item("http://schemas.microsoft.com/cdo/" & _ "configuration/sendusing") = 2 objConfigFields.Item("http://schemas.microsoft.com/cdo/" & _ "configuration/smtpserverport") = 25 'replace the SMPT server address with your SMTP address objConfigFields.Item("http://schemas.microsoft.com/cdo/" & _ "configuration/smtpserver") = "mail.westernsydney.edu.au" 'or try SCEM's remote SMTP server "mail.scem.westernsydney.edu.au" objConfigFields.Update The three configuration fields that this script uses are sendusing, smtpserverport, and smtpserver. The configuration field sendusing instructs CDO whether to send the message using the local SMTP service (sendusing = 1), send to a remote SMTP (sendusing = 2) or send using an Exchange Server mail submission URI (sendusing =3). The field smtpserverport specifies the SMTP port to use, which is 25, by default. If your remote SMTP server listens on a different port, you can configure CDO to send to that port instead. The last configuration field specifies the SMTP server. You should fill in the name of the SMTP server you are going to use to send messages. If you run your program in a SCEM lab, you could use the school email server mail.scem.westernsydney.edu.au. This may not work at ITD computer labs, where you should be able to use mail.westernsydney.edu.au. Lastly, we must update the configuration by calling the Update method. More and more administrators are restricting access to their servers to control spam or limit which users may utilize the server. Adding the following lines to the Mail.vbs if your SMTP server uses the basic authentication, the most commonly used authentication method. 'Type of authentication, NONE, Basic (Base64 encoded), NTLM objconfigFileds.Item("http://schemas.microsoft.com/cdo/configuration/smtpauthenticate") = cdoBasic 'Your UserID on the SMTP server objconfigFileds.Item("http://schemas.microsoft.com/cdo/configuration/sendusername") = "youruserid" 'Your password on the SMTP server objconfigFileds.Item("http://schemas.microsoft.com/cdo/configuration/sendpassword") = "yourpassword" 'Use SSL for the connection (False or True) objconfigFileds.Item("http://schemas.microsoft.com/cdo/configuration/smtpusessl") = False For a full list of the CDO configuration fields, please visit CDO Messaging Configuration. Note that if you do not set a CDO configuration, then CDO sets one for you prior to sending out each message using the default values. Creating an email message To create an email message, we first create an CDO message object: Set objMessage = CreateObject("CDO.Message") Secondly, we set this message to use the above setting of CDO configuration to send: objMsg.Configuration = objConfiguration Next, we fill-in Sender, Subject and Recipient fields of the headers and the body text which can be either plain text or HTML. objMsg.Subject = "subject of the message here" objMsg.From = "your email address here" objMsg.To = "addressee's email address here" objMsg.TextBody = "the message text here" Finally, you use the Send method to send the message. objMsg.Send Manipulating files with an email You might like to edit an email message body in a separate file. The following function can be used to load a text file to an email message: function ReadTextFile(strFileName) Dim objFSO, objTextFile, strReadLine Set objFSO = CreateObject("Scripting.FileSystemObject") Set objTextFile = objFSO.OpenTextFile(strFileName,1) do while not objTextFile.AtEndOfStream strReadLine = strReadLine + objTextFile.ReadLine() loop objTextFile.Close() ReadTextFile = strReadLine end function You can attach files to an email message as email attachments. See the code for a comprehensive example Mail.vbs. Please note, when using the AddAttachment method in your scripts you must use a fully qualified pathname as the argument to the method. Using just a file name or a relative path will produce the error " The specified protocol is unknown". If you want to send a message to a large group of persons, say sending an announcement, you can put all the receivers' addresses in a text file and load them to the email message you want to send by using a similar function as above. Even more, you can connect to a database to collect information from the database, generate email messages and send them automatically.

    Lecture 9 Hypertext Applications (HTAs)

    In Lecture 8, we learnt how to write a script to create and send an email. In this lecture, we consider another application of scripting technologies. We learn how to write an HTML Application (HTA). An HTML application is a Windows-based program written in a language that combines HTML and script languages. Such a combination packs the power of Web browsers and scripting. Due to the use of HTML, an HTA requires a Web browser to run. However, it does not require hosting on a Web server to run the embedded scripts because an HTA uses the client machine to run (you have to download and run it locally). Key words HTAs (Hypertext Applications), HTML, DHTML (Dynamic HTML) Why use HTAs Let's start with a code snippet (download from embedScript.html), which is to send a message taken from a web page to a specified address. <HTML> <HEAD> <TITLE>Web Mail</TITLE> <SCRIPT LANGUAGE="VBScript"> Sub cmdSendEmail_OnClick Dim objMsg, objConfiguration, objConfigFields Set objConfiguration = CreateObject("CDO.Configuration") Set objConfigFields = objConfiguration.Fields objConfigFields.Item("http://schemas.microsoft.com/cdo/" & _ "configuration/sendusing") = 2 objConfigFields.Item("http://schemas.microsoft.com/cdo/" & _ "configuration/smtpserverport") = 25 objConfigFields.Item("http://schemas.microsoft.com/cdo/" & _ "configuration/smtpserver") = "email.westernsydney.edu.au" objConfigFields.Update Set objMsg = CreateObject("CDO.Message") objMsg.Configuration = objConfiguration objMsg.Subject = "subject of the message here" objMsg.From = "j.yang@westernsydney.edu.au" objMsg.To = Document.webmail.EmailAddress.Value objMsg.TextBody = Document.webmail.Message.Value objMsg.Send End Sub </SCRIPT> </HEAD> <BODY> <H1>Web Mail</H1> <FORM NAME="webmail"> <B>EmailAddress: </B> <INPUT TYPE="Text" NAME="EmailAddress" SIZE=30> <br> <B>Message: </B><INPUT TYPE="Text" NAME="Message" SIZE=80> <BR> <INPUT TYPE="Button" NAME="cmdSendEmail" VALUE="Send"> </FORM> </BODY> </HTML> The coding structure is obvious - simply a combination of HTML text and VBScript code, where VBScript statements are embedded into an HTML file to create an interactive webpage. It tries to collect a message from the Message textfield and use CDO to send the message. Unfortunately this code does not work. This is because the Web browser that runs the HTML file has no access to the CDO object on the local machine. The Web browser security (sandbox) prevents a browser from accessing local system information. In fact, if you take the VBScript code out from the HMTL and make it a standalone VBScript program, it works well. So this sample code is not what we mean by HTML application. An HTA is an HTML-based script that runs locally in a web browser but is not served via HTTP from a web server. An HTA runs under the security context of the currently logged-in user who executes the script, which widens the script operational features beyond the limited to the browser. In fact, if you insert the following statement <HTA:APPLICATION /> into the second line of the above HTML file and change the extension of the file name from .html to .hta, the program will work well. Download and run embedScript.hta (Note: save the code locally and change the email address and SMTP server name to fit into your case). An HTA gets advantages from HTML and scripting languages. HTML provides an easy control of user interface design. Scripting technologies allows a full control on the client computer. Moreover, HTAs are not subject to the same security constraints as Web pages. Does this mean that HTAs are insecure? No. As with any executable file, the user is asked for permission of downloading an HTA. The user has to save and run the application in the local machine. In other words, the user is fully aware of the running of the program. HTAs are suited to many uses, whether you are prototyping, making wizards, or building full-scale applications. Everything Dynamic HTML and script can deliver¡ªforms, multimedia, Web applications, HTML editors, and browsers¡ªHTAs can too. See Microsoft's HTA tutorial for more details: Introduction to HTML Applications (HTAs). You are also encouraged to search the Web. HTA template An HTA begins with the standard HTML framework but will likely include additional <script> tags to define the functionality of the application. The following is the general format of an HTA: <html> <HTA:APPLICATION options/> <head> <title>HTA test</title> <style>Include Cascading Style Sheet information here</style> <script>Include the program functionality here</script> </head> <body> Include the HTML document defining the HTA format here and call functions or subroutines from this section. </body> </html> It is easy to see that the ONLY visible difference of an HTA from a normal HTML file is the tag <HTA:APPLICATION options/> (besides the difference in file names). For instance, the following are the HTA options of the script ClientCheck.hta we are going to study in this lecture: <HTA:APPLICATION ID="ClientCheck" APPLICATIONNAME="Client Diagnostic Tool" SCROLL="no" SINGLEINSTANCE="yes" WINDOWSTATE="normal" BORDER="thick" BORDERSTYLE="normal" MAXIMIZEBUTTON="yes" MINIMIZEBUTTON="yes" INNERBORDER="yes" SYSMENU="yes" /> Check out the options of HTA:APPLICATION for the meaning of the parameters and other options. The second part of an HTA is the definition of layout style. You are allowed to use cascading style sheet (CCS) to define the look and feel of the application, including font style, size and color. The CSS styles are defined within the <style> tags. You can leave everything to be default if you do not seek for a fancy layout. The third part, and possible the most tricky part, of an HTA is the script. You can write the script in either VBScript or JScript. The script is specified within the <script tags>. For instance, <script language = "VBScript"> The final part is the body where you format a front-end. You can use HTML to define buttons, checkboxes, and text fields for collecting data and out put information. Case study: Checking Client Machine Jeff Fellinge introduced an HTA in his book: IT Administrator's Top 10 Introductory Scripts for Windows, which implements a tool that can be used to gather information for network connectivity, machine configuration and running processes from a client machine. The interface of the program ClientCheck.hta is the following: The script accepts input from the user through HTML forms, including the buttons for controlling the process, the checkboxes for choosing different tasks and the text fields for specifying an IP address for testing. Exactly following the template of HTAs, the file consists the following four components: HTA application declaration (within the tag <HTA:APPLICATION />) Defining document style (within the tag <style>) VBScript (within the tag <script>) HTML body (within the tag <body>) Let's explain the script in more detail. The first subroutine Window_Onload is to configure the initial parameters of the HTA. Note that this subroutine is called automatically when the HTA is run. More specifically, it runs when the _onload event is fired. Sub Window_Onload Dim iReturn, objFSO, objShell, objLocator, strHTML window.ResizeTo 640,480 cmdRun.disabled = False cmdSave.disabled = True On Error Resume Next Set objLocator = CreateObject("WbemScripting.SWbemLocator") If Err <> 0 Then strHTML=Heading("The WMI Core Components do not " &_ "appear to be installed.","Red") & " As a result, both " &_ "the PC Check and Process Check have been disabled. <br><br>" strHTML=strHTML & "<i>To run diagnostics, please download " &_ "and install the core WMI services for Windows.<br>" &_ "Download these files from Microsoft <a href=" & chr(34) &_ "http://msdn.microsoft.com/library/default.asp?url" &_ "=/downloads/list/wmi.asp" & chr(34) & ">here</a>." &_ "</i><br><br>" output.innerHTML= strHTML chkPC.checked=False chkPC.disabled=True chkProcess.checked=False chkProcess.disabled=True End If On Error Goto 0 Set objShell=CreateObject ("WScript.Shell") g_strTemp=objShell.ExpandEnvironmentStrings("%temp%") &_ "/tempdiagnostics.txt" End Sub The subroutine first sets the size of the HTA widow, enables the Run button and disable the Save button. Next, it creates a SWbemLocator object. SWbemLocator is a scripting object that can get access to WMI on a particular host computer, much as the WMI moniker "winmgmts:" The next segment of code provides basic error handling. The second subroutine PerformDiagnostics is used to launch the processes of PC check, Process check and Network check in response to the user's selection. The functions PCcheck, Processcheck and Networkcheck are designed to perform the functionality of checking information about the computer, current running processes, and network. The PC Check subroutine uses WMI to demonstrate how to retrieve a variety of information from a local computer. The information is collected from five different WMI classes: Win32_OperatingSystem, Win32_BIOS, Win32_ComputerSystem, Win32_Processor, and Win32_LogicalDisk. The Process Check subroutine also uses WMI in order to retrieve the information of the active processes. The WMI class that is used in the subroutine is Win32_Process, which contains the information about the active processes, such as the process name, the command line that was used to start it, how much memory the process has consumed, the number of page faults caused by the process, and others. The Network Check subroutine uses WSH run methods and FSO methods to drive external applications such as ping, ipconfig, and tracert. Before running the test, the user can specify the IP address of a remote computer to measure the quality of the connection between the two computers. By default, this value is set to the 127.0.0.1, or localhost. There are a few other subroutines or functions that are used for formating, save test results and quit the HTA. I would recommend all of you to read the code carefully for an in-depth understanding. Thanks for your time.

    Lecture 10 CGI Scripting

    The techniques we have learnt in the previous lectures are mostly for client side programming. In other words, the code is executed at the machine the user is running. However, for most Internet applications, significant amounts of processing must be performed on the server side. For instance, to build an online booking system for a hotel, all the enquiries on the availability of hotel rooms have to be transfered to a server where the database of booking information is situated. Getting a Web server to perform application processing is not necessarily complicated. Most Web servers support the Common Gateway Interface (CGI) protocol, which allows a degree of interaction between the client browser and the server. For instance, our school Web server supports CGI. Therefore we can build a website based on our school Web server. In the last two lectures, we will learn the basic scripting techniques for building a website using CGI. CGI applications can be written in any language. However, the standard all-purpose languages, such as C, C++, and Java, are mostly too heavy for simple CGI applications. The commonly used languages for CGI applications are scripting languages, such as Unix shell script, Perl, PHP, VBScript and so on. Among them, the most popular languages for small CGI applications are Perl and PHP. Key words CGI, Client-side/Server-side Web Programming, Perl, PHP In this unit, we only use Perl. The reason I pick up Perl rather than PHP is that I know Perl more than PHP, although both are good and easy to learn. For basic knowledge on Perl, here is an online book: Simon Cozens, Beginning Perl. Lab setup We will not systematically introduce CGI and Perl language. Instead, we learn by practice. To make this possible, we have to set up a server which support CGI. For Windows system, you need to run IIS and install Perl interpreter. For unix system, the school Web server supports CGI and has Perl interpreter installed. Therefore we only have to learn how to use the facility. Let me explain the steps of CGI server setting by using a simple example. Before we start, you need to download the client side program firstCGITest.html and the server side program myFirstCGI.cgi [Note: If you are not allowed to download .CGI file, try this link]. Store them in a folder on your local machine. Next, we install the server side program to the school Web server via the following steps: 1. Logon to the School unix server through SSH. If you have never used SSH before, please refer to the school Website: https://www.scem.westernsydney.edu.au/home/support/secureshell. 2. Create a folder called Homepage (case sensitive) if it does not exist, and make the folder executable by all by executing (skip this step if the folder already exists): mkdir Homepage chmod 755 Homepage 3. Go inside the subfolder Homepage. Create another subfolder cgi-bin and make it executable by all (skip this step if the folder already exists): cd Homepage mkdir cgi-bin chmod 755 cgi-bin 4. You also have to make your home directory executable: cd chmod 755 . Note that there is a dot at the end of the above command. 5. From the SSH main menu, choose window -> New File Transfer. You will see a new window: SSH Secure File Transfer. 6. Choose Operation -> File Transfer Mode -> ASCII from the new window. 7. Go inside the subdirectory cgi-bin under Homepage (on the right column of the window). Upload the file myFirstCGI.cgi. 8. Change the attribute of the file to be everybody can run: chmod 711 myFirstCGI.cgi 9. Open firstCGITest.html file on your local computer by using a text editor. You will see <html><head><title>My First CGI</title> </head><body> <form action="http://staff.scem.westernsydney.edu.au/cgi-bin/cgiwrap/~jianhua/myFirstCGI.cgi"> <h1>Connect to the server.</h1> <input type="submit"> </form> </body> </html> Change the URL http://staff.scem.westernsydney.edu.au/cgi-bin/cgiwrap/~jianhua/myFirstCGI.cgi into your login name: http://student.scem.westernsydney.edu.au/cgi-bin/cgiwrap/~XXXXXXX/myFirstCGI.cgi, where XXXXXXX is your school user id. 10. If you are not using the school lab computer, you must connect your computer to the school network using VPN. 11. Run firstCGITest.html by using a Web Browser from your local computer. Click Submit button. If you can see: Congratulations! You have successfully connected to the server. then the job is done. Otherwise, check if you have had followed all the above steps. Do these steps again if necessary. HTML Forms The most common way for a user to communicate information from a Web browser to the server is through a form. In the above client side program, the form defines an action that calls a CGI program on the Web server: <form action="http://staff.scem.westernsydney.edu.au/cgi-bin/cgiwrap/~jianhua/myFirstCGI.cgi"> </form> In fact, it does nothing but specifies the URL of the CGI script myFirstCGI.cgi on the school web server (note that the URL is different from the path of the file). You can actually call this script manually from a web browser using the URL: http://staff.scem.westernsydney.edu.au/cgi-bin/cgiwrap/~jianhua/myFirstCGI.cgi A form is defined by the <form> tag. The tag can contain a few attributes, which further specifies the properties of the form. The most frequently used attributes are: action: specifies the URL where Web application is located. method: specifies which HTTP method will be used to submit the form data set. Possible (case-insensitive) values are "get" (the default) and "post". enctype: specifies the content type used to submit the form to the server (when the value of method is "post"). The default value for this attribute is "application/x-www-form-urlencoded". The value "multipart/form-data" should be used in combination with the INPUT element, type="file". name: specifies the id of the form so that the form may be referred to from style sheets or scripts. See more attributes of a form from http://www.w3.org/TR/html401/interact/forms.html. A form can be controlled by a set of widgets, which is used for text, passwords, checkboxes, radio buttons, Submit button and Reset button. A widget is defined by the <input> tag. For instance, the following statement specifies a text input box: <input type = "text" name = "giveItaName" size = "20"/> Similarly, the following statement defies a radio button: <input type="radio" name="sex" value="Male"> You may contain as many widgets as required. In any case, you must define a submit button; otherwise the action specified in the form tag will not be taken and the data collected by the input fields will not be transferred to the server. A submit button can also trigger a call to a local script embedded in the HTML file or an HTA. To learn how to define a form, see another more complicated example moreForms.htm. Note that the action specified in this form is to call the default email program to send the collected information to the specified receiver. For more detailed instructions for building a form, see http://www.w3.org/TR/html401/interact/forms.html. CGI scripts The Common Gateway Interface (CGI) is a standard protocol for a Web server to pass a Web user's request to an application program and to receive data back to forward to the user. When a user fills out a form on a Web page and sends it in, it usually needs to be processed by an application program. The Web server typically passes the form information to a small application program that processes the data and may send back a confirmation message. This method or convention for passing data back and forth between the server and the application is called the common gateway interface (CGI). It is part of the Web's Hypertext Transfer Protocol (HTTP). With such an interface, we can write a CGI application in a number of different languages, such as C, C++, Java. However, since most of the CGI applications are quite small, it is more popular to use a scripting language such as unix shell, Perl, PHP, VBScript and etc., to write a CGI application. In this lecture, we use Perl. The following code is the CGI application (myFirstCGI.cgi) you just put on the school server under your Homepage: #!/usr/bin/perl use CGI ':standard'; print "Content-type: text/html\n\n"; print "Congratulations! You have successfully connected to the server."; The code is written in Perl. The first line of the code simply tells the Web server to call a Perl interpreter to execute this code. The next statement specifies the module we use in CGI, which is the standard module. The next two print statements are the messages that are sent to the client's browser. Therefore it is a way the server communicates with clients. The first print statement is telling the client browser that the coming MIME content is of type text/html. Note that there is a space between Content-type: and text/html\n\n. Note that the browser won't be able to display the output at all without this line. Interaction between the server and clients One may wonder how the server side program communicates with clients. To see the secrete inside, let's try the following example: Server side program myName.cgi: [Note: If you are not allowed to download .CGI file, try this link - a zip file with all .CGI files used in Lectures 10 and 11 as well as relevant pracs]. #!/usr/bin/perl use CGI ':standard'; my $name = param("myName"); print "Content-type: text/html\n\n"; print "Hello, $name."; Client side program myName.html: <html><head><title>What's your name</title></head> <body> <form action="http://staff.scem.westernsydney.edu.au/cgi-bin/cgiwrap/~jianhua/myName.cgi"> <h1>What's your name?</h1> <input name = "myName" type = "text" size = "25" /> <br> <input type="submit" value ="Submit"> </form> </body> </html> Follow the steps we did before to upload the server-side program to the cgi-bin folder under your unix Homepage and run the client side html file. You will see similar results as shown in the figures below. It is easy to see that in order to capture the content of the text field, named myName, in the client side program, call the param function in the server-side program as param("myName"). The function will return the content that has been filled in the text field. We will show more complicated examples in next lecture.

    Lecture 11 Server Side programming Using Perl

    In the previous lecture, we have learnt the basic concept of CGI and server side programming. In this lecture we'll reinforce CGI programming skills via a set of examples, where file operations are to be illustrated. Note that all these examples are very fragile. I did not include too much error catching in the code in order to make the code more readable. Any change on the code could cause problem to run. All the code is tested in my working environment. To make the code working for you, the URL of your CGI program should be in the following format: http://student.scem.westernsydney.edu.au/cgi-bin/cgiwrap/~XXXXXXX/YYYYYYY.cgi where XXXXXXX is your school user id and YYYYYY is your CGI program name. To run your CGI, you must be connect to the school using VPN or work at school lab. Key words CGI (Common Gateway Interface), Client-side/Server-side Web Programming, Perl, PHP Reference to textbook chapters For basic knowledge on Perl, here is an online book: Simon Cozens, Beginning Perl. There are also plenty of online Perl tutorials over the Web. File operations: read files The following script readTextFile.cgi can read a text file (lyrics.txt) from the server and publish the content of the file to the client's browser. #!/usr/bin/perl -w use CGI qw ( :standard); print "Content-type: text/html\n\n"; $file="lyrics.txt"; open(FILE, "<$file") or die("The file could not be opened!"); while($line=<FILE>){ print("$line <br>"); } close(FILE); The program simply reads the file lyrics.txt line-by-line and outputs to the client's browser. $file is a variable, which is used to store the name of the input file. Similar to VBScript, we do not need to declare a variable before we use it. We also do not need to worry about the type of an variable. The statement open(FILE, "<$file") is used to open the file. The label FILE is called filehandle, which is used for file processing. We can view it as a reference of $file. Note that the symbol "<" in the statement indicates that the file is opened for reading. You do not need to set the text file to be 'everybody can read'. It just needs to be accessible by your script. If the file is placed in a different directory other than cgi-bin, you need to specify its relative path, say "../../documents/lyrics.txt". To call this script, you can simply type in this URL: http://staff.scem.westernsydney.edu.au/cgi-bin/cgiwrap/~jianhua/readTextFile.cgi in your Web browser. You can also write a HTML file to call the script (readTextFile.html): <HTML> <HEAD> <TITLE>Read File</TITLE> </HEAD> <BODY> <FORM ACTION="http://staff.scem.westernsydney.edu.au/cgi-bin/cgiwrap/~jianhua/readTextFile.cgi" METHOD="POST"> <INPUT TYPE="submit" VALUE="Get file"> </FORM> </BODY> </HTML> Remember to change the URL to fix your working environment when testing your own CGI code. File operations: write files The code for write a message into a text file is similar. Note that the resulting file is stored in the server side. First, let's look at the client-side program writeTextFile.html: <HTML> <HEAD> <TITLE>Write a message</TITLE> </HEAD> <BODY> <FORM ACTION="http://staff.scem.westernsydney.edu.au/cgi-bin/cgiwrap/~jianhua/writeTextFile.cgi" METHOD="POST"> Write your message here<br> <TEXTAREA NAME="message" ROWS=4 COLS=45></TEXTAREA> <P><INPUT TYPE="submit" VALUE="Send"> </FORM> </BODY> </HTML> Run the client-side program before you install the server-side CGI program to get a feeling of the HTML form. In fact, it takes client's message from a textarea and send it to the server via a CGI query. The server catches this query and write the message into a file (logfile.txt). The server side program writeTextFile.cgi is the following: #!/usr/bin/perl use CGI qw(:standard); print "Content-type: text/html\n\n"; $content = param("message"); $file="logfile.txt"; open(FILE, ">$file") || die("Fail to open the file"); print FILE "$content"; close (FILE); print "Thanks for your message."; The program is almost the same as "readTextFile.cgi" except: 1.the statement that catches the message from the client side program and save it to the variable $content: $content = param("message"); 2.and the statement that open the file logfile.txt for write: open(FILE, ">$file") Note that ">" means overwriting the file. To append data to the file, use ">>". Upload files to the server programmatically First, create a special folder at your server (not necessarily readable and writable to every body but should be true to your script) where you are going to upload files. For instance, you can make a folder named "upload" under your home directory in Unix drive by the following commands: cd ~ mkdir upload Next you create a client side program to collect client's files ( uploading.html): <html><head><title>Uploading Files</title> </head><body> <form action="http://staff.scem.westernsydney.edu.au/cgi-bin/cgiwrap/~jianhua/uploading.cgi" method="post" enctype="multipart/form-data"> What file would you like to upload? <input type="file" name="uploadfile" size="30"><br> <input type="submit"> </form> </body> </html> Download the file and save it locally. Change the URL to point to the CGI code on your server. Now the job left is to write a server side program to accept the files to upload. See uploading.cgi: #!/usr/bin/perl -w use CGI qw/:standard/; print "Content-type: text/html\n\n"; my $file = param('uploadfile'); my $upload_dir = ">../../upload"; my $fileName = $file; $fileName =~ s/.*[\/\\](.*)/$1/; if ($file) { open (UPLOAD, ">$upload_dir/$fileName") || Error (); my ($data, $length, $chunk); while ($chunk = read ($file, $data, 1024)) { print UPLOAD $data; } close (UPLOAD); print "<p>Thank you for uploading <b>$fileName</b>."; } else { print "No file was chosen."; } sub Error { print "Couldn't open temporary file: $!"; exit; } In the above code, the first three line are standard. The highlighted block in blue defines the file names of the file to upload and the file to save. The variable $file holds the file name to upload (now on your local machine). $upload_dir specifies the folder "upload" your just created. $fileName gives the name of the file to be saved on the server. Note that the saved file name is the same as its original name except the possible path of the original file has been removed (use regular expression). The highlighted part in red reads the file to upload, block-by-block, and save it to the file on the server. The read function reads 1024 bytes data from $file to $data variable each time. The print statement saves the data from $data to UPLOAD, a reference of the saved file. Password checking The final example I am going to show you is the code for checking user id and password. The client side code password.html is the following: <html><head><title>Verifying a username and a password</title> </head><body> <h2>Type in your username and password below. </h2> <form action="http://staff.scem.westernsydney.edu.au/cgi-bin/cgiwrap/~jianhua/password.cgi" method="post"> <table><tbody><tr> <td>Username:</td> <td> <input name="username" type="text"> </td> </tr><tr> <td>Password:</td> <td> <input name="password" type="password"> </td> </tr><tr> <td> <input type="submit" value="Enter"> </td> </tr> </tbody></table> </form> </body></html> As usual the URL points to the CGI program password.cgi. Two inputs widgets accept user name (as text) and password (as password), respectively. Note that the Web browser can automatically blind user's input of password. The server side program (password.cgi) is a bit more complicated. #!/usr/bin/perl -w use CGI qw( :standard ); print "Content-type: text/html\n\n"; $testUsername = param( "username" ); $testPassword = param( "password" ); open(FILE, "password.txt" ) || die( "The database could not be opened." ); while ( $line = <FILE> ) { chomp( $line ); ( $username, $password ) = split(",", $line ); if( $testUsername eq $username ) { $userVerified = 1; if( $testPassword eq $password ) { $passwordVerified = 1; last; } } } close( FILE ); if ( $userVerified && $passwordVerified ) { accessGranted(); }elsif ( $userVerified && !$passwordVerified ) { wrongPassword(); }else { accessDenied(); } sub accessGranted{ print "Permission has been granted"; } sub wrongPassword{ print "You entered an invalid password. Access has been denied."; } sub accessDenied{ print "You have been denied access to this site."; } The core of the program is the highlighted part in red. It reads the password.txt file line-by-line. Each line of the file is in the format: username, password. The chomp function removes any terminating newline characters from its parameter. The split function splits each line into two parts and store the result into the array $username, $password. The two if statements check user name and password, respectively (match the information provided by a user to records stored in a file). The rest of the code is trivial. Tips for debugging a Perl program 1. Always start from the simplest code and make sure it works well. Add more functionalities one by one. Once you implement a new functionality, save it to a backup folder before you add more functionalities to it. 2. A server side program is supposed to be small. Too complicated programs would slow down the server. 3. A CGI program needs to be everybody executable. However, you should keep other file to be safe, especially the password database. 4. Perl and Unix commands are case sensitive.

    Lecture 12 Conclusion

    We have learnt the basic scripting techniques from the previous eleven lectures. By using FSO, ADSI, and WMI, we can retrieve information of a local or network computer, execute a Windows command, remotely control a network computer, and manipulate domains, groups and users programmatically using VBScript. We have also learnt how to write a CGI script using Perl. All of these form the foundation of Windows system administration. We tried a few new approaches in teaching this subject. All the lectures are online so that students can "attend" the lectures without need to travel. Students' work was checked individually to ensure that every student can actually do the job. One may wonder what if we use the traditional approach to deliver the subject. The ideas to use this online approach are the following: 1.Script programming is mainly a skill that needs more practice. As mentioned in the practical sessions, the skill of programming is like the skill of driving. You can't learn to drive by attending a university course or watching other persons to drive. You have to do it by yourself. 2.The main difficulty of script programming is not the scripting language but the background knowledge of using the language. For instance, to use ADSI and WMI, we need to know which Windows object contains what information. There are thousands of Windows objects. Even searching for a related object or attributes of an object can be a burden, it's less feasible to include all the details of the objects in lecture notes. With online lectures, we can refer to related knowledge by using hypertext links to the related Websites, say Microsoft's MSDN. Actually, you may often need to search the Web on demands when reading the lecture note. So a set of key words have been provided for in each lecture your convenience. In addition, the textbook itself is also in an eBook format. 3.As a hands-on subject, it is important that the skill of programming is built step-by-step. Checking students' work individually can "push" students to follow the designed learning process. Due to some uncontrollable situation, not all the ideas above have been implemented. Nevertheless, I have been enjoying the teaching of this subject even though it took me considerable time to maintain this unit throughout the semester. Trust you enjoyed the unit too. =========Thank you and Good luck=========

    to pipe a script to WScript

    Short answer is No unfortunately. The WScript Engine does not provide a way to pass script either piped or via the command arguments, the only option is using StdIn to interpret and process the commands.

    Simple HTTP Server in VB.Net

    Imports System.Net Imports System.Net.Sockets Imports System.Text Imports System.Threading Public Class Server #Region "Declarations" Private Shared singleServer As Server Private Shared blnFlag As Boolean Private LocalTCPListener As TcpListener Private LocalPort As Integer Private LocalAddress As IPAddress = GetIPAddress() Private ServerThread As Thread #End Region #Region "Properties" Public Property ListenPort() As Integer Get Return LocalPort End Get Set(ByVal Value As Integer) LocalPort = Value End Set End Property Public ReadOnly Property ListenIPAddress() As IPAddress Get Return LocalAddress End Get End Property #End Region #Region "Methods" Private Function GetIPAddress() As IPAddress With System.Net.Dns.GetHostEntry(System.Net.Dns.GetHostName()) If .AddressList.Length > 0 Then Return New IPAddress(.AddressList.GetLowerBound(0)) End If End With Return Nothing End Function Friend Shared Function getServer(ByVal LocalPort As Integer, ByVal Optional LocalAddress As String = Nothing) As Server If Not blnFlag Then singleServer = New Server If Not LocalAddress Is Nothing Then Server.singleServer.LocalAddress = IPAddress.Parse(LocalAddress) End If If Not LocalPort = 0 Then Server.singleServer.LocalPort = LocalPort End If blnFlag = True Return Server.singleServer Else Return Server.singleServer End If End Function Public Sub StartServer() Try LocalTCPListener = New TcpListener(LocalAddress, LocalPort) LocalTCPListener.Start() ServerThread = New Thread(AddressOf StartListen) serverThread.Start() Catch ex As Exception Console.WriteLine(ex.Message) End Try End Sub Public Overloads Sub SendResponse(ByVal sData As String, ByRef thisSocket As Socket) SendResponse(Encoding.UTF8.GetBytes(sData), thisSocket) End Sub Public Overloads Sub SendResponse(ByVal bSendData As [Byte](), ByRef thisSocket As Socket) Dim iNumBytes As Integer = 0 If thisSocket.Connected Then If (iNumBytes = thisSocket.Send(bSendData, bSendData.Length, 0)) = -1 Then ' socket error can't send packet Else ' number of bytes sent. End If Else ' connection dropped. End If End Sub Private Sub New() ' create a singleton End Sub Private Sub StartListen() Do While True ' accept new socket connection Dim mySocket As Socket = LocalTCPListener.AcceptSocket If mySocket.Connected Then Dim ClientThread As Thread = New Thread(Sub() Me.ProcessRequest(mySocket)) ClientThread.Start() End If Loop End Sub Private Sub ProcessRequest(ByRef mySocket As Socket) Dim bReceive() As Byte = New [Byte](1024) {} Dim i As Integer = mySocket.Receive(bReceive, bReceive.Length, 0) Dim sRequest = Encoding.UTF8.GetString(bReceive) Dim sResponse As String sResponse = "Your message was : " & sRequest SendResponse(sResponse, mySocket) mySocket.Close() End Sub Public Sub StopServer() Try LocalTCPListener.Stop() ServerThread.Abort() Catch ex As Exception Console.WriteLine(ex.Message) End Try End Sub #End Region End Class It remains to process the request and generate the response in the processRequest method.

    TCP Client/Server Simple Chat Program

    Server Side that accepts Messages from Client Option Explicit On Imports System.IO, System.Net.Sockets Public Class Form1 Dim listener As New TcpListener(4000) Dim client As TcpClient Private Sub Form1_FormClosing(ByVal sender As Object, ByVal e As System.Windows.Forms.FormClosingEventArgs) Handles Me.FormClosing listener.Stop() End Sub Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load listener.Start() Timer1.Start() End Sub Private Sub Timer1_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Timer1.Tick Dim message As String Dim nStart As Integer Dim nLast As Integer If listener.Pending = True Then message = "" client = listener.AcceptTcpClient() Dim reader As New StreamReader(client.GetStream()) While reader.Peek > -1 message &= Convert.ToChar(reader.Read()).ToString End While If message.Contains("<>") Then nStart = InStr(message, "<>") + 4 nLast = InStr(message, "<>") End If TextBox1.Text = message TextBox1.Text = message If message = "#GO" Then MsgBox("Test Command has been receive. xD") End If End If End Sub The Problem is I dont know how to.. Send back message to Client(s) And i want 2 or more clients can connect to this Server... --------------------------------------------------- 2nd Problem is i don't know how to accept Message from Server. Here is the code for Client Side.. Option Explicit On Imports System.IO Imports System.Net.Sockets Public Class Client Dim client As TcpClient Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load End Sub Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click Try client = New TcpClient("127.0.0.1", 8281) Dim writer As New StreamWriter(client.GetStream()) writer.Write("<>" & TextBox1.Text & "<>") writer.Flush() Catch ex As Exception End Try End Sub ' COMMAND BUTTON Send to Server Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click Try client = New TcpClient("127.0.0.1", 8281) Dim writer As New StreamWriter(client.GetStream()) writer.Write("#GO") ' This is for my Future Commands that Can Control Another PC on my Network.. writer.Flush() Catch ex As Exception End Try End Sub End Sub End Class

    scripting Windows Media Player

    Set oPlayer = CreateObject("WMPlayer.OCX") oPlayer.openPlayer("F:\abc.mp3") ' Launches WMP window ' This launches background process, don't want this... 'oPlayer.url = "file:///F:/2014-04-27.mp3" ' Wait for file to load... wscript.sleep 200 ' Check the state of the player... While oPlayer.Playstate <> 3 log "Waiting for player. Current state is: " & oPlayer.Playstate WScript.Sleep 100 Wend oPlayer.controls.pause() wscript.sleep 2000 oPlayer.controls.play()

    simple example

    Dim oPlayer Set oPlayer = CreateObject("WMPlayer.OCX") oPlayer.URL = "C:\Users\User\Music\freesound\955.mp3" oPlayer.controls.play While oPlayer.playState <> 1 ' 1 = Stopped 3 = playing WScript.Sleep 100 Wend oPlayer.close