Friday, July 25, 2008

VBScript part 2: looping and constants

Looping:

For Each...Next:
These commands let you walk through a collection of objects, do something with each of them, then move on to the next one. You cannot perform a WScript.Echo on a collection because each item in the collection can be assumed to have different properties, so which would it echo? Instead you'll need to use a "For Each"..."Next" loop.

For...Next:
"For...Next" differs from "For Each...Next" in that you need to know how many items there are in the collection in order to use "For...Next" while you do not when using "For Each...Next".

Do While...Loop:
This command runs a script as long as a certain condition is in effect.

Wscript.sleep:
Wscript.sleep pauses the script for the specified period of time (in milliseconds). An example of a one second pause would look like:
WScript.Sleep 1000
...but don't rely on it for scientific measuring of time under a second, it's just not that accurate!

Timer:
The timer function is used to time how long it takes to run a script. You use it once, it counts the number of seconds since midnight, then you use it again at the end and when you subtract the first from the second, you get the length of time that it took to run the script as your result. The variable names that are often used for this are "startTime" and "snapTime".

Constants:

"Const": You define a constant by using "Const" (variable) = (value).
Example:
Const DriveType = 3


General Info:

Interacting with programs/services that are already running:
...if the program you're using is already running, like WMI for "GetObject" you do not have to create an instance of the WMI object by using "CreateObject". Instead, you can just get it by using "GetObject".

Line breaks:
An underscore at the end of a line breaks the code into two lines, usually to make it easier to read. When a line that's inside parenthesis is broken up an ampersand ("&") is needed as well.

WMI:
To get information about drives you need to connect to WMI using GetObject("winmgmts:") then you can use a query to select the drives you want.

Time Stamp:
Wscript.Echo Now
Will print out current date and time. Useful for logs. Also can be used to time your script since it reports the time down to the second.

Space ():
The "Space ()" command is built into the language and, therefore, does not need to be defined or declared. It acts like a variable tab command, so you just need to tell it how many spaces you want and it'll skip that many spaces.

vbNewLine:
The vbNewLine command is also built-in, it tells the script to print out a new line.

No comments:

Post a Comment