Windows Script Host Bazaar
     
FAQ

 



 

top Frequently Asked Questions (FAQ)

How can I create a user output?

There are a few ways to create 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"

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

WScript.Echo ("Hello World", 1, "I was here");
Tip: The Echo method enables you to redirect the output to files, if the script is executed in Command Prompt Window (CScript.exe C:\Test\Hello.vbs > MyTxt.txt).

The Popup method exposed from the WScript Shell object provides another way to create script output. 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 brackets:

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 allows you in the 2nd parameter a time-out value. If this value is set to 0, no time-out is used, the dialog box is shown till the user clicks onto a button. With a time-out value set to 10, the dialog box will be closed automatically after 10 seconds, if the user doesn't click the button. The parameter title allow 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 codes are the same as for the Windows Message Box function. And you can retrieve a status code from the Popup method to find out which button was clicked from the user:

var status = objWSH.Popup ("Hello World", time_out, title, buttons);
if (status != 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 a dialog box causes that the system formats the output to fit the size of the user dialog. Sometimes it will be helpful to insert line breaks and tab characters into the text to force line wraps and colums. 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 & "... WSH 2 is released"
WScript.Echo "Name" & vbTab & WScript.FullName

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

WScript.Echo ("Hello World.. \n...WSH 2 is released");
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. Then there are two possibilities to debug a script using Microsoft Script Debugger:

  • The recommended method in WSH 1 is to put a stop statement into the first lines of a VBScript program. In JScript you must use the debugger statement in the code. These statements invoke the script debugger if the statement is executed. Then you may use the debugger to step through your code.
  • In WSH 2 you need to invoke your .js and .vbs files using the switches //D or //X. //X invokes the Debugger after the first statement is reached. //D invokes the debugger only, if a stop or debugger statement is reached.
  • In .wsf files you can supress debugg by inserting a <? debug="false"> processing instruction into the script file.

During a debug session you may use the buttons to execute the code line by line, set break point or inspect variables. To print the value of a script variable within the debugger, use the direct window. This windows may be used to execute command. Enter the command: ? title to display for instance the value of the variable title. In JScript the engine knows no ? command. Therefor you can use the Echo method to display values. With the command WScript.Echo title typed in the direct window you get a dialog box showing the content of your variable.

During debugging a script you must separate between syntax errors and run-time errors. A syntax error can't be found using a debugger, because the language engine doesn't execute the script statements.If a syntax- time error occurs, the script delivers an error dialog specifying the line number within the faulty code. In this case use an editor that shows line numbers (or my WSH IDE) to identify the faulty statement reported in the error dialog.

After all syntax errors are detected and the code is amended, you can use a Script Debugger to test the behavior of your program and find out where run-time errors occur. The debugger highlights the statement where the run-time error was found.

Back

Run-Time 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
On Error Goto 0

The err object returns the error object. The property number was set within the last executed statement to a valid run-time error numer. The property description contains the error text.

Warning: A On Error Resume Next statement directs error handling to a script. An Option Explicit statement inserted in the script's header to detect undeclared VBScript variables won't work until On Error Goto 0 is detected.

JScript provides from script engine 5.0 upward the keywords try ... catch(x) to catch run-time errors. Then 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 { ... }.

Back

How to get script properties?

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

'************************************************
' File: Properties.vbs (WSH sample in VBScript)
' Author: (c) G. Born
'
' Shows the properties of the WSH, the script and
' 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

'*** End
Note: In VBScript you can use & and + for string concatenation. A good programming style uses the & operator to make it clear that a string concatenation and not an addition is shall be used.

Tip: WSH provides a Quit method (WScript.Quit) that can be used to terminate a script. If a parameter is submitted:
VBScript: WScript.Quit 1
JScript: WScript.Quit (1);
this value is returned to Windows as a process termination code. This code may be retrieved using the ERRORLEVEL statement in BAT files. If no value is submitted:

VBScript: WScript.Quit
JScript: WScript.Quit ();

the return code is set to 0. A script doesn't need to be terminated using a WScript.Quit statement. If the last script statement is already executed, WSH terminates the script automatically.

Back

How to get submitted arguments

You can submit arguments to a script. Within the script you must use the Arguments collection to read the arguments. This can be done in VBScript with the following code snipped

Set objArgs = WScript.Arguments ' create object with collection
For i = 0 to objArgs.Count - 1
  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

How to 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 same folder as the script file. Then you may move the the files into other folders. 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;
}
Warning: Some people assuming that the script's folder is equivalent to the current directory. This is true as long as the script is executed using a double-click on the scripts icon. If the script is invoked from a Run dialog, from a Command Prompt Windows or from a shortcut file, the script folder and the current directory will be distinct (see also my title Advanced Development with Microsoft Windows Script Host 2.0, Microsoft Press USA.

Back

How to handle blanks in file names

Some paths (with folder and file names) contain blanks like c:\My script\Folders 1.vbs. Using this path within a script, may cause trouble, because of the blanks within this path. To avoid any confusion, the path need to be enclosed in " (double quotes). A double quote character is defined in VBScript as "" and in JScript as \". The following code encapsulates the path in double quotes. Here is the VBScript code:

Option Explicit
DIM file, oWSH
file = "c:\My script\Folders 1.vbs"

Set oWSH = WScript.CreateObject ("WScript.Shell")
' use a constant as path (use """)
oWSH.Run """c:\My script\Folders 1.vbs""",1,True
' use a variable containing the path (use """")
oWSH.Run """" & file & """",1,True

The first line uses """, because the two "" defines a single double quote within the string. To add a double quote to a string variable, we need to concatenate two strings """" & file. The four """" defines one double quote character string. In JScript use the following code:

var file = "c:\My script\Folders 1.vbs";

var oWSH = WScript.CreateObject("WScript.Shell");
// use a constant as path (use "\")
oWSH.Run ("\"c:\\My script\\Folders 1.vbs\"",
     1,True);
' use a variable containing the path (use "\"")
oWSH.Run ("\"" + file + "\"",1,True);

Back

 

There are many other tricks and undocumented features in Windows and WSH (published in my WSH books).

Copyright (c) by Günter Born
All Rights Reserved