Is your server running slowly? Check with SolarWinds ipMonitor
Get a free evaluation copy of ipMonitor
Contents for Ezine 69 Option Explicit
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.
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.
If you are looking for handy network utilities, try some of the free downloads at
Tools4Ever
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.
Instructions
- Prerequisite you need to substitute your printer share for \\ Alan\HP6
- I assume that your client is later than Windows 98.
- Copy and paste the script below into notepad.
- Save the file with .vbs extension e.g. GuyPrinter.vbs
- Double click and then check the message box.
-
Examine your Printers and Faxes folder for a new printer.
' GuyPrinter.vbs ' Author Guy Thomas http://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.
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.
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 http://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.
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.
Their topics and material are ideal for getting you started with VBScript. The
videos are easy to follow and you can control the pace. Try their free demo material and then see if you want to buy the full package.
See more about VB Script Training CD.
|