Guy’s Scripting Ezine 69 – Option Explicit

Contents for Ezine 69 Option Explicit

 ♣

This Week’s Secret

I have a grand scheme for future ezines. Starting this week, I am going to alternate between editions with easy scripts, which explain VBscript and more difficult editions which tackle a specialist task.  This week my buzzword is Option, so this edition is about Option Explicit (easy), next week it will be ‘Join’ and ‘GetEx’ (difficult).

What I seek with my weekly ezines is to weave a delicate pattern.  One strand represents the pure task, for example to map a printer with AddWindowsPrinterConnection.  A separate strand represents mastering VBscript techniques, for example, Option Explicit.  Where possible, I will add a further strand, error correcting code.  My aim, as ever, is to give you the skills to build your own scripts.

Every week I see proof that people only truly learn by making mistakes and correcting them.  So, I would also like to provide scripts with deliberate errors.  I will let you into a secret, many of these out-takes just happen in the course of preparing my final script seen in the ezine.  Occasionally, scripts get through with undetected errors, if you see any, then please let me know.

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

Twin Objectives, Map a printer and understand Option Explicit.

Even if you are familiar with mapping network printers using VBscript, there may be nuances that you have forgotten.  For instance, perhaps you had not realized that running AddWindowsPrinterConnection a second time would not produce an error, even if the printer already exists on the local machine.

Let us take the situation where you have a printer which is shared out on the network.  You would like a script which adds this network printer to the printers’ folder.  For this scenario we employ the VBscript method – AddWindowsPrinterConnection.  Incidentally, it is rare that VBscript is ever case sensitive, so you can type instructions just in lower case if you prefer.  Sprinkling UpperCase letters in methods, is a simply a scripting tradition to make these verbs easier to read.

The best method for our task is AddWindowsPrinterConnection, this method works for all clients from XP to Windows 95.  In the case of XP, Windows 2000 and NT all you need in the ‘argument’ is the string value of the UNC path to the printer, for example, \\ alan\HP6.  However, Windows 9x are trickier to script because they also require the name of the printer driver for example, "HP Laser Jet 6L".

Note there is a similar sounding method called AddPrinterConnection, but this is just for DOS based printers, I will ignore this method for now.

Option Explicit is not required for this or any other VBscript.  However, I believe that it is so important to start scripts with Option Explicit, that I regard scripts without this command as amateurish.  The only reason that I would omit Option Explicit is for clarity when teaching.  Sometimes I need to focus on just the main point of the script.

What then is the point of Option Explicit and Dim?  In a nutshell, to protect us making silly typo mistakes.  Even if the mistake is trivial, a wrong letter can completely alter the sense of a script.

Guy Recommends: Tools4ever’s UMRAUMRA The User Management Resource Administrator

Tired of writing scripts? The User Management Resource Administrator solution by Tools4ever offers an alternative to time-consuming manual processes.

It features 100% auto provisioning, Helpdesk Delegation, Connectors to more than 130 systems/applications, Workflow Management, Self Service and many other benefits. Click on the link for more information onUMRA.

Example 0 – The benefit of Option Explicit.

Var1 = 5
Result = Vari + 7.
Wscript.echo "Result = " &  Result
WScript.Quit

‘ End of example VBScript

What do think would appear in the WScript.echo message box?  Result = 7 or Result = 12?  Almost certainly the WScript message box will display 7, and is very unlikely to return a value of 12.   The reason is that on the second line, after V a r  is the letter (i) instead of a numeric one (1).  Moreover Vari had not been declared, and certainly does not = 5.  My point is that Option Explicit would clear up this ambiguity.

 

Option Explicit
Dim Var1
Var1 = 5
Result = Vari + 7.
Wscript.echo "Result = " &  Result
WScript.Quit

‘ End of example VBScript

Learning Points

Note 1: The error tells us what’s wrong with Line 4:  ‘Variable is undefined: Vari’.

Note 2: If you edit Vari to Var1, then you should get the expected Result = 12.

Example 1 – Add a printer with AddWindowsPrinterConnection

Instructions

  1. Prerequisite you need to substitute your printer share for \\ Alan\HP6
  2. I assume that your client is later than Windows 98.
  3. Copy and paste the script below into notepad.
  4. Save the file with .vbs extension e.g. GuyPrinter.vbs
  5. Double click and then check the message box.
  6. Examine your Printers and Faxes folder for a new printer.

 

‘ GuyPrinter.vbs
‘ Author Guy Thomas https://computerperformance.co.uk
‘ Version 1.2 – April 3rd 2005
‘ —————————————-‘

