Contents for Ezine 100 - 'If' Statements
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.
If you are looking for handy network utilities, try some of the free downloads at
Tools4Ever
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.
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. 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 the line numbers, which helps when you have to troubleshoot error messages. -
Save the file with a .vbs extension, for example:
SynchTime.vbs 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 PointsNote 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 {}.
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.
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.
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.
|