Tuesday, 1 July 2014

WshNetwork | Error Handling | VBscript

WshNetwork

The WshNetworkobject exposes some basic network information for the current user, such as 
the username or computer name. This object can also be used to manage printer and drive 
mappings. Let’s take a quick look at this object’s functionality by incorporating it into the 
script.

WshNetworkSample

dim objShell,objNetwork,collDrives 
set objShell=CreateObject("Wscript.shell") 
Set objNetwork=CreateObject("WScript.Network") 
'title for popup window 
strTitle="Welcome" 
'enumerate mapped drives 
strMappedDrives=EnumNetwork() 
'enumerate mapped printers 
strMappedPrint=EnumPrint() 
'compose popup message text 
strMsg=objNetwork.UserName & ", thank you for logging in to " &_ 
objNetwork.ComputerName & VbCrLf & vbcrlf 
strMsg=strMsg & strMappedDrives & VbCrLf & VbCrLf 
strMsg=strMsg & strMappedPrint & VbCrLf & VbCrLf 
strMsg=strMsg & "It is now " & Now & VbCrLf 
strMsg=strMsg & "Have a nice day." 
'set time to -1 to neverdismiss popup window 
objShell.Popup strMsg,10,strTitle,vbOKOnly+vbInformation 
WScript.quit 
Function EnumNetwork() 
On Error Resume Next 
Set colDrives = objNetwork.EnumNetworkDrives 
'If no network drives were enumerated, then inform user, else display 
'enumerated drives 
If colDrives.Count = 0 Then 
ret="There are no network drives to enumerate." 
Else 
ret = "Current network drive connections: " & vbCRLF 
For i = 0 To colDrives.Count - 1 Step 2 
ret = ret & VbCrLf & colDrives(i) & vbTab & colDrives(i + 1) 
Next 
End If 
EnumNetwork=ret 
End Function 
Function EnumPrint() 
On Error Resume Next 
Set colPrint = objNetwork.EnumPrinterConnections 
Chapter 1: Getting Started 9
'If no network printers enumerated, then inform user,else display 
'enumerated printers 
If colPrint.Count = 0 Then 
ret="There are no printers to enumerate." 
Else 
ret = "Current Printer connections: " & vbCRLF 
For i = 0 To colPrint.Count - 1 Step 2 
ret = ret & vbCRLF & colPrint(i) & vbTab & colPrint(i + 1) 
Next 
End If 
EnumPrint=ret 
End Function

we customize the message to display the user name, the computer the user is 
logging onto, and any mapped drives or printers. We also create an object in our script called 
objNetwork, which is an instance of the WshNetwork object. With the objNetwork object, we 
can build a list of mapped drivesand printers by calling the EnumNetworkand EnumPrint
functions. These functions use the EnumNetworkDrivesand EnumPrinterConnectionsmethods 
to create collections of mapped network drives and printers respectively, as follows.
For i = 0 To colPrint.Count - 1 Step 2 
ret = ret & vbCRLF & colPrint(i) & vbTab & colPrint(i + 1) 
Next
The function then loops through the collection and lists the mapped network resources.
Back in the main part of the script, we compose the message. We personalize it by calling the 
usernameand computernameproperties, as shown here.
strMsg=objNetwork.UserName & ", thank you for logging in to " &_ 
objNetwork.ComputerName & VbCrLf & vbcrlf
The only other addition to our display message is the information about mapped drives 
and printers. The user now sees a personalized message showing all his or her mapped 
drives and printers. The message appears for 10 seconds and then closes. We raised the timeout value because there’s more to read now than in the Listing 1-1 example.
Note The username property is the user’s NT4 style or sAMAccountNameattribute such as 
jhicksor donj. If you want the user’s full name or display name from Active Directory, you must 
add code to search for the account based on the sAMAccountNameattribute.
Error Handling
Any administrative script should have some degree of error handling. Even if you develop 
scripts that only you use, error handling makes them easier to develop, debug, and deploy. 
You certainly don’t need to examine every single place where an error could occur, but you 
should identify sections of code where an error or failure will have a significant and negative 
10 Part I: The Basics of Advanced Windows Scripting
effect on your script. For example, if you are creating a log file with the FileSystemObjectand 
attempt to write to a drive for which the user lacks proper permissions, that code will fail. The 
best approach is to catch this kind of error ahead of time and provide some meaningful feedback to the user, as shown in Listing 1-6.
Note The error handling we are discussing is specific to VBScript. The engine that runs our 
scripts, Windows Script Host, is language independent. We could have written our scripts in 
JScript and handled errors in an appropriate manner for that scripting language.

 Error Handling Sample: Err

