Contents for Ezine 99 Time Now
I want to combine a script that is useful in its own right with a script with that can be adapted to other scenarios. This week's script to restart Windows services fits the bill perfectly.
This Week's Mission - Restart ServicesThis week's mission is to restart a Windows Service such as the Windows Time service. As a matter of tactics, it's much more satisfying to cure a problem
by restarting a service than by rebooting the machine. Not only is restarting the service faster, and less disruptive for users, but also it entices you to pinpoint the problem. This Week's Scripting Mission
- VariablesI want to introduce variables and show you how I employ a adaptation of the Hungarian Variable system in my scripts. Variables, now function. Just having fun remember main agenda help people get started with VBScript. Everyone copies a good script and uses it with minimal thought.
I want to take you to the next level where you know what to look for in a script, thus you can make sensible adjustments, even improvements. I realize that using Time as the vehicle for the third week in a row
will bore those with a low concentration threshold, the other side of the coin is it makes the scripts familiar to newcomers. There is a sense of building on success, which is not to be underestimated when
writing
scripts. I have flirted with scripting languages which were very strict in declaring variables, in comparison VBScript is pure anarchy. For a start, you don't even have to declare variables at all.
If you do declare variables you can use any reasonable combinations of letters and numbers, string variables could be strServer, sServer, or you need not start with 's' at all. Children don't like anarchy, and so it is with
scripting. My advice is to impose rules when you name variables, but make them your rules not mine. The concept behind the Hungarian system for naming variables is that the first few letters give you a clue
whether the variable will be used for a string, number, time or other category of object. For example, strTimeSrv (string) intSleepLong (integer number). You may notice that invariably my scripts
begin with the almost inconsequential, Option Explicit. This forces me to declare my variables, the benefit is that Option Explicit warns me if (when) I make a typo later in the script. Now
Purpose of the Script
The primary purpose of this example is to resync with a time server. Just in case no time server has been set, or you wish to swap time servers, the script includes a W32 time command to set the Time
Server. This is the equivalent of the net time /setsntp we used in last week's script. Known problem
Sometimes the Windows Time service mysteriously stops, or appears started, yet is not working properly. Symptoms, when you run my script you get error 800706B5 or a similar code number. Fortunately, the
solution is easy, navigate to the Administrative Tools, services and re-start the Windows Time Service. I can here you thinking,
'why doesn't Guy put a restart command in the script?' I could add the code, but remember my resolution to keep it simple? Restarting services will feature in future ezine, then you can bolt both
together to solve the problem.
Instructions for synchronizing the Time Server This script is designed for servers, but there is no reason why it should not work on an XP machine. If you use my time server (uk.pool.ntp.org or time-a.nist.gov),
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:
W32tm.vbs
Double click W32tm.vbs, observe the cmd session and check the message box.
'====================================================== ' VBScript Source File -- Created with XLnow OnScript ' W32tm.vbs ' AUTHOR: Guy Thomas ' COMPANY: Computer Performance ' DATE: January
2006 Version 1.4 ' COMMENT: Script to set the time server, then sync ' Known problem. Windows Time Service stopped or 'Jammed'. Restart it. '=======================================================
Option Explicit Dim objShell Dim intShortSleep, intLongSleep Dim strTimeSrv Set objShell = CreateObject("WScript.Shell")
' Time Server set (Remove ' Rem if you want to change) 'strTimeSrv
= "time-a.nist.gov" strTimeSrv = "uk.pool.ntp.org" intShortSleep = 500 intLongSleep = 4000 '1000 = 1 second
' Cmd prompt opened with .Run method objShell.Run "cmd" Wscript.Sleep
intShortSleep objShell.SendKeys "{Enter}"
' set the time server. Equivalent of net time /setsntp Wscript.Sleep intShortSleep objShell.SendKeys "w32tm /config /syncfromflags:manual
/manualpeerlist:"_ & strTimeSrv objShell.SendKeys "{Enter}" Wscript.Sleep intShortSleep
' Point where the script synchronizes objShell.SendKeys "w32Tm /resync /rediscover"
objShell.SendKeys "{Enter}" Wscript.Sleep intLongSleep
' Cmd prompt exited objShell.SendKeys "Exit" Wscript.Sleep intShortSleep objShell.SendKeys "{Enter}"
Wscript.Echo " Time
Server synchronized with: " & strTimeSrv WScript.Quit
VBScript Tutorial - Learning PointsNote 1: The header section, between the == records the script's, date, version number and purpose. This section is always optional, but
recommended as it helps troubleshooting. Note 2: Option Explicit forces me to declare all my variables. This is why I have Dim statements at the top of my scripts, to dimension variables such as
strTimeSrv. Note 3: On line 14 this script creates the shell object. Later we employ the shell object (objShell) and the .SendKeys method to send keystrokes to the command prompt. Note 4: W32tm is the
command line equivalent of the Windows Time service. Observe how the script sets the external time source with, config /syncfromflags:manual /manualpeerlist. Note 5: This week's
new feature is the w32Tm /resync /rediscover command, which is not available with 'Net time'. Challenges
- Deliberately alter your computer's clock by about 10 minutes and then run the script. Observe VBscript correct the time.
- Deliberately stop the Windows Time service and prove that error 800706B5 is not a figment of my imagination.
- At the cmd prompt, try w32tm /? Perhaps this will give you ideas for other experiments with this script.
Summary of W32tm VBScript.W32tm is a more versatile command than 'net time'. In particular you can now resync a computer with its time server. From a VBScript point of view, get into
the habit of adding or amending your script's header. Another best practice is to start your script proper with Option Explicit followed by the Dim statements.
If you are looking for handy network utilities, try some of the free downloads at
Tools4Ever
Purpose of the Script
Here is a very simple VBScript, which is designed to multiply two numbers. This script generates
two input boxes. Each box collects one number, the script should then multiply the two numbers and should calculate the correct answer. However, something is amiss and each answer is wrong. How can you
troubleshoot the code to make sure it always displays the correct maths?
' InputNumber.vbs ' VBScript Multiply two numbers ' Author Guy Thomas http://computerperformance.co.uk/ ' Version 1.2 - December 2005 '
-----------------------------------------------------------------' Option Explicit Dim strInput, strFirst, strSecond, strProduct, intFirst, intSecond
' Input Boxes to get the values of the two
numbers Do strFirst = (InputBox(" First Number", "Enter First Number")) intFirst = IsNumeric(strFirst) If intFirst = True Then strInput =
True Else WScript.Echo "Enter a number not a letter" End if Loop until strInput = True strInput = False Do While strInput = False strSecond = (InputBox(" Second Number",
"Enter Second Number")) intSecond = IsNumeric(strSecond) If intSecond = True Then strInput = True Else WScript.Echo "Enter
a number not a letter" End if Loop
' Calculation strProduct = strFirst * strSecond + int((rnd * 7)+1) WScript.Echo strFirst & " multiplied by " & strSecond _ & " = " & strProduct
WScript.Quit ' End of Example VBScript.
VBScript Tutorial - Learning Points1) This script provides a refresher on the syntax of InputBox. Observe how the variable strFirst is set to the value entered in the box. Also note
how inputbox() has two extra arguments to guide users in entering information correctly. 2) IsNumeric provides error correcting code. The job of this function is to make sure that the user enters a number and not a letter. 3) I am very
fond of code that repeats instructions, for this example I demonstrate two variations of looping; a) Do .... Loop Until, b) Do While.... Loop.
The purpose of this script is to map a network share to a suitable drive letter. However, even if you substitute a valid UNC path on your network for \\ grand \home, the script still fails. Your task is to make
a simple correction to one line in the script and so get this logon script working correctly.
' MapNetworkDrive.vbs ' VBScript to map a network drive to a UNC Path. ' Author Guy Thomas http://computerperformance.co.uk/ ' Version 1.2 - December 2005 '
------------------------------------------------------------' Option Explicit Dim objNetwork Dim strDriveLetter, strRemotePath strDriveLetter = "C:" strRemotePath = "\\grand\home" ' Purpose
of script to create a network object. (objNetwork) ' Then to apply the MapNetworkDrive method. Result J: drive Set objNetwork = CreateObject("WScript.Network")
On Error Resume Next
objNetwork.MapNetworkDrive strDriveLetter, strRemotePath If err.number = -2147024811 then WScript.Echo "Guy's problem is set - Drive letter in use" Else If err.number =
-2147023693 then WScript.Echo "Check UNC Path" Else If err.number = 0 then WScript.Echo "Successfully mapped " &
strDriveLetter Else Wscript.Echo err.number End If End If End If ' Purely for testing I added code to remove the
mapped drive ' Comment out, or delete the next line in a production script objNetwork.RemoveNetworkDrive strDriveLetter
WScript.Quit ' End of Example VBScript.
VBScript Tutorial - Learning Points1) I introduced error correcting code half way through this example. The extra lines have two opposite effects, they mask the problem, yet give
you extra clues to solve the problem. As part of my hidden agenda, the error correcting code shows you how to anticipate problems and add code to deal with 'exceptions'. 2) The decimal
numbers -2147024811 and -2147023693 are the equivalent of the Hex numbers that you see in the code 080070055 error messages. You see these 0800xxxxx message boxes if you run the script without the On Error Resume Next statement.
The purpose of this script is simply to display the day of the week = E.g. Saturday. As you may see, the code is in a terrible mess. You could be ruthless and reduce the whole script to a
few lines. In which case, don't be shy of researching VBScript and weekdays in Google. Alternatively, you could take the script at face value and cure each fault methodically. Should
you need clues, seek and remove the three sets of comments (') in the lines that follow Option Explicit.
' Weekday.vbs ' VBScript to determine the day of the week ' Author Guy Thomas http://computerperformance.co.uk/ ' Version 2.3 - December 2005 '
---------------------------------------------------------------' Option Explicit Dim DayWeek, DayWeek2 ' , strDay
DayWeek = Weekday(date(),0) 'DayWeek2 = WeekdayName(DayWeek) 'DayWeek2 =
WeekdayName(Weekday(date(),1))
Select Case DayWeek Case 1 strDay = "Sunny day" Case 2 strDay = "Mondale" Case 3 strDay = "Toes day" Case 4 strDay = "Wedding day" Case 5 strDay = "Thirsty
day" Case 6 strDay = "Frying day" Case 7 strDay = "Saturn day" Case Else strDay = "Something wrong" End Select
Wscript.Echo DayWeek & " = " & strDay & " " & DayWeek2
WScript.Quit '
End of Example VBScript.
Learning Points1) The first problem is to remember to declare all your variables. After all, the point of Option Explicit is to prevent typing errors later in
the script. 2) Date() is a built in VBScript function. It is possible to employ Date() to extract a
numeric representation of the day of the week, for example Saturday = 7. The underlying problem is whether to begin the week at Sunday or Monday. Research indicates that you control this
factor with date(),0 or ,date(),1. 3) While I love Select Case, I have deliberately used the command inappropriately; firstly, by misspelling the days of the week, secondly, it is possible to simplify
the whole scriplet to one command: DayWeek2 = WeekdayName(Weekday(date(),1)). |