‘ Purpose of script to map a network printer
‘ ******************************
Option Explicit
Dim objNetwork, strPrinterPath
strPrinterPath = "\\Alan\HP6"
Set objNetwork = CreateObject("WScript.Network")
objNetwork.AddWindowsPrinterConnection strPrinterPath
WScript.Echo "Connected Printer: " & strPrinterPath
WScript.Quit

‘ End of example VBScript

Learning Points

Note 1:  For XP clients, AddWindowsPrinterConnection takes only one argument, the path to the network printer.  In the case of Win 9x clients you must add the printer driver name. e.g. "HP LaserJet 6L".

Note 2: WScript.echo confirms that action has occurred. See how it makes use of the strPrinterPath variable.

Example 2 to investigate the effect of Option Explicit

Option Explicit works hand in glove with the Dim statements.  This pairing is good scripting technique because it makes us think about the variables that the script needs.  Dim forces you to consider the names of the variables and whether they should have an initial value.  In this script the variables are called objNetwork and strPrinterPath.  On line 10 we set strPrinterPath to the UNC path of the printer, then we create a network object called objNetwork.

Scripting thrives on objects.  Once an object is born, then you can manipulate it with commands or verbs such as AddWindowsPrinterConnection.  Think of Option Explicit as ensuring that names declared by Dim, will be used consistently later in the script.  If you began with strPrinter, but later referred to it as, strPath, then watch out for undesirable effects.

To see what I mean about the benefits of adding Option Explicit, try this.

1) Remove Option Explicit

2) Introduce a deliberate spelling mistake with the name strPrinterPath, change the name on line 12 to strPanterRoad and see what happens.  Note this is what I mean Line 12: objNetwork.AddWindowsPrinterConnection strPanterRoad .  (Changing line 9 will not produce my desired error!)

 I admit that this is not the best showcase for Option Explicit, but I hope that you get the idea, and will trust me when I say always use Option Explicit at the beginning of your production scripts.

Solarwinds Config GeneratorGuy Recommends: The Free Config Generator

SolarWinds’ Config Generator is a free tool, which puts you in charge of controlling changes to network routers and other SNMP devices.  Boost your network performance by activating network device features you’ve already paid for.

Guy says that for newbies the biggest benefit of this free tool is that it will provide the impetus for you to learn more about configuring the SNMP service with its ‘Traps’ and ‘Communities’. Try Config Generator now – it’s free!

Download your free copy of Config Generator

Example 3 to add error correcting code.

The key command to bypass VBscript problems is, ‘On error resume next’.  What this phrase does is tell VBscript to ignore the error and carry on processing the next lines.  However, what I want to do is actually trap the error code, and then turn the error number into a more meaningful message.  For this correcting code, I introduce err.number.

In practical terms, I assume that the only problem is caused by a typo in strPrinterPath.  Amazingly, if the printer is already connected, then there is no error when you run AddWindowsPrinterConnection for a second time.  I say amazingly, because MapNetworkDrive would have given an error if the drive was already mapped.

 

‘ GuyPrinter.vbs
‘ Author Guy Thomas https://computerperformance.co.uk
‘ Version 1.6 – April 3rd 2005
‘ —————————————-‘

‘ Purpose of script to map a network printer
‘ ******************************
Option Explicit
Dim objNetwork, strPrinterPath
strPrinterPath = "\\lucy4\HP Laser 4L"
Set objNetwork = CreateObject("WScript.Network")

‘ Extra Section to deal with UNC path errors

On Error Resume next
objNetwork.AddWindowsPrinterConnection strPrinterPath

If err.number = 0 Then
   WScript.Echo "Connected Printer: " & strPrinterPath
     ElseIf Err.Number = -2147023095 Then
     Wscript.Echo "Check Server & Printer names "
     Else Wscript.Echo "Unknown error " & err.number
     Err.Clear
End if

WScript.Quit

‘ End of example VBScript

Learning Points

Note 1: The error correcting section employs, If… then End if. This is a flexible construction used in many types of VBscript.

Note 2: -2147023095 in decimal, corresponds to 80070709 in Hex.  If you run the script without my error correcting code, you get a message box displaying that same Hex number.  My point is that you can intercept the error, write your own error message and add On Error Resume Next to bypass the problem section.

Summary – Option Explicit

Prevention is better than cure.  Add Option Explicit at the beginning of all your scripts.  This action will make sure that you are using only variables that the VBscript knows about. 

To map a network printer, the key method is AddWindowsPrinterConnection.

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