I am aware VB-Scripting is vanishing where PowerShell takes precedence, but still this post is for people who still use VB-script. The post talks about some of the rules that can be implied with error handling.
Rules:
- Explicitly set error handling using the “On Error” statement.
- Explicit declaration makes it clear that error handling has been considered.
- Use “On Error GoTo 0” to turn off error handling. With error handling turned off, a VB script will stop immediately upon encountering a run-time error. This should only be used in circumstances where failure of the script is inconsequential.
- Use “On Error Resume Next” to turn on error handling. With error handling turned on, a VB script will not stop execution. Instead it attempts to run the next line, skipping lines that generate errors and running lines that do not. With error handling turned on, it is important to check Err.Number to trap fatal error conditions.
- Process errors appropriately when error handling is turned on.
- When a VB script is set to handle errors (On Error Resume Next), the script should check Err.Number after every operation that might cause an error. Whenever Err.Number is not equal to zero, the script should take appropriate action and clear the error using Err.Clear.
- Include an “On Error” statement at the beginning of every function and subroutine.
- This will ensure that error handling statements from previous functions do not spill over into the current function.
- When using the WMI interface, get details about errors from the SwbemLastError object.
- The WMI interface cannot return detail error information in the standard ERR object. It is necessary to use SwbemLastError to retrieve details about the last error encountered in the WMI interface.
- Use the application event log to record success/failure of the script.
- The message accompanying the event log entry should include the full script name & version, the user name, and the logon server as well as text describing the condition encountered. The text describing the condition may include values of critical variables, e.g. properties of the Err object (number, description, source) would be helpful for troubleshooting. The Event Type will indicate success, error, warning, or information. Use of the event log is required for logon/logoff, startup/shutdown and their subordinate scripts.
set wshShell =
WScript.CreateObject("WScript.Shell")
wshShell.logevent EVENT_INFO, _
"User: " &
wshShell.ExpandEnvironmentStrings("%USERNAME%") _
& vbCrLf & "Logon Server:
" _
& vbCrLf &
wshShell.ExpandEnvironmentStrings("%LOGONSERVER%") _
& vbCrLf & "Script Name:
" & Wscript.ScriptFullName _
& vbTab & "Version: "
& SCRIPT_VERSION _
& vbCrLf & "Description of
the condition...."