Here is what I am trying to do:
- Get a VBScript to run another VBScript.
- get the second VBScript to post an error on completion, either 0 if successful or >0 if not back to the original script and then work on conditions Based on the error code returned.
Uninstall 2010 & copy office 2013
'Copy files from a network share to machine
Set FSO = CreateObject("Scripting.FileSystemObject")
WScript.Echo "Starting to uninstall Microsoft Office 2010 from the machine"
FSO.CopyFile "\\data01\Tools\WSM\Copy_2013.vbs", "C:\temp\Copy_2013.vbs"
FSO.CopyFile "\\data01\Tools\WSM\OffScrub10.vbs", "C:\Temp\OffScrub10.vbs"
FSO.CopyFile "\\data01\Tools\WSM\DeleteOffice13Package.vbs", "C:\temp\DeleteOffice13Package.vbs"
'Wait to execute rest of script where copied filed need to be in location
WScript.Sleep 5000
'Executes Office 2013 copy at the same time, do not wait to continue uninstalling office 2010
Set objShell = WScript.CreateObject("WScript.Shell")
Call objShell.Run("C:\temp\Copy_2013.vbs", 0, False)
WScript.Sleep 3000
'Run VBScript that uninstalls office 2010 (currently set to copy a non existent path for error capture test)
strRemoveOffice10 = "c:\Temp\offscrub10.vbs ALL /Quiet /NoCancel"
Call objShell.Run(strRemoveOffice10, 0, True)
WScript.Echo Err.Number
If Err.Number <> 0 Then WScript.Echo " Microsoft Office 2010 could not be uninstalled. Please uninstall again manually."
If Err.Number = 0 Then WScript.Echo "Microsoft Office 2010 has uninstalled from the machine"
Set objFileSys = Nothing
WScript.Quit
OffScrub10.vbs
Dim objFileSys
Set objFileSys = CreateObject("Scripting.FileSystemObject")
objFileSys.GetFolder("C:\Temp\Temp1\bla").Copy "C:\WSM\Test"
On Error Resume Next
If Err.Number <> 0 WScript.Quit Err
asked Jan 9, 2017 at 12:16
1
To enable error handling you need to put On Error Resume Next
before the statement that may cause an error. Then you can return a status code like this:
Set fso = CreateObject("Scripting.FileSystemObject")
On Error Resume Next
fso.GetFolder("C:\Temp\Temp1\bla").Copy "C:\WSM\Test"
WScript.Quit Err.Number
However, since you said you want a return value >0 in case of an error and Err.Number
is an unsigned integer that might be interpreted as a positive or negative value depending on its actual value, something like this might be a better choice:
Set fso = CreateObject("Scripting.FileSystemObject")
On Error Resume Next
fso.GetFolder("C:\Temp\Temp1\bla").Copy "C:\WSM\Test"
If Err Then WScript.Quit 1
WScript.Quit 0 'can be omitted, because it's the default
To check the returned value in the calling script you need to capture it in a variable. When using the Call
statement like you do in your first script the return value is simply discarded. VBScript does not put return values of external commands in the Err
object. You may also want to make sure that your script is being run with cscript.exe
to avoid messages/popups blocking execution.
strRemoveOffice10 = "cscript.exe c:\Temp\offscrub10.vbs ALL /Quiet /NoCancel"
rc = objShell.Run(strRemoveOffice10, 0, True)
If rc = 0 Then
'OK
Else
'an error occurred
End If
answered Jan 9, 2017 at 13:03
Ansgar WiechersAnsgar Wiechers
193k25 gold badges256 silver badges330 bronze badges
0
Yes, you can return an exit code from your second script to the first as follows…
WScript.Quit(-1)
Where -1 is your exit code of choice.
answered Jan 9, 2017 at 12:19
Nick AllanNick Allan
3874 silver badges10 bronze badges
Option Explicit
If WScript.Arguments.Count = 0 Then
' If we don't have any arguments, call ourselves to retrieve
' the exit code. It will be returned by the call to the
' Run method
Dim returnCode
returnCode = WScript.CreateObject("WScript.Shell").Run ( _
Chr(34) & WScript.ScriptFullName & Chr(34) & " myArgument " _
, 0 _
, True _
)
' Note ^ the "True"
' We need to wait for the "subprocess" to end to retrieve the exit code
Call WScript.Echo(CStr( returnCode ))
Else
' We have arguments, leave current process with exit code
Call WScript.Quit( 1234 )
End If
Quick sample for testing.
There are two elements to consider:
- The called subprocess uses the
WScript.Quit
method to return the process exit code to the caller - The caller must wait for the subprocess to end to retrieve the exit code. The
Run
method will return the exit code of the subprocess
answered Jan 9, 2017 at 12:50
MC NDMC ND
69.6k8 gold badges84 silver badges126 bronze badges
На чтение 8 мин Просмотров 1.1к. Опубликовано
В этой статье мы рассмотри обработку ошибок в языке VBScript, а именно объектErr, конструкцию On Error Resume Next и On Error Goto 0. Конструкция VBScript On Error Resume Next включает обработку ошибок, а On Error Goto 0 отменяет их обработку.
Объект Err не нуждается в предварительном объявлении, и доступен всегда, давайте рассмотри его методы и свойства:
- Description — данное свойство содержит описание ошибки.
- Number — содержит целое число – номер ошибки. Если значение свойства Number ровно нулю – значит, ошибка отсутствует.
- Source — свойство содержит название приложения, в котором возникла ошибка.
Методы
Clear – полная очистка информации об ошибке. Стоит обратить внимание, что информация об ошибке автоматически очищается при выполнении операторов On Error Resume Next, Exit Sub и Exit Function.
Raise(number, [source, description]) – данный метод позволяет генерировать собственную ошибку времени выполнения. Видим, что тут можно задать параметры, аналогичные по своей принадлежности свойствам самого объекта Err. Видим, что тут является обязательным только первый параметр.
Хорошо, теперь давайте рассмотри четыре примера на языке vbscript.
Пример 1
'------------------------------------------------------------------------------ ' vbscript on error resume next ' произойдет вычисление только для первых 3 значений ' on_error_1.vbs '------------------------------------------------------------------------------ Option Explicit 'включаем обработку ошибок On Error Resume Next dim MyArr(8), icount, Result, msgErr, msg ' заполняем массив MyArr(0) = 5 MyArr(1) = -3 MyArr(2) = 15 MyArr(3) = 0 MyArr(4) = 2 MyArr(5) = 6 MyArr(6) = 0 MyArr(7) = -1 icount=0 msg="" msgErr = "Ошибка!!!" & vbCrLf 'циклично делим число 15 на каждый элемент массива Do result=15/MyArr(icount) If Err.Number <> 0 Then msgErr=msgErr & "Код ошибки: " & Err.Number & vbCrLf &_ "Описание: " & Err.Description & vbCrLf &_ "Приложение: " & Err.Source & vbCrLf result = msgErr msgErr="" end if icount = icount+1 msg=msg & Result & vbCrLf & vbCrLf Loop While (icount < 8) MsgBox msg
В данном примере мы создали массив из 8 элементов, каждый из которых является числом, два элемента – являются нулями. В цикле do…loop (работа данного цикла рассмотрена в статье Урок 7 по VBScript: Циклы do…loop и while…wend) идет деление числа 15 на каждый элемент массива (Урок 9 по VBScript: Массивы). Так как мы не включили в данном примере очистку информации об ошибке, то произойдёт деление только первых трёх значений, а всё остальное будет принято за ошибку.
Пример 2
'------------------------------------------------------------------------------ ' vbscript on error resume next ' Вычисления не произойдут ' on_error_2.vbs '------------------------------------------------------------------------------ Option Explicit 'включаем обработку ошибок On Error Resume Next dim MyArr(8), icount, Result, msgErr, msg ' заполняем массив MyArr(0) = 5 MyArr(1) = -3 MyArr(2) = 15 MyArr(3) = 0 MyArr(4) = 2 MyArr(5) = 6 MyArr(6) = 0 MyArr(7) = -1 icount=0 msg="" msgErr = "Ошибка!!!" & vbCrLf 'циклично делим число 15 на каждый элемент массива Do result=15/MyArr(icount) If Err.Number <> 0 Then msgErr=msgErr + "Код ошибки: " & Err.Number & vbCrLf &_ "Описание: " & Err.Description & vbCrLf &_ "Приложение: " & Err.Source & vbCrLf result = msgErr msgErr="" ' Отменяем обработку ошибок!!! On Error Goto 0 end if icount = icount+1 msg=msg & result & vbCrLf & vbCrLf Loop While (icount < 8) MsgBox msg
Тут мы дополнительно использовали конструкцию On Error Goto 0, которая отключает обработку ошибок. Это приведёт к тому, что никакие вычисления не будут произведены, и при запуске сценария автоматически произойдёт ошибка времени выполнения.
Скачать архив с примерами
Пример 3
'------------------------------------------------------------------------------ ' on error resume next vbscript ' Правильный подход обработки ошибок ' on_error_3.vbs '------------------------------------------------------------------------------ Option Explicit 'включаем обработку ошибок On Error Resume Next dim MyArr(8), icount, Result, msgErr, msg ' заполняем массив MyArr(0) = 5 MyArr(1) = -3 MyArr(2) = 15 MyArr(3) = 0 MyArr(4) = 2 MyArr(5) = 6 MyArr(6) = 0 MyArr(7) = -1 icount=0 msg="" msgErr = "Ошибка!!!" & vbCrLf 'циклично делим число 15 на каждый элемент массива Do 'Очищаем информацию об ошибке Err.Clear result=15/MyArr(icount) If Err.Number <> 0 Then msgErr=msgErr + "Код ошибки: " & Err.Number & vbCrLf &_ "Описание: " & Err.Description & vbCrLf &_ "Приложение: " & Err.Source & vbCrLf result = msgErr msgErr="" end if icount = icount+1 msg=msg & result & vbCrLf & vbCrLf Loop While (icount < 8) MsgBox msg
В этом примере мы сделали все правильно, так как вначале цикла прописали Err.Clear, который очищает информацию о предыдущих ошибках.
Ну и наконец четвертый пример, тут мы генерируем собственное описание ошибки.
Пример 4
'------------------------------------------------------------------------------ ' on error resume next vbscript ' генерация собственной ошибки ' on_error_4.vbs '------------------------------------------------------------------------------ Option Explicit 'включаем обработку ошибок On Error Resume Next dim MyArr(8), icount, Result, msgErr, msg ' заполняем массив MyArr(0) = 5 MyArr(1) = -3 MyArr(2) = 15 MyArr(3) = 0 MyArr(4) = 2 MyArr(5) = 6 MyArr(6) = 0 MyArr(7) = -1 icount=0 msg="" msgErr = "Ошибка!!!" & vbCrLf 'циклично делим число 15 на каждый элемент массива Do 'Очищаем информацию об ошибке Err.Clear result=15/MyArr(icount) If Err.Number <> 0 Then Err.Raise 100, "текущий сценарий", "пробуем делить на ноль" msgErr=msgErr + "Код ошибки: " & Err.Number & vbCrLf &_ "Описание: " & Err.Description & vbCrLf &_ "Приложение: " & Err.Source & vbCrLf result = msgErr msgErr="" end if icount = icount+1 msg=msg & result & vbCrLf & vbCrLf Loop While (icount < 8) MsgBox msg
Давайте подытожим сказанной в данной статье…. Должен сказать, что материал получился довольно сухим на предмет обзора, это и не удивительно — большую часть занимают примеры программного кода. В целом, мы рассмотрели внутренний объект Err, который содержит методы и свойства для обработки исключительных ситуаций в сценариях на языке VBSCRIPT.
Чтобы включить обработку ошибок вам нужно поставить On Error Resume Next
перед утверждением, которое может вызвать ошибку. Затем вы можете вернуть код состояния, например:
Set fso = CreateObject("Scripting.FileSystemObject")
On Error Resume Next
fso.GetFolder("C:\Temp\Temp1\bla").Copy "C:\WSM\Test"
WScript.Quit Err.Number
Тем не менее, поскольку вы сказали, что хотите вернуть значение>0 в случае ошибки и Err.Number
целое число без знака, которое может быть интерпретировано как положительное или отрицательное значение в зависимости от его фактического значения, что-то вроде этого может быть лучшим выбором:
Set fso = CreateObject("Scripting.FileSystemObject")
On Error Resume Next
fso.GetFolder("C:\Temp\Temp1\bla").Copy "C:\WSM\Test"
If Err Then WScript.Quit 1
WScript.Quit 0 'can be omitted, because it's the default
Чтобы проверить возвращаемое значение в вызывающем скрипте, вам нужно записать его в переменную. При использовании Call
утверждение, как вы делаете в вашем первом скрипте, возвращаемое значение просто отбрасывается. VBScript не помещает возвращаемые значения внешних команд в Err
объект. Вы также можете убедиться, что ваш скрипт запускается с cscript.exe
чтобы избежать блокирования сообщений / всплывающих окон.
strRemoveOffice10 = "cscript.exe c:\Temp\offscrub10.vbs ALL /Quiet /NoCancel"
rc = objShell.Run(strRemoveOffice10, 0, True)
If rc = 0 Then
'OK
Else
'an error occurred
End If
Error Handling
Error handling does not involve finding
errors in your scripts. Instead, use error handling techniques to
allow your program to continue executing even though a potentially
fatal error has occurred. Ordinarily, all runtime errors that are
generated by the VBScript engine are fatal, since execution of the
current script is halted when the error occurs. Error handling allows
you to inform the user of the problem and either halt execution of
the program or, if it is prudent, continue executing the program.
The On Error Resume Next Statement
There are two main elements to error handling in VBScript. The first
is the On
Error
statement,
which informs the VBScript engine of your intention to handle errors
yourself, rather than to allow the VBScript engine to display a
typically uninformative error message and halt the program. This is
done by inserting a statement like the following at the start of a
procedure:
On Error Resume Next
This tells the VBScript engine that, should an error occur, you want
it to continue executing the program starting with the line of code
which directly follows the line in which the error occurred. For
example, in the simple WSH script:
On Error Resume Next x = 10 y = 0 z = x / y Alert z
a “Cannot divide by Zero” error is generated on the
fourth line of code because the value of y
is 0. But because you’ve placed the On Error
statement in line 1, program execution continues with line 5. The
problem with this is that when an error is generated, the user is
unaware of it; the only indication that an error has occurred is the
blank Alert box (from line 5) that’s displayed for the user.
Tip
A particular On
Error
statement
is valid until another On
Error
statement in the line of execution is encountered. This means that if
Function A contains an On Error
statement, and
Function A calls Function B, but Function B does not contain an
On
Error
statement, the error
handling from Function A is still valid. Therefore, if an error
occurs in Function B, it is the On
Error
statement in Function A that handles the
error; in other words, when an error is encountered in Function B,
program flow will immediately jump to the line of code that followed
the call to Function B in Function A. When Function A completes
execution, the On
Error
statement it contains also goes out of scope. This means that, if the
routine that called Function A did not include an
On
Error
statement, no error
handling is in place.
This is where the second element of VBScript’s error handling
comes in. VBScript includes an error object, named Err, which, when
used in conjunction with On
Error
Resume
Next
, adds much more functionality to error
handling, allowing you to build robust programs and relatively
sophisticated error handling routines.
The Err Object
The Err object is part of the VBScript
language and contains information about the last error to occur. By
checking the properties of the Err object after a particular piece of
code has executed, you can determine whether an error has occurred
and, if so, which one. You can then decide what to do about the error
—you can, for instance, continue execution regardless of the
error, or you can halt execution of the program. The main point here
is that error handling using On Error
and the Err
object puts you in control of errors, rather than allowing an error
to take control of the program (and bring it to a grinding halt). To
see how the Err object works and how you can use it within an error
handling regimen within your program, let’s begin by taking a
look at its properties and methods.
Err object properties
Like all
object properties, the properties of the Err object can be accessed
by using the name of the object, Err, the
dot (or period) delimiter, and the
property name. The Err object supports the following properties:
- Number
-
The Number property is an integer value that
contains an error code value between
and 65535, representing the last error. If the value of
Err.Number
is 0, no error has occurred.
The line of code like the following, then, can be used to determine
if an error has occurred:If Err.Number <> 0 Then
Although the properties of the Err object provide information on the
last error to occur in a script, they do not do so permanently. All
the Err object properties, including the Number property, are set
either to zero or to zero-length strings after an End Sub, End
Function, Exit Sub or Exit Function statement. In addition, though,
you can explicitly resetErr.Number
to
zero after an error by calling the Err object’s
Clear method. The WSH script in Example 4.8 illustrates the importance of resetting the
Err
object after an error occurs.Example 4-8. Failing to Reset the Err Object
Dim x, y ,z On Error Resume Next x = 10 y = 0 z = x / y If Err.Number <> 0 Then MsgBox "There's been an error #1" Else MsgBox z End IF z = x * y If Err.Number <> 0 Then MsgBox "There's been an error #2" Else MsgBox z End If End Sub
The division by zero on the fifth line of the script in Example 4.8 generates an error. Therefore, the conditional
statement on line 6 evaluates toTrue
, and an
error dialog is displayed. Program flow then continues at line 12.
Line 12 is a perfectly valid assignment statement that always
executes without error, but the Err.Number property still contains
the error number from the previous error in line 5. As a result, the
conditional statement on line 13 evaluates to
True
, and a second error dialog is displayed.
Despite the two error messages, though, there’s only been a
single error in the script.The Err object can be reset by using the Clear method (which is
discussed in the next Section 4.2.2.2). - Description
-
The Description property contains a string
that describes the last error that occurred. You can use the
Description property to build your own message box alerting the user
to an error, as the WSH script in Example 4.9 shows.
Example 4-9. Using the Description Property to Display Error Information
Dim x, y ,z On Error Resume Next x = 10 y = 0 z = x / y If Err.Number <> 0 Then MsgBox "Error number " & Err.Number & ", " & _ Err.Description & ", has occurred" Err.Clear Else MsgBox z End If z = x * y If Err.Number <> 0 Then MsgBox "Error No:" & Err.Number & " - " & _ Err.Description & " has occurred" Err.Clear Else Alert z End If
- Source
-
The Source property contains a string
expression that indicates the class name of the object or application
that generated the error. You can use the Source property to provide
users with additional information about an error; in particular,
about where an error occurred.The value of the Source property for all errors generated within
scripted code is simply “Microsoft VBScript runtime
error.” This is true of all VBScript scripts, whether
they’re written for Active Server Pages, Windows Script Host,
Internet Explorer, or Outlook forms. Obviously, this makes the Source
property less than useful in many cases. However, you can assign a
value to the Source property in your own error handling routines to
indicate the name of the function or procedure in which an error
occurred. In addition, the primary use of the Source property is to
signal an error that is generated by some other object, like an OLE
automation server (like Microsoft Excel or Microsoft Word) or a COM
component.
Err object methods
The two
methods of the Err object allow you to raise or clear an error, in
the process simultaneously changing the values of one or more Err
object properties. The two methods are:
- Raise
-
The Err.
Raise method allows you to generate a
runtime error. Its syntax is:[1]where
ErrorNumber
is the numeric code for
the error you’d like to generate. At first glance, generating
an error within your script may seem like a very odd thing to want to
do! However, there are times, particularly when you are creating
large, complex scripts, that you need to test the effect a particular
error will have on your script. The easiest way to do this is to
generate the error using the Err.Raise method and providing the error
code to theErrorNumber
parameter, then
sit back and note how your error handling routine copes with the
error, what the consequences of the error are, and what side effects
the error has, if any. The client-side script in Example 4.10, for instance, allows the user to enter a
number into a text box, which is passed as the error code value to
the Err.Raise method. If the value of the error code is nonzero, an
Alert box opens that displays the error code and its corresponding
description. Figure 4.6, for instance, shows the
Alert box that is displayed when the user enters a value of 13 into
the text box.Example 4-10. Calling the Err.Raise Method
<HTML> <HEAD> <TITLE>Using the Err Object</TITLE> <SCRIPT LANGUAGE="vbscript"> Sub cmdButton1_OnClick On Error Resume Next errN = Document.frm1.errcode.value Err.Raise(errN) If Err.Number <> 0 Then Alert "Error No:" & Err.Number & " - " & Err.Description Err.Number = 0 End If End Sub </SCRIPT> </HEAD> <BODY BGCOLOR="white"> <CENTER> <H2>Generating an Error</H2> <P> <FORM NAME="frm1"> Enter an Error Code <INPUT TYPE="text" NAME="errcode"> <INPUT TYPE="button" NAME="cmdButton1" VALUE="Generate Error"> </CENTER> </BODY> </HTML>
At present there is no definitive list of VBScript runtime error
codes available from Microsoft. Table 4.1 lists a
few of the most common
runtime
errors.Tip
An Error Code Generator
(ERRCODES1.HTML
,
ERRCODES1.ASP
, and
ERRCODES1.VBS
), which allows you to generate a
complete list of current VBScript error codes, can be found on the
O’Reilly Visual Basic web site athttp://vb.oreilly.com.
Table 4-1. Some Common VBScript Error Codes
Error Number
Description
5
Invalid procedure call
6
Overflow
7
Out of memory
9
Subscript out of range
11
Division by zero
13
Type mismatch
Figure 4-6. Generating a Type mismatch error at runtime
- Clear
-
The Clear method clears the information
that the Err object is storing about the previous error; it takes no
parameters. It sets the values of
Err.Number
to
and the Err object’s Source and Description properties to
a
nullstring.
Get VBScript in a Nutshell now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.
Error handling in UFT automation scripts is very important like any other language. We have some very common vbscript examples to demonstrate it.
To show the use of different error handling statements in vbscript, we will use a function which divides an integer by zero (code given below) and produces «Division by zero error». Then we will use each error handling statements using vbscript
How to use — «On Error Resume Next»
On Error Resume Next statement enables the Error handling in the code. If there is error in the code On error Resume Next ignores it and continues execution with next line of code. In the below example code, division by zero statement produces Division by zero error but it is ignored and next line is executed.
Error handling example
On Error Go to 0
On error got to 0 statement disables error handling which we had enabled in our script by using On Error resume Next. In the below example, please see how division by zero statement throws the Division by zero error again after disabling the error handling by using On error goto 0
Error handling example
err.number and err.description
Provides the error number and the description of the error