Dim objFSO,objTS 
On Error Resume Next 
Set objFSO=CreateObject("Scripting.FileSystemObject") 
Err.clear 
Set objTS=objFSO.CreateTextFile("R:\Logs\auditlog.txt") 
If Err.Number<>0 Then 
strMsg="There was an error creating the logfile" & VbCrLf 
strMsg=strMsg & "Error#" & Err.Number & " " & Err.Description 
WScript.Echo strMsg 
WScript.Quit 
End If 
'script continues from here

we attempt to create a log file. If this attempt fails, there is no reason to continue 
with the script. Before we try to capture error information, we make an Err.Clearstatement. In 
a short script like this it probably isn’t necessary, but in a longer and more complicated script, 
calling Err.Clearremoves any errors that occurred earlier in the script and were ignored. For 
example, you might be creating a user object in Active Directory from new user information 
stored in a text file. If one of the user attributes you want to populate is telephonenumber, but 
not every new user has this attribute populated,you want the script to continue regardless 
(hence the On Error Resume Nextat the beginning of the script). However, when you try to set 
this attribute in the script, an error is still raised. If you don’t call Err.Clear, the next time you 
check for the value of Err.Number, it might return the value of the previous error. In Listing 
It's is a highly unlikely event—nevertheless, we wanted to be very clear about how and 
when to use Err.Clear.
The actual error checking is looking for the value of Err.Number. A value of 0 indicates 
success. Any value other than 0 indicates some failure or error in the previous command. 
Depending on what the script was trying to accomplish, you might get a lot of error information or a little. At a minimum, we recommend displaying the Err.Numberand Err.Description
information to the user in some sort of error message. Keep in mind that not every error will 
have a corresponding description. Depending on the nature of your script and the value of 
Err.Number, you might add more sophisticated error handling. First intentionally induce 
errors that a user might cause and make note of the error numbers and descriptions. Then use 

a Select Casestatement to take more sophisticated steps or offer more detailed information 
based on the error, as follows.
Select Case Err.Number 
Case 76 
WScript.Echo "Verify that path is available" 
Case 71 
WScript.Echo "You seem to be attempting to access a drive" &_ 
" that isn't ready, like a CD" 
Case 70 
WScript.Echo "You don't seem to have permission to write to" &_ 
" that file." 
Case Else 
WScript.echo "Error #" & Err.Number & " " & Err.Description 
End Select
Of course, there is more to error handling than just the Err object. Some of the objects you 
might include in your script have their own mechanisms for avoiding or detecting errors. For 
example, the FileSystemObjectincludes the FolderExists, DriveExists, and FileExists methods. 
These methods return TRUE if the item in question exists, which means you can write code 
like that. 

Error Handling Sample: FileSystemObject

On Error Resume Next 
Dim objFSO,objTS 
strFile="R:\logs\audit.log" 
Set objFSO=CreateObject("Scripting.FileSystemObject") 
If objFSO.FileExists(strFile) then 
Set objTS=objFSO.OpenTextFile(strFile) 
Else 
Wscript.echo "Can’tfind " & strFile 
Wscript.quit 
End if 
'script continues

No comments:

Post a Comment