Guy’s Scripting Ezine 90 – Looping

Contents for Ezine 90 – Looping

This Week’s Secret – Why Loop?

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.

Guy Recommends: Tools4ever’s UMRAUMRA The User Management Resource Administrator

Tired of writing scripts? The User Management Resource Administrator solution by Tools4ever offers an alternative to time-consuming manual processes.

It features 100% auto provisioning, Helpdesk Delegation, Connectors to more than 130 systems/applications, Workflow Management, Self Service and many other benefits. Click on the link for more information onUMRA.

Tactics for Looping

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).

Example 1: Simple For.. Next loop.

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.

  1. Copy and paste the example script below into notepad or use a VBScript editor.

  2. One advantage of a good script editor such as OnScript is that you can see break out of the script if it goes wrong.

  3. To get OnScript Script Editor. See menu top left

  4. Save the file with a .vbs extension, for example: ForNext.vbs 

  5. Double click ForNext.vbs and check the message box.

‘ ForNext.vbs
‘ Example VBScript to create a simple loop
‘ Author Guy Thomas https://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.

Guy Recommends: The Free IP Address Tracker (IPAT) IP Tracker

Calculating IP Address ranges is a black art, which many network managers solve by creating custom Excel spreadsheets.  IPAT cracks this problem of allocating IP addresses in networks in two ways:

For Mr Organized there is a nifty subnet calculator, you enter the network address and the subnet mask, then IPAT works out the usable addresses and their ranges. 

For Mr Lazy IPAT discovers and then displays the IP addresses of existing computers. Download the Free IP Address Tracker

Example 2: Do While Loop Meets Select Case

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 https://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.

Summary of Looping

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.

See more about VBScript

VBScripts  • Ezines  • WMI  • Logon Scripts   • PowerShell Foreach  •Tool Kit

• Ezine 1 Loops   •Ezine 14 Loops  • Ezine 47 .put  • PowerShell Loops  • Free Web Watcher

• Ezine 90 VBS Looping  • Ezine 91 VBS Looping   • Ezine 92 LDIFDE   • Ezine 100 If