Guy’s Scripting Ezine 100 – ‘If’ Statements

Contents for Ezine 100 – ‘If’ Statements

This Week’s Missions – ‘If’ Statement also Datepart and Time

This week’s main mission is to master the tiny but useful, ‘If’ conditional statement.  Every scripting language has an ‘If’ construction, we are going to study the VBScript syntax for ‘If’…Then  End If.  I will also touch on variations such as ElseIf.

The context for this week’s script is checking the system clock, (next week I promise we will use a new vehicle for our scripts – Active Directory).  What we want to do is display different messages depending on whether the computer’s clock is fast, slow, or synchronized with the external time source.  Here is an example:

If timeDiff < 0 then
WScript.Echo "Clock was fast by " & -timeDiff & " secs"
End If

0) I like this 3 line version of the ‘If’ logic.  However, it is possible to employ short ‘If’ statements all on one line.
    If timeDiff < 0 then xyx.

1) Observe the word ‘then’.  See how ‘then’ follows the test, ‘If timeDiff < 0’ and notice that ‘then’ is the last word on the first line.

2) To tell VBScript that ‘If’ has finished evaluating the test statement, sign off with, ‘End If’ (note the space between End and If.

3) As you can see, the ‘If’ construction is flexible.  In scripts where there is a main test and only one subsidiary, then I recommend that you employ ‘If’ (as usual) and just one plain ‘Else’ statement.  With VBScript, when you have three or four tests, then precede the second and subsequent test with ElseIf.

ElseIf is different from Else If.  Where possible, choose ElseIf (all one word) because then you only need one End If no matter how many ElseIfs you have.  Avoid Else (space) If unless you have a specific reason for using this construction, the reason being each Else (space) If needs its own End If.  As ever, examples clarify thinking.

Example A (Good)

If timeDiff < 0 then
     WScript.Echo "Clock was fast by " & -timeDiff & " secs"
     ElseIf timeDiff > 0 then
     WScript.Echo "Clock was slow by " & timeDiff & " secs"
     ElseIf timeDiff = 0 then
     WScript.Echo " Clock synchronized " & timeDiff & " difference"
End if

Below, I added the extra End If, caused by choosing Else If instead of ElseIf.

Example B (Not Recommended)

If timeDiff < 0 then
     WScript.Echo "Clock was fast by " & -timeDiff & " secs"
     Else If timeDiff > 0 then
     WScript.Echo "Clock was slow by " & timeDiff & " secs"
     Else If timeDiff = 0 then
     WScript.Echo " Clock synchronized " & timeDiff & " difference"
End if
End if
End if

4) Should you have more than five ElseIf statements then consider a different construction altogether – Select Case.

Time and Date Functions – DATEPART and Time

Almost incidentally, this week’s script features time functions.  There is a whole family of related date and time functions, for example, NOW, TIME and DATEPART.  In this week’s ezine, Datepart and TIME play a role  in calculating whether the computer clock was fast, slow or synchronized with the time server.  As with previous scripts, this script cries out for you to deliberately alter the computer’s clock; otherwise the script just says ‘Clock synchronized’ .

When Datepart reads the TIME function, "s" means seconds, minutes is ‘n’ (and not "m"), while hour is ("h").  My mission was to translate the clock time into seconds, then we can compare one pure number with another.

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

This Week’s Secret

SENDKEYS is a useful method for leaning what the code is doing.  I also use .Sendkeys for troubleshooting what went wrong.  However, in the case of production scripts favour the .RUN method.  You can imagine the potential for disaster if you or a user switches windows after one .Sendkeys {} command and before the next.  At best the script would fail, at worst it could unleash a disastrous sequence of commands.

Example: To Synchronize with the Windows Time Service

Purposes of the Script

The script synchronizes the local machine with an internet time server, then displays a message indicating if the internal clock was slow, fast or on time.

Instructions for Synchronizing with the Windows Time Service
This script is designed for Windows servers, but there is no reason why it should not work on an XP machine.  If you use uk.pool.ntp.org or time-a.nist.gov as the time server, make sure that your machine has an internet connection.

  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 the line numbers, which helps when you have to troubleshoot error messages.

  3. Save the file with a .vbs extension, for example: SynchTime.vbs 

  4. Double click SynchTime.vbs, and check the clock synchronization in the message box.

