Skip navigation

Error-Handling Techniques

One of my script mentors taught me that a trick to writing good script code is to make it handle errors gracefully. He always thought that 25 percent of the code in a script should accomplish the task and 75 percent should handle errors. Although I think his percentages might have been flawed, he has a point. Some utilities and commands take a long time to timeout if they're run against a nonexistent node. If you have many nodes in your input list that don't respond, these combined timeout errors can make a script take a long time to complete. Also, not having sufficient rights on the remote node to run a command or utility against a remote node could cause a long timeout.

You should always check whether a node is online before you query it for information. Optionally, performing a rights test isn't a bad idea, either. Traditionally, I've used a Ping test, run Nbtstat, or tested the C$ admin share to check whether a node is online. The GetBiosDate script includes code to perform the C$ test, which you can see at callout A in the main article's Listing 1. In the 11 "mini" scripts, I've added the code to determine whether the path to the C$ default administrative share exists. This is a simple double test: It reveals whether the node is online and also whether you have administrative rights on the target node.

Another potential area where you might need error handling is in console output. In many cases, the script is working “correctly” and gathering the desired data but nevertheless produces console messages, which can concern and confuse the script operator. To suppress error output in the GetHostsFileSize script, I use the redirection operator (>), as the code at callout A in the main article's Listing 2 shows. The 2^>NUL code following the Dir command suppresses File Not Found console messages if the HOSTS file is in an alternate path. Because the redirection character is inside the For command, I need to precede the > with the caret escape character (^). (Similarly, you must also use precede a pipe character—|—inside a For command with a ^.)

Hide comments

Comments

  • Allowed HTML tags: <em> <strong> <blockquote> <br> <p>

Plain text

  • No HTML tags allowed.
  • Web page addresses and e-mail addresses turn into links automatically.
  • Lines and paragraphs break automatically.
Publish