Export (0) Print
Expand All
Expand Minimize
0 out of 3 rated this helpful - Rate this topic

Converting VBScript's On Error Statement


Windows PowerShell


Definition: Enables or disables error-handling.

On Error

By default Windows PowerShell issues an error message the moment an error occurs. If you prefer that processing continue without displaying an error message then set the value of the Windows PowerShell automatic variable $ErrorActionPreference to SilentlyContinue. You know, like this:



$erroractionpreference = "SilentlyContinue"

Incidentally, your choices for this variable include:

  • SilentlyContinue

  • Continue (the default value)

  • Inquire

  • Stop

To illustrate the differences between these error-handling states, suppose we have the following script, a script that features a syntax error on the very first line:



bob
$a = 2
$b = 2
$c = 2 + 2
$c

If you run this script and error-handling is set to Continue, you’ll get back the following:



The term 'bob' is not recognized as a Cmdlet, function, operable program, or script file. Verify the term and try again.

At C:\scripts\test.ps1:1 char:4
+ bob <<<<
4

As you can see, the script ended up running and the value 4 is echoed back to the screen, but only after a detailed error message has been displayed.

By contrast, here’s what you get when error-handling has been set to SilentlyContinue:



4

The script continued to process, and no error was reported.



If error-handling is set to Inquire Windows PowerShell will suspend operations and ask you how you wish to proceed:

Action to take for this exception:
The term 'bob' is not recognized as a Cmdlet, function, operable program, or script file. Verify the term and try again.
[C] Continue  [I] Silent Continue  [B] Break  [S] Suspend  [?] Help (default is "C"):

Finally, here’s what happens if error-handling is set to Stop:



The term 'bob' is not recognized as a Cmdlet, function, operable program, or script file. Verify the term and try again
.
At C:\scripts\test.ps1:1 char:4
+ bob <<<<

In this case the error message is displayed and the script terminates; the value 4 is not displayed because once the error occurred no additional lines of code were executed.


Return to the VBScript to Windows PowerShell home page

Did you find this helpful?
(1500 characters remaining)
Thank you for your feedback
Show:
© 2014 Microsoft. All rights reserved.