Guy’s Scripting Ezine 54 – Error Correcting Code

Contents for Guy’s Scripting Ezine 54 – Error Correcting Code

This Week’s Secret

I like playing the card game Bridge.  One of the first techniques that you learn in Bridge is the finesse.  However, after a while you discover that there are often better ways of making your contract than relying on the simple finesse.  Here is the parallel between bridge and VBScript.  When I began writing VBScript, at first I always used On Error Resume Next.  All my mistakes seemed to disappear – wonderful.  But I soon realized that this was fool’s gold, more often than not my VBScript errors were just pushed elsewhere.  So I abandoned On Error Resume Next and concentrated on writing better code.

Last week two unrelated events made me rethink On Error Resume Next.  Firstly, I saw the Bridge genius Zia Mahmood make a redoubled slam on a finesse.  Needless to say this was not a simple finesse of a king, but deep roughing finesse of the jack.  I thought ‘hmm perhaps the finesse has its place after all’.

The other, more relevant event, was JT writing in and showing me how to ensure that last week’s script ran smoothly even when the OU already existed.  The answer was On Error.  To let you into another secret, writing error correcting scripts has been gnawing away at the back of my mind for months.  Well, all the pieces are in place, so let us experiment with error correcting code.

Guy Recommends: The Free IP Address Tracker (IPAT) IP Tracker

Calculating IP Address ranges is a black art, which many network managers solve by creating custom Excel spreadsheets.  IPAT cracks this problem of allocating IP addresses in networks in two ways:

For Mr Organized there is a nifty subnet calculator, you enter the network address and the subnet mask, then IPAT works out the usable addresses and their ranges. 

For Mr Lazy IPAT discovers and then displays the IP addresses of existing computers. Download the Free IP Address Tracker

Meet the Family of ‘ On Error… ‘ Commands

On Error Resume Next

Introducing an old favourite –  ‘ On Error Resume Next ‘.  If your script produces errors, and you are in a hurry to fix those 0800 messages, then try ‘ On Error Resume Next ‘.  What this does is says to VBScript / WSH host, ignore the problem and carry on with the next instruction.

On Error Goto 0

Here is the mirror image of ‘ On Error Resume Next ‘.  What ‘ On Error Goto 0 ‘ does is to turn off the ignore error command.  Just to be clear, the purpose of this command is to return to normal.  Normal means that errors will halt the script.  Just in case this double negative logic is confusing, here is a summary.

  • Default state – Error halts script with 0800xxxxx message.
  • On Error Resume Next – Script by-passes error 0800 messages.
  • On Error Go to 0 – Back to the default Error halts script.

 

No doubt you spotted the zero (not o).  Incidentally this is the only use of GoTo that I have found in VBScript. 

Err.Number

Surprisingly, Err. is an object.  Keep your eye on Err.Number.  Good news for your script would be Err.Number = 0 meaning no errors.  Here is the glimmer of an idea, if Err.Number is NOT zero, then we have a problem, however being resourceful we turn this to our advantage.  The idea is once an error is identified, we can take corrective action with a branch in the script which deals with the exception.

If Err.Number <> 0 Then…..  Correct the problem with a clever statement.  One of my themes is introducing new terms, so here I employed vbEmpty instead of zero:
If Err.Number <> vbEmpty Then…..

For pure finesse have a look at the utilities on offer at Tools4Ever

Example Script to create an OU called Suppliers

On the surface, the idea of this script is simply to create an OU called suppliers (building on what we did last week).  However, underneath the covers, my purpose is to test error correcting code.  An all too common scenario is that you run a script to create an object, but that object already exists.  We need to anticipate this duplication error in our script.

One technique is to ignore the error with On Error Resume Next.  A better alternative is to create a branch in the VBScript which handles the error gracefully.

Instructions

  1. Which OU will create in your test script?  My script uses OU=Suppliers. 
  2. Copy and paste the script below into notepad.
  3. Save the file with .vbs extension e.g. ErrOU.vbs.
  4. Double click and examine the message boxes.
  5. Here is one script which I would like you to run for a second time.
  6. Remember to use Refresh in Active Directory to check what has happened.  Sometimes just pressing F5 is not good enough.
 

‘ ErrOU.vbs
‘ Purpose VBScript to demonstrate Error Handling.
‘ Learning Points: Create OU
‘ Usage this as a Template Script to introduce error handling
‘ Author Guy Thomas https://computerperformance.co.uk/
‘ Version 1.4 – November 28th 2004
‘ ————————————————————–‘
Option Explicit
Dim objRoot, objOU, objDomain, objUser
Dim strDNS, strContainer, strOUDescription, strOURebuild

‘ Set string variables
strContainer = "OU=Suppliers"
strOUDescription = "Guy’s Contacts OU"
strOURebuild = "Rebuilt Guy’s Contacts OU"

‘ Section to attach to Active Directory
Set objRoot = GetObject("LDAP://rootDSE")
strDNS = objRoot.Get("defaultNamingContext")
Set objDomain = GetObject("LDAP://" & strDNS)

‘ Section to create an OU
On Error Resume Next
Set objOU=objDomain.Create("organizationalUnit", strContainer)
objOU.Put "Description", strOUDescription
objOU.SetInfo

‘ ——————————————–
‘ Main point of the script
‘ Err correcting code
If Err.Number <> vbEmpty Then
    Wscript.Echo "Error number " & Err.Number
    Err.Clear
    objOU=objDomain.Delete("organizationalUnit", strContainer)
    Set objOU=objDomain.Create("organizationalUnit", strContainer)
    objOU.Put "Description", strOURebuild
    objOU.SetInfo
    On Error GoTo 0
    Else
    WScript.Echo "No Error (" & Err.Number & ") OU Created 1st time"
End If

WScript.Echo "Look in " & strDNS & " for (F5) " & strContainer
WScript.Quit

‘ End of example VBScript

Learning Points

Note 1: The script should work when you run it a second time, however you get a different message.

Tip:  To check the script again, either delete the Suppliers OU, or amend strContainer, for example strContainer = Supplier2

Note 2: Observe where the script ignores the error.  (On Error Resume Next).  Then see where it reverts to normal with :
– On Error GoTo 0.

Note 3: In line 31, vbEmpty is an alternative to 0 (Zero)

Note 4: err.clear it is good practice to reset the error so that it does not interfere with subsequent lines of code.

Note 5: Did you spot that I changed the strOUDescription to strOURebuild?

Challenge

Employ this error correcting technique to your own scripts and send them in to me.  Alternatively, have a look over my previous scripts and correct them!

Summary – Error Correcting Code

All good script writers should anticipate how their scripts will be used.  Where you can foresee a problem such as the object already exists, produce an error handling section in your VBScript.  Consider this page as a template which you can adjust for other error correcting scenarios.

See more about VBScript error correcting codes

VBScripts  • 800 Code list  • Ezines  • Logon Scripts   • PowerShell ErrorAction   • Free Log Tool

Ezine 7 On Error Resume  •Ezine 15 Error Codes  • Ezine 33 Troubleshooting  • Free WMI Monitor

• Ezine 49 Errors  • Ezine 54 Error correcting  • Ezine 69 Option Explicit  • Ezine 71 On Error