Born's Windows Scripting Host FAQ Page

  • How can I create a user output?
  • How to format the user dialogs?
  • How to debug a script?
  • Error handling in scripts (Check the existence of a Registry entry)
  • How to get the script properties?
  • How to get submitted arguments?
  • Get the path to the script folder
  • How can I create a user output?

    There are a few ways to create a user output. The most simple way is to use the Echo method of the WScript object. In VBScript you may use:

    WScript.Echo "Hello World", 1, "I was here"

    JScript has a slight different syntax, parameters need to be enclosed in parentheses:

    WScript.Echo ("Hello World", 1, "I was here");

    Another way is to use the Popup method of the Shell object. In VBScript you may use:

    time_out = 10      ' wait max. 10 seconds
    title = "WSH sample"
    button = vbOKonly  ' vbOKOnly
                       ' create object
    Set objWSH = WScript.CreateObject("Wscript.Shell")
    objWSH.Popup "Hello World", time_out, title, buttons

    In JScript we have a slight different syntax, so we must enclose the parameters into in parentheses:

    var time_out = 10;   // wait max. 10 seconds
    var title = "WSH sample";
    var button = 0;      // vbOKOnly
                         // create object
    var objWSH = WScript.CreateObject("Wscript.Shell");
    objWSH.Popup ("Hello World", time_out, title, buttons;)

    The Popup method allows you to pass a time-out value in the 2nd parameter. If this value is set to 0, no time-out is used. The dialog box will be shown till the user clicks a button. A time-out value set to 10 for instance, closes the dialog box automatically after 10 seconds, if the user doesn't click a button. The parameter title allows you to specify the title text shown in the dialog box title bar. The parameter button defines the buttons and the icon shown within the dialog box. The values used in buttons  are the same as in the Windows MsgBox function. Popup can return a status code indicating which button was clicked:

    var result = objAdr.Popup ("Hello World", time_out, title, buttons);
    if (result != 0) ......

    In VBScript you can use also the MsgBox function for user dialogs. The function may be called like:

    title = "WSH sample"
    button = vbOKonly ' vbOKOnly
    MsgBox "Hello World", vbOKonly + vbExclamation, title)
    status = MsgBox "Terminate program", vbYesNo + vbQuestion, title)
    if status = vbYes Then WScript.Quit

    Back

    How to format user dialogs?

    Passing a string to MsgBox, Echo or Popup causes an automatic line wrapping within the dialog box. Sometimes it will be helpful to insert line breaks and tab characters into the text, to force line wraps and columns. This may be done either in VBScript or JScript with a small trick: Just add the control codes into the string. For VBScript use the following code:

    WScript.Echo "Hello World..." + vbCRLF + "...the WSH is coming on the horizon"
    WScript.Echo "Name" & vbTab & WScript.FullName

    The (predefined) VBScript constant vbCRLF creates a line wrap and vbTab causes a tab stop within the text. In JScript you may insert the escape sequence characters "\n" for a new line or "\t" for a tab character into the text:

    WScript.Echo ("Hello World.. \n...the WSH is coming on the horizon");
    WScript.Echo ("Name \t " + WScript.FullName);

    Back

    How to debug a script?

    If you have installed the Microsoft Script Debugger on your machine, you can use this tool for debugging purposes. There are two possibilities to debug a script using Microsoft Script Debugger:

    But keep in mind that the Microsoft Script Debugger won't work anymore, after you have installed Visual Studio (because VS comes with its own debugger). Also it seems that the upcoming Microsoft Office 2000 version will have a Script Editor, which includes also a script debugger. If these programs are installed, use the debugger provided within the programs. 

    During a debug session you may use the buttons to execute the code line by line, set break points or inspect variables. To show the value of a script variable within the debugger, use the direct window. This windows may be used also to execute a command. Let's assume your script contains a variable title. To show the value of this variable, enter the command:

    ? title 

    into the direct window. The JScript language engine doesn't know a ? command. Therefore you need to use the Echo method to display a value. Enter the command:

    WScript.Echo title 

    into the direct window. A dialog box with the variable's content is shown.

    Executing a script may causes error messages. Errors will be shown  either in an error dialog box, or in the Microsoft Script Debugger window, or in a dialog box asking for invoking the script debugger (if Microsoft's Script Editor is installed). Errors must be grouped into two categories: syntax errors, which will be detected during the compile process of the language engine (for instance un-terminated string constants). Run-time errors are detected during executing the program (for instance a missing object, an unsupported method and so on).

    The debugger will be invoked only, if the script contains no syntax errors. If there are still syntax errors, WSH terminates the compile process and invokes the error dialog, which displays the line number containing the error. After successful compiling a script, WSH begun to execute (interpret) the compiled code. You can use the Microsoft Script Debugger (or the debugger included in the Script Editor) only, if your program is getting compiled error free. Then you may test the behavior of your program and find out logical program errors. 

    Tip: To locate a faulty line within your source code, an editor which supports line numbering comes in handy. Have a look into my WSH link page (for Primal SCRIPT for instance). There are several editors supporting line numbering. German readers are encouraged to check the test version of M&E WinEdit from http://ourworld.compuserve.com/homepages/MI_Software. This is a small but powerful editor, which may be registered for only 49,- Deutsche Mark. For the English readers I like to encourage to have a look at the following editors. Edit Plus (http://www.editplus.com) is a simple text editor for script editing. My first choice for script development is the PrimalSCRIPT editor (http://www.sapien.com) offered by SAPIEN Inc. This is more than an editor, it's a whole scripting development environment  with integrated help, code snippets and template handling and much more. The new 2.x version will comes with much neat features to develop and test your scripts. Another choice may be CodeMagic . This tool is also a scripting IDE, it is free (in the first version) and fairly customizable. The program may be downloaded from http://www.petes-place.com/codemagic.html. TextPad  and NoteTab  are both shareware editors NoteTab also has a Light version that's freeware. Both editors doesn't support text color highlighting. You can download TextPad from www.textpad.com and NoteTab from www.notetab.com.

    Have also a look into the sneak preview of my WSH book. The Adobe Acrobat files contain a few more explanation about debugging, script editors and more.

    Back

    Error handling in scripts

    Calling a method or using other functions may result in a run-time error. WSH shows the error dialog with the line number and an error number. After closing the error dialog the script terminates. In many cases a script programmer must handle such run-time errors within the code to allow to continue the script execution. In VBScript we can use the statement:

    On Error Resume Next

    If a run-time error occur, the interpreter is forced to resume the script execution with the next statement. For instance, if your try to read a registry entry which doesn't exists, the RegRead-methods fails (unfortunately with a misleading error text). You may use the following code to catch these run-time errors:

    On Error resume next
    wsh.RegRead (.......)
    If err <> 0 Then
      WScript.Echo "Error: " & err.number & " Entry doesn't exists"
      WScript.Quit()
    End if

    The err object delivers the error number which was set within the last executed statement. In JScript (version 3.x) is no err object available. The script engine 5.0 (which is shipped with MS IE 5.0) supports the keywords try ... catch(x) to catch run-time errors. With this language engine you may use the following code:

    try
    {
      wsh.RegRead (.......); ' Registry access
    }
    catch (e)
    {
      if (e != 0)
        {
           WScript.Echo ("Error: " + e + " Entry doesn't exists");
           WScript.Quit(1);
         }
    }

    The statements within the try branch may contain the code to create the run-time error. If a run-time error occurs, the controls is passed to the catch branch. The object variable e receives the error object which may be evaluated within the branch. Important is that you enclose the statements within these branches into brackets { ... }.

    Sample: Check the existence of a Registry key

    Here is a simple VBS script derived from my WSH Tutorial which uses this technique to check whether a Registry key exists. The function KeyExists returns the value true or false.

    '************************************************
    ' File: Registry2.vbs (WSH sample in VBScript) 
    ' Author: (c) Günter Born
    '
    ' Demonstrates the access to the Registry.
    ' Use KeyExist to check wheter a key/value exists.
    '
    ' Use AS-IS, no warranty of any kind.
    '************************************************
    Option Explicit
    
    Dim key1
    Dim WSHShell
    
    ' Get WSHShell object for Registry methods
    
    Set WSHShell = WScript.CreateObject("WScript.Shell")
    
    ' Query key name for new key
    
    key1 = InputBox ("Enter a key (for instance HKCR\.bmp\) ", "Key","HKCR\")
    If KeyExists (key1) = True Then
    MsgBox "Key: " + key1 + " Value: " + WSHShell.RegRead(key1)
    Else
    MsgBox "Key: " + key1 + " doesn't exists"
    End if
    
    WScript.Quit()
    
    ' Helper function: tests, whether the key exists
    Function KeyExists (key)
    Dim key2
    On Error Resume Next
    key2 = WSHShell.RegRead (key)
    If err <> 0 Then
    KeyExists = False
    Else
    KeyExists = True
    End if
    End Function
    
    ' End

    Remark: To avoid some run-time errors (for instance a missing key in RegRead) I wrote my own ActiveX control to check whether a Registry key exists. The WSHExtend control may be downloaded from my WSH Bazaar.

    Back

    How to get script properties?

    Sometimes it is helpful to display the properties of the script, of  WSH or of the script engines. These properties may be retrieved from several sources. The following VBScript program demonstrates how to obtain all those properties and displays them within a dialog box window:

    '************************************************
    ' File: Properties.vbs (WSH sample in VBScript) 
    ' Author: (c) G. Born 
    '
    ' Shows the properties of WSH, of the script and
    ' of the language engine within a dialog box.
    '************************************************
    Option Explicit
    
    Dim Message
    Dim Title
    
    ' init title
    Title = "WSH sample " + WScript.ScriptName + " - by G. Born"
    
    ' Show the properties of the WScript object
    ' we start with Host properties
    
    Message = "WScript host properties" + vbCRLF + vbCRLF
    Message = Message + "Application: " + WScript.Application + vbCRLF
    Message = Message + "Name: " + WScript.Name + vbCRLF
    Message = Message + "Version: " + WScript.Version + vbCRLF
    Message = Message + "FullName: " + WScript.FullName + vbCRLF
    Message = Message + "Path: " + WScript.Path + vbCRLF 
    
    ' Get the Interactive-Status
    If (WScript.Interactive) Then
    Message = Message + "Interactive: true" + vbCRLF 
    Else
    Message = Message + "Interactive: false" + vbCRLF 
    End if
    
    ' Get script properties
    Message = Message + vbCRLF 
    Message = Message + "WScript script properties" + vbCRLF + vbCRLF
    Message = Message + "ScriptFullName : " + WScript.ScriptFullName + vbCRLF
    Message = Message + "ScriptName : " + WScript.ScriptName + vbCRLF
    
    ' get the version of the language engine
    Message = Message + "Script-Engine: " + CStr(ScriptEngine()) + vbCRLF
    Message = Message + "Version: " + CStr(ScriptEngineMajorVersion()) 
    Message = Message + "." + CStr(ScriptEngineMinorVersion()) + vbCRLF
    Message = Message + "Build: " + CStr(ScriptEngineBuildVersion())
    
    MsgBox Message, vbInformation + vbOKOnly, Title
    
    WScript.Quit() ' terminate script 
    ' End

    NOTE: Here I like to give a short remark about string concatenation in VBScript. In VBScript you may use the & operator to concatenate sub strings (like text = "Hello " & "World"). This is the method which shall be preferred. Within my sample VBScript scripts you will find also the + operator to concatenate sub strings (like text = "Hello " + "World"). VBScript uses the add operation for the expression. Because we have strings, both sub strings are concatenated. But in a mixed expression (x = 10.0 + "Hello") this operator causes a run-time error because of a type mismatch. I have used the + operator, because I ported several samples from VBScript to JScript and vice versa. In JScript string concatenation must be done using the + operator. 

    Back

    How to get submitted arguments

    You can submit parameters (also called arguments) to scripts. Within a script you must use the Arguments collection to read all arguments. This can be done in VBScript using the following code snippet: 

    Set objArgs = WScript.Arguments ' create object with collection
    For i = 0 to objArgs.Count
      WScript.Echo objArgs(i)
    Next

    In JScript you may use a similar code. It is only important that you exchange the Count property with the length property (because Count isn't supported in JScript).

    Back

    Get the path to the script folder

    To execute a program or load a file, it might be helpful, if the file is located in the script file's folder. Then you may move both files into another folder. As long as all files are in one folder, the script will work. To get the path to the script file folder, use the following function in VBScript:

    Function GetPath
    ' Return path to the current script
    DIM path
    path = WScript.ScriptFullName  ' script file name
    GetPath = Left(path, InstrRev(path, "\"))
    End Function

    In JScript use the following function:

    function GetPath ()
    // Retrieve the script path
    {
    var path = WScript.ScriptFullName;  // script name
    path = path.substr(0,path.lastIndexOf("\\")+1);
    return path;
    }

    Back

    There are many other tricks and undocumented features in Windows 98 and WSH. Some other stuff is contained within the other pages. I have published it all in my WSH book.


    Do you feel these samples are useful? Comments, suggestions? Found some errors (yeah, I know, my English isn't perfect). Please post me a note.


    by Günter Born