‘===========================================
‘ VBScript Source File — Created with XLnow OnScript
‘ SynchTime.vbs
‘ AUTHOR: Guy Thomas
‘ COMPANY: Computer Performance
‘ DATE: January 2006 Version 3.2
‘ COMMENT: Script to synchronize with the Time service
‘===========================================
Option Explicit
Dim objShell
Dim intShortSleep, intLongSleep, strService
Dim strTimeSrv, timeBefore, timeAfter, timeDiff
Set objShell = CreateObject("WScript.Shell")
strService = "w32Time"
intShortSleep = 3000
intLongSleep = 6000 ‘1000 = 1 second

‘ Time Server set (Remove ‘ Rem if you want to change)
strTimeSrv = "time-a.nist.gov"
‘strTimeSrv = "uk.pool.ntp.org"

‘ Use .Run method to configure the time server
objShell.Run "w32tm /config /syncfromflags:manual /manualpeerlist:"_
& strTimeSrv
Call Restart()
‘ Collect time before the script synchronizes
timeBefore = DatePart("s" , Now) + DatePart("n" , Now) *60
timeBefore = timeBefore + DatePart("h", Now) *3600

‘ Key command to resynchronize with time server
objShell.Run "w32Tm /resync /rediscover"
Wscript.Sleep intShortSleep
timeAfter = DatePart("s" , Now) + DatePart("n" , Now) *60
timeAfter = timeAfter + DatePart("h", Now) *3600

‘ Cosmetic section to display the clock adjustment
timeDiff = (timeAfter – timeBefore) – (intShortSleep/1000)
If timeDiff < 0 then
    WScript.Echo "Clock was fast by " & -timeDiff & " secs"
       ElseIf timeDiff > 0 then
       WScript.Echo "Clock was slow by " & timeDiff & " secs"
       ElseIf timeDiff = 0 then
       WScript.Echo " Clock synchronized " & timeDiff & " difference"
End if
WScript.Quit

Sub Restart()
‘ Restart Service
objShell.Run "net stop " & strService
objShell.Run "net start " & strService
Wscript.Sleep intLongSleep
End Sub

VBScript Tutorial – Learning Points

Note 1:  Get into the rhythm of the If, then, End If.  This simple construction is versatile and greases the wheels of many VBScripts.

Note 2:  ElseIf is better than Else If.  My advice is avoid a space between Else and If, unless you deliberately want a different outcome.  If you have more than five ElseIfs then investigate the alternative Select Case.

Note 3:  Observe how this script employs the .Run method rather than .Sendkeys {}.

Guy Recommends: SolarWinds Free Network Bandwidth MonitorFree Real-Time Bandwidth Monitor

This freeware monitor is great for checking whether your network’s load-balancing is performing as expected, for example, are two interfaces are getting about equal traffic?

It’s easy to install and straightforward to configure. You will soon be running tests to see how much network bandwidth your applications consume.

The GUI has a lovely balance between immediate network traffic data in the middle, combined with buttons to seek related data and configuration settings. Give this monitor a try, it’s free! 

Download your free network bandwidth monitor

If you need more comprehensive network analysis software:
Download a free trial of NPM (Network Performance Monitor)

Challenges

  • Try deliberately setting the computer’s script fast or slow.
  • Give the script a real job by stopping the Windows Time service before running the script.
  • Experiment with the intSleep variables.  Try changing the values, or even removing them.
  • See the difference a space makes in Else If (Instead of ElseIf) and see how Else If requires its own matching End If.
  • I tried simplifying, timeAfter = DatePart("s" , Time) + DatePart("n" , Time) *60
    to timeAfter = Time.  My results were disappointing, the value was always the same, even though I changed the time on the computer clock.

Summary of ‘If’ Statement

The ‘If’ conditional statement is flexible and adds value to so many VBScripts.  Take the time to master the syntax, especially of ElseIf.

SendKeys is great in testing and troubleshooting, but production scripts are more reliable if you employ the .Run method.

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