The VBScript Network and Systems Administrator's Cafe:

VBScript Statements

May 9 2008   5:54PM GMT

VbScript Statements: Explaination of Select … Case



Posted by: Jerry Lees
vbscriptstatements, VBScript Statements, VBScript, Functions

The Select … Case Vbscript statement is a very powerful way to easily preform specific actions based on a comparison of a variable to a series of cases you specify, plus it allows for the fact that NONE of the cases apply with an optional case else condition. The Select Case statement is often a better solution then a if…Then…Else if when you have more than 2 conditions that could apply.

Consider the following code snippet to check if a number is positive or negative:

Function TestNumber(Number)  

    Select case Number
        Case Number > 0
             TestNumber = “Positive”
        Case Number < 0
             TestNumber = “Negative”
        Case Else
             TestNumber = “Zero”
    End Select

Apr 13 2008   1:40AM GMT

Converting variable types in vbscript from one type to another type



Posted by: Jerry Lees
Development, VBScript, Variable Types, VBScript Statements, Functions

In a previous posting, titled Variable types in VBscript and their upper and lower limits– just prior to my Rant about CAPTCHA, we discussed the types of variables and why you might want to use them and I showed you a few scenarios where you could get unpredicatable results by not using the proper variable type. If you haven’t had a chance to read it yet, you might want to go back here before continuing.

In this installment We’ll discuss the challenge created by using these variable types specifically. Remember, I said that if you use pieces of code or a COM object written in another language it may require a certain type of variable when you call it from your script. (Note, VBScript generally does a good job of converting for you behind the scenes, but it is a best practice to do the conversion on your own first.)  You might be thinking, “Why not just use a double for everything, that covers a wide enough amount of numbers that I’ll never be able to use a number that high?”

Well, the reason is the size of the amount of data it takes because a larger number takes more bits in binary to be represented– therefor the larger the number (or more correctly the RANGE of the variable type) the more space it will take to store it. (A binary lesson may be in order, but not today.)  The last reason is related to the size as well, it takes more processing power to deal with larger numbers because the bus of the CPU is only so wide, and it must sometimes bring the number across the bus in two steps, thus taking more time. Therefore, if you use numbers to big your  scripts can run slower. When I mean slower, I’m only talking about fractions of a second for the work to be complete, but slow scripts tend to each your life away a millisecond at a time… Imagine something being a millisecond slower but you have to do it 100,000 times. Now you’re looking at almost 2 minutes eaten away.

Now, We discussed the types of variables last time, below you will find a table that shows you the function that converts one variable type to another and a link to a useful site showing you how to use the function. Yes, a function. These get fed a number of one type and return a number of another, so you’ll need to assign the return to another variable when you call them.  (Note: the site referenced uses document.write in it’s examples, to use the examples in VBScript simply replace document.write with a wscript.echo)

VBScript Type Conversion Functions

Function Description
CBool Converts any nonzero value to True and 0 (zero) to False.
CByte Converts an expression to a Byte value.
CCur Converts an expression to a Currency value.
CDate Converts an expression to a Date value.
CDbl Converts an expression to a Double value.
CInt Converts an expression to an Integer value. If the fractional part of the expression is .5, CInt will round the value to the nearest even number. For example, 3.5 will be rounded to 4, and 6.5 will be rounded to 6.
CLng Converts an expression to a Long value.
CSng Converts an expression to a Single value.
CStr Converts an expression to a String value.

This information should be very helpful to you in coverting variables from one type to another in the future. The thing to remember is that you don’t always need to do this, but if you’re getting wierd results in your script; check for uninitialized variants, variables of one type (or variant) that are being used with a external piece of code from another language, or for places where a return value is one type and you use it as another.

Enjoy!

Extra credit: What happens if you have a variable (of any type) and add enough to it to cause it to go above the maximum value of the variable type? What’s this generally called?


Mar 12 2008   5:38PM GMT

Use of option explicit and the DIM statement in VBSCRIPT.



Posted by: Jerry Lees
Development, VBScript, Error control, Variable Types, VBScript Statements

As an answer to the extra credit portion of my posting a few days ago:

DIM in a script declares a variable to be used. It just simply creates the variable, nothing more. By default, vbscript will create variables on the fly for you as you use them the first time you use them.

There are other ways to create a variable as well, but create specific types of variables. Here are a few I can think of off the top of my head.

Const  - creates a Constant Variable, while it may seem line an oxymoron, they are sometimes very useful rather than risking typing a long value over and over again. Consider these examples Please note, they are abbreviated here for display purposes— please do not use them in code to launch a rocket to Mars ;-) .

Const Pi = 3.14159265358979323846264338327950288419716939937510582097494459230 ‘ Pi
Const GC = 0.62432998854355087099293638310083724417964262018052 ‘ The Golomb Constant
Const AC = 0.37395581361920228805472805434641641511162924860615  ‘ Artins Constant

By doing this we can type this in our code: 

Answer = Pi * GC * AC

Instead of:

Answer = 3.14159265358979323846264338327950288419716939937510582097494459230 * 0.62432998854355087099293638310083724417964262018052 * 0.37395581361920228805472805434641641511162924860615

And just imagine the mistakes we’d make if we had to type it a bunch of times!

Also there is This command:

Redim  - used to create a single or multi-dimensional array.

