Contents for Ezine 90 - Looping
Is your server running slowly? Check with SolarWinds ipMonitor
Get a free evaluation copy of ipMonitor
If I were to ask, 'Why create a VBScript when you could carry out a task manually?' Amongst the replies I would expect, automate repetitive tasks and speed up operations. It is looping that plays a
crucial part in cycling through instructions and thus makes scripting more efficient than performing the same tasks manually.
I will let you into a secret, I find loops magical. When a loop instructs the code to repeat the instructions 100 times in the blink of an eye, I still get a childlike joy from the result.
What tasks benefit most from looping? I suggest that looping is essential for WMI scripts where you want to cycle through a collection (collation) of say 27 properties before finding the property or attribute
you need. Active Directory domains have hundreds or even thousands of users; if you create a routine to change the Department field from say Customer Service to Help Desk, then it makes sense to repeat the routine
for each and every user that matches your criteria. Incidentally, criteria are dealt with separately and elsewhere by the, 'If ...then End IF' construction.
Any script which reads or writes data, benefits from a loop which calls for the next cell, or writes to the next line. As for logon scripts, they only occasionally need to loop. In conclusion, every branch of VBScript benefits from loops.
If you are looking for handy network utilities, try some of the free downloads at
Tools4Ever
I would begin simply. Start by getting the commands to work for one object. Only when the routine works perfectly would I 'top and tail' the routine with a loop. The
simplest loop construction is, For... Next. This loop is so straightforward you may even overlook the fact that the script is cycling through the commands between the For... and the Next.
With looping it's a matter of horses for courses. All that simple procedures need is the For.. Next loop. However, WMI scripts use groups or collations, therefore they require two extra words, EACH
and IN. Example, For EACH colItems IN objProcess.... Next. Scripts that read spreadsheets benefit from a different type of loop commands, Do UNTIL EOF (End of File)... Loop.
Alternatively, Do UNTIL
strxyz = "" (Null String).
In Example 1, we want a script to test the For... Next loop. All that this scriplet does is echo numbers 1 to 7 to the screen. Although this is the simplest of the loop commands there are a few points to
note. The basic syntax is: For counter x to y. Example For intCounter 1 to 7.... Next. I prefer the long variable name intCounter, whereas many scriptwriters just use the single character - i. For i 1
to 7.
Instructions for Creating a For.. Next Script This script should work on any Windows machine. Copy and paste the example script below
into notepad or use a VBScript editor.
One advantage of a good script editor such as OnScript is that you can see break out of the script if it goes wrong.
To get
OnScript Script Editor. See menu top left
Save the file with a .vbs extension, for example:
ForNext.vbs
Double click ForNext.vbs and check the message box.
' ForNext.vbs ' Example VBScript to create a simple loop ' Author Guy Thomas http://computerperformance.co.uk/ ' Version 1.5 - October 2005 Option Explicit Dim intCounter, strDays
strDays = "Days of Week ----------------" intCounter = 1 ' ========================================== ' For next loop section For intCounter = 1 to 7 strDays = strDays & chr(10) & "Day " &
intCounter Next ' ========================================= WScript.Echo strDays intCounter = 0 WScript.Quit
Guy Learning Points
Note 1: Even though this is a simple script, I still use Option Explicit to force me to declare all my variables. Note 2: intCounter controls the number of loops or cycles. The
syntax always expects a counter in the format counter = x to y. Where x and y are whole numbers. Note 3: You can be 'flashy' and add extra parameters, for example Step z. Where z is a number such
as two. It does not make much sense in this example, but you could use: For intCounter = 1 to 7 Step 2. Note 4: The WScript.Echo statement is actually outside the loop. If we put
WScript.Echo strDays inside the loop then we get RSI pressing the 'OK' button 7 times instead of once. Note 5: I am embarrassed to tell you how long it took me to deduce that I needed chr(10) to force a line
feed. Stupidly, I persisted far too long with vbCr, which is useless in this situation. chr(13) did not work either. Addendum Alison wrote in suggesting that I (we) use vbCrLF
for this situation. strDays = strDays & vbCrLf & "Day " & intCounter. Brilliant thank you Alison. Challenges You always learn more when you start altering someone else's
script, rather than slavishly copy it.
- Try different values for intCounter = 1 to 7. (1 to 5, 2 to 9)
- Add the Step command, For intCounter = 1 to 7 Step 2.
- Move the WScript.Echo command inside the loop.
- Substitute vbCr for chr(10). This is a deliberate mistake.
This second example takes a giant step forward from the first script. However, if you study it carefully I expect that you can make the conceptual leap from For... Next to Do While... Loop.
For... Next is not the only looping method. I want to emphasise that different tasks require different loops. In Example 2 I have replaced, For.. Next with Do While.... Loop. In addition, I could not resist introducing Select
Case, I love this construction and it helps to give the script purpose.
' ForNextSelect.vbs ' Example VBScript to create a loop and employ Select Case ' Author Guy Thomas http://computerperformance.co.uk/ ' Version 2.2 - October 2005
Option Explicit Dim intCounter,
strWkDay, strWeekDay strWkDay = "Days of Week ----------------" intCounter = 1 ' =============================================== ' Do While Loop, also note intCounter = intCounter +1 Do While
intCounter < 8 call WeekDay strWkDay = strWkDay & chr(10) & intCounter & strWeekDay intCounter = intCounter +1 Loop WScript.Echo strWkDay WScript.Quit
'================================================ ' End of Do While Loop. (Start of Subroutine WeekDay() sub WeekDay() Select Case intCounter Case "1" strWeekDay = " Monday" Case "2" strWeekDay =
" Tuesday" Case "3" strWeekDay = " Wednesday" Case "4" strWeekDay = " Thursday" Case "5" strWeekDay = " Friday" Case "6" strWeekDay = " Saturday" Case "7" strWeekDay = " Sunday" ' Finish
with Case Else to catch exceptions Case Else strWeekDay = "Something Wrong" End Select End Sub
Guy Learning Points Note 1: The statement: Do While intCounter < 8 .. Loop, can also be written: Do Until intCounter > 8 ... Loop. There also two more variants.
Do ... Loop Until and Do.... Loop While. Whichever variant you employ, always remember to add an incrementor, for example, line 14: intCounter = intCounter +1. Note 2: Imagine that the script is designed to generate the days of the week.
The Select Case construction gives the numbers greater meaning, for example, Day 1 now indicates Monday. This extra codes adds clarity. Note 3: To isolate and to emphasise both the Loop
and Select
Case I created Select Case as a sub routine. You could move the Sub WeekDay() section inside the loop and also remove the line: Call WeekDay, however I prefer the method as it stands.
Looping is the core command that automates scripts. Almost every script benefits from a routine that repeats commands for each object that you wish to manipulate. Changing Active Directory
attributes and cycling through WMI collations are classic scripting tasks. What these scripts do is get you started, they provide a test bed for perfecting the loop structures which you can then 'top
and tail' a routine which your scripts need to repeat.
Their topics and material are ideal for getting you started with VBScript. The
videos are easy to follow and you can control the pace. Try their free demo material and then see if you want to buy the full package.
See more about VB Script Training CD.
|