The set statement is used to assign any value to any type of variable. For the most part this command is optional. However, it needs to be used when you are assigning an object reference to a variable, such as when you use a variable to hold the return of a CreateObject function for later reference in your code.
An example of the set command would look like:
Set objDictionary = CreateObject(”Scripting.Dictionary”)
The VBScript statement Sub allows you to create a section of code that can be reused over and over, called a subroutine. It also allows you to name this section of code and refer to it by name, rather than typing it in multiple times.
Subroutines can optionally have parameters associated with them, but they must complete all their work in the subroutine because they can not return any values back to the portion of the program that called them.
Sub routines start with a declaration of the name and parameters and end with a “End Sub” statement. An example subroutine would look like so:
Sub AddNumbers (x, y)
To call this subroutine from your script you would simply place the following code elsewhere in your script:
AddNumbers 2, 4
(Notice that parenthesis were not used when calling the subroutine.)
If you read this blog regularly, you know that much of what I write about is VBScript. But that’s not completely the goal of this blog. The main goal is to make your life as a systems admin easier! (Scripting just happens to be a big way to accomplish this.) So, on occasion I do write about other topics.
One topic I plan on starting is one for useful tools I find to help make your job easier. (Please don’t applaud, just keep coming back and reading the blog.) To help identify these postings, I will place “Essential Tools:” at the front of the title and tag them “essential tools“.
This will be a virtual corner of the blog that you will be able to find free tools and applications that will either make your life easier or provide those sysadmins with less resources (read budget) than a fortune 500 company gives to the systems administration team to accomplish things.
Stay tuned, the first tool is on the way!
The With … End With statement allows you to execute a section of code on a specific object or class that calls methods or set properties on the object from within VBScript without referencing the object directly in the code written.
It is a way of simplifying your code, and very useful in large scripts.
(please note, these examples are snippets of code and will not work by themselves in an editor)
.FirstName = “Jerry”
.LastName = “Lees”
.URL = “http://www.gamersigs.net”
.XBoxLiveTag = “CrashSerious”
.Email = “Not-a-chance-spammers”
This would be equivalent to the following standard code:
objSomething.FirstName = “Jerry”
objSomething.LastName = “Lees”
objSomething.URL = “http://www.gamersigs.net”
objSomething.XBoxLiveTag = “JLees”
objSomething.Email = “Not-a-chance-spammers”
I like free stuff. Who doesn’t? And with the price of technology books you can imagine I was amazed when I found a pretty cool site recently, Scribd, that allows you to upload electronic documents. They then add this document to the database they have and make it search-able. Plus, you can search the database for specific subjects or words.
Not only are regular people uploading books and documents, but there are publisher’s uploading books. Sometimes they are just excerpts, but sometimes they are entire books as well like:
And Many Many more… so stroll on over there and see what you can find!
In my last posting I gave you 5 of what I consider to be 5 of the top 10 things to grasp so that you can be successful in writing powerful VBScripts to make your life easier. In this installment I finish up these trains of thought. So lets dive back in:
5. Always try to use option explicit in your code, especially if the script is longer than 100 lines.
Trust me on this one, using option explicit may force you to think a little bit about declaring a variable before you use it and it may be a pain having a silly error about a undeclared variable when you test your code, but it’s a heck of a lot better than trying to find two places where you’ve spelled a variable two different ways in your code– and creating a hard to find bug because of the different spellings.
4. Learn when to use on error resume next and when to just let the script die.
Sometimes you just can’t cover all the possible errors in your code (though you should try) and turning off error checking is an absolute must. When you do do this, be sure and turn error checking back on after you have passed over the area of your code that could cause a problem (with– on error goto 0)
3. Conditional statements are invaluable, just know what tool is right for the job.
Branching your script because a variable has a specific value, is greater than, or less than something else can be invaluable. Often it is the key to clearer to follow code and getting your script up and running quickly. Knowing which conditional statement (If-then-else, for-next, do-loop, select-case, etc) to use is an invaluable tool to have in your tool belt as a systems administrator.
2. If you do it over and over, then you should script it.
This is my motto! You’ve seen it several times… BE LAZY! There is absolutely no sense in doing something that is repeatable by hand day in and day out. Your time could be better spent spending a few seconds looking at a output from a script to make sure it went well when it ran as a scheduled task. Thus freeing you up to do more (or less) of what you need to accomplish during the day.
1. Everything has been done before, it just may take a little effort on your part to cobble it together.
Almost everything has been done before in a script or other program… it just may not be exactly what you need to get the job done. After searching for a while for a script that does exactly what you want and not finding it— look for several scripts that do pieces of what you need done and put them together into one script that is exactly what you need! Above all else use Google for what it does best, search the web for examples. Additionally, as you find sites that are helpful book mark them for later reference. My blog roll to the right is a good place to start as well, I use these sites myself.
In this installment I thought I’d give the network administrator looking to learn VBScript a little help in focusing in of key skills needed to write not only useful VBScripts, but help them make their lives easier! There are certainly more concepts that are helpful, but these are the ones I think are the most basic to everything else.
So let’s dive in with Number 10!
10. String Manipulation is your friend.
There’s a reason people are still writing scripts in PERL. It is very useful in manipulating strings– and sometimes you need to manipulate and use strings to get done what you need to get done. Built in String manipulation functions like Replace(), Instr(), Mid(), Ucase(), and Lcase() are invaluable, so commit their syntax to memory or use a script editor with intellisense that will help you with the syntax as you type.
9. Learning to create functions and subroutines will make your life easier.
The key to generating a script quickly is to use the code you’ve already worked hard on creating previously. Most of my scripts that I post here are smaller for a single purpose but, they are still useful if you take the heart of the script and wrap it in a function! You will find, over time, you’ll end up digging through your script repository to copy and paste pieces of code into another script. (I do.) Plus, it will save you time! Be Lazy! Don’t re-invent the wheel every time you sit down in front of the keyboard!
8. Key scripting objects were created for a reason– so you don’t have to create them yourself.
This is a continuation of the same concept. Don’t re-invent the wheel. There are already objects for specific functions, string manipulation for example– so don’t reinvent the replace() statement unless you have a really good reason to do so. If you need a little different functionality try to at least wrap it in a function.
7. Recursion in your code can be your best friend– or your worst enemy.
Recursion is where a section of code (generally a function) calls itself. This is invaluable! It saves a ton of lines of code because sometimes you do need to use the functionality of a function inside itself. (file and directory manipulations for example) However, be aware that recursion is dangerous because it poses the potential to create an infinite loop (which would be very bad if you were deleting files) and also can be somewhat hard to troubleshoot.
6. You will eventually need to debug that script, so comment your code and use Wscript.Echo to write to the screen what you are doing.
It’s inevitable, at some point a situation is going to arise that you didn’t think of 3 years ago when you wrote the script and your going to have to figure out why that script you wrote (and forgot about) has been dying for 6 months.
Comments are helpful in documenting how and why a script is doing something in a particular manner. I can’t tell you how many times I’ve went to the effort to rewrite a section of code to find out my thought wasn’t going to work because of something I figured out previously and didn’t document or didn’t because the code didn’t make sense.
Another useful tip is to use Wscript.Echo to output the key information the script is using, a variable in a For Next loop for example, or a string being passed into a function and the output of the function. You can always either comment them out when you’re done — or use a variable to hold a “debug state” and wrap the Wscript.Echo in a if statement, like so:
‘This is the debug “flag”, set it to 0 to turn off debugging output
‘… lots of code omitted
If debug = 1 then
Wscript.Echo “We’re cooking with Gas now!”
That’s enough for now, you’ll at least have something to consider. There’s more in the next Blog posting, so continue on over there!
I’ve been writing lately on individual topics and thought it was time for a little fun, while introducing you to a new object in the process… the Scripting.Dictionary object! (and random number generation in the process)
The Scripting.Dictionary object is a quite useful object. It will let you store data in a categorized manner through it’s use of a key when you add data to the object. It works very much like a multi-dimensional array would, except that it is much easier to retrieve a specific type of data.
You place the data into the object via the .add method and retrieve a specific item via it’s key. The key can either be numeric or a string. In the example below, I’ve chosen a number. Now for the example… a script so useful that I’m certain it will become a key part of your decision making process at work… The Magic Eight Ball! Now, before you laugh not everyone has a magic eight ball (I have two) and that’s a shame because they really do help with making decisions.
Just run the script below several times and ask it these questions:
Will anyone notice if I reboot the exchange server now?
Will the network survive while the Network Guys upgrade the switches?
Will the servers survive another patch Tuesday?
Does my boss appreciate me enough to give me a $10,000 raise?
And now for the example code you’ve been waiting for…
Set objDictionary = CreateObject(“Scripting.Dictionary”)
objDictionary.Add 1, “All signs point to NO”
objDictionary.Add 2, “Outlook not likely”
objDictionary.Add 3, “All signs point to YES”
objDictionary.Add 4, “Maybe”
objDictionary.Add 5, “You want what… When?”
objDictionary.Add 6, “Definitely”
objDictionary.Add 7, “Reply Hazy, try again later”
objDictionary.Add 8, “I could tell you, but I’d have to kill you”
objDictionary.Add 9, “Sure, why not.”
objDictionary.Add 10, “One word Answer. Snowball… you figure it out.”
Answer = int(Rnd(1)*10)
Loop While (Answer < 1)
As always, this code works perfectly. However, sometimes the formatting of the blog breaks the code if you copy and paste it into your editor. So, if you’d like to not type or troubleshoot any syntax errors due to the copy and paste problems– I’ve provided the code for download, plus example output files from my final tests for you. You’ll find the code and other files available for download from my website’s (www.websystemsadministration.com) File Depot under the ITKE Blog Scripts category. Enjoy and happy scripting!
The VBScript REM statement is used to place a comment in your script or function. It is typically considered essential to place comments in code, not only to document what something does for others– but for yourself 6 months down the line.
Another short hand method of placing a comment in the code is to use the ‘ character to comment the code. Below are two examples:
Rem This is a comment
‘ This is a comment too
x=x+1 ‘this is a comment after a line of code, the code is processed and the comment is ignored.
The For Each Next statement combination is very useful for situations where you need to loop through a piece of code a specific number of times, just like the For Next statement, except that you may not even know at run time how many items you need to loop through.
This particular variation of the For Next statement is particularly helpful when iterating through arrays, objects, or collections– cases where you may not know how many items are in the object or collection with out going through them first. (Which would be a waste of resources)
You can use Exit For statements to exit out of a For Each Next loop, if you need to check for a condition inside the loop.
Here is an example of a For Each Next statement:
Collection(0) = “Test”
Collection(1) = “Test 2″
Collection(2) = “Test 3″
For Each Item in Collection