For example:

Redim StudentQuarterlyGrades(4) ‘ single dimensional array for grades for a student
Redim ClassQuarterlyGrades(4,13) ‘ a multidimensional array for quarterly grades for a class of 13

Enough of that tangent of extra information! The last  extra credit item was:

option explicit, which forces the writer of a script to declare their variables before they use them.

This can be very valuable and a huge time saver– though it requires a little extra work on the from side declaring variables before you use them. In fact, most programming languages, like c/c++, java, and others, require you to declare the variables prior to use as well as decalre what kind of value you will be putting in them.

Consider this code, without using OPTION EXPLICIT:

StudentFinalGrade = 100
StudentHomeworkGrade = 100

StudentCourseGrade = ((StudentFialnGrade + StudentHomeworkGrade)/200)*100

Do you see the problem? I spelled final wrong in the last line StudentFialnGrade.

Some poor student will get a F (50%), instead of an A (100%) because of that mistake. However, The same code with option explicit and proper DIM statements below (yes, you can declare multiple variables on one line with a comma):

Option Explicit
Dim StudentFinalGrade, StudentHomeworkGrade

StudentFinalGrade = 100
StudentHomeworkGrade = 100

StudentCourseGrade = ((StudentFialnGrade + StudentHomeworkGrade)/200)*100

Yields the following error, pointing to the line and the variable that is either misspelled or not decalred:

… Untitled4.vbs(7, 1) Microsoft VBScript runtime error: Variable is undefined: ‘StudentFialnGrade’
 

Notice how easy that is. Trust me on this. Get into the habit of starting every script with option explicit and using DIM to declare your variables… while it may not matter for 20 -40 line scripts, you will notice it in 100 or 1000 line scripts– and wish you had done it when you spend several hours tracing down why a calculation or string value is coming out differently than you expected!


Mar 3 2008   9:11PM GMT

Using Set, GetObject, ExecQuery, and For Next in VBSCRIPT to use WMI objects



Posted by: Jerry Lees
SQL, Development, VBScript, Networking, Objects, VBScript Statements

In my last blog entry I explained error control via on error resume next and on error goto 0, there are other ways as well– but for now this should work to get us by.

Next well discuss the Set, GetObject, ExecQuery, and “For Each” commands in the script we worked with, these are on lines 3, 4 and 5 below.

The script was basically (line numbers included as a reference):

1. On Error Resume Next
2. 
strComputer = “.”
3. Set objWMIService = GetObject(”winmgmts:\\” & strComputer & “\root\cimv2″)
4.
Set colItems = objWMIService.ExecQuery(”Select * from Win32_PrinterDriver”,,48)
5.
For Each objItem in colItems
6. 
    Wscript.Echo “ConfigFile: ” & objItem.ConfigFile
7. 
    Wscript.Echo “DataFile: ” & objItem.DataFile
8. 
    Wscript.Echo “DriverPath: ” & objItem.DriverPath
9.
     Wscript.Echo “Name: ” & objItem.Name
10.
   Wscript.Echo “OEMUrl: ” & objItem.OEMUrl
11.
   WScript.Echo “_________________” & vbcrlf
12.
Next

The Set command basically tells cscript (or wscript) to assign the value of a variable to be the value of another or creates an object. For all intensive purposed, you can think of an object as a piece of specialized code that is already written that you can call from within your program and use as if it were your own. An object can contain many different types of values, that are referenced by names. These names are either properties (values) or methods (functions to do something and probably give you a value back).

Next, the GetObject command. this is the true heart of our WMI script. In fact, this is where almost all the magic happens! The Getobject comamnd lets us use pieces of code outside of our application as if we had written them on our own– the plus being that we don’t have to write them. In this case it is a WMI call to retrieve an object called “winmgmts:\\.\root\cimv2″.

This object is the root WMI provider that is built into the OS and the period represents the local machine, to get other machine you would specify it’s name instead– this is why we used a variable in the script. (Remember, scripts are powerful when they are reusable for the same situation at a different time, so try to use variables where ever you think a piece of information could change in the furture to allow you to reuse the script.) This WMI provider returns a WMI object that allows us to reference and use the piece of the OS that deals with WMI. Notice we SET the object to the variable objWMIService in the line?

 In the next line of code we actually USE it, again another SET command. But this time we use:
… objWMIService.ExecQuery(”Select * from Win32_PrinterDriver”….

The execQuery method is a part of the WMI classes Microsoft has written, and we are simply calling it to preform work. In this case, we are constructing a call to pull back all the printer drivers. The part in the quotes works exactly like a simple SQL statement would operate. Essentially in english it works like– Select all values from Table containing the printer driver information. This “table” contains lots of information on the printer drivers, I’ve only chosen to show a few items from the table, you can get more information here.

After this command completes, colItems will contain a collection of objects that each have properties named the same as the columns in the table. We use the For Each command on line 5 to loop through each member of a collection one at a time and do something with the data (or to the data). The Next command on line 12 loops back to the beginning as long as there is another object after the one currently being used in the collection.

That’s it! It’s pretty easy stuff, once you get the concepts down. Remember, The WMI object is used to execute a query against the WMI database on the system. This query returns a collection of objects containing data for the query you built.

The actual data returned (and names of methods and properties used to get the data) depends on the query you specified. More on that next time!