Scheduling Script Execution
In this chapter, Molly will write a new script that she will then execute every 24 hours using the Windows Task Scheduler. This script, once executed, will be responsible for running each of the report and log analyzer scripts sequentially. As you go through this chapter, you will learn why Molly chose to create a scheduling script instead of simply setting up each of the report and log analyzer scripts as independent scheduled tasks. You will also learn how to work with the Scheduled Task Wizard.
Examining Scheduling VBScript Options
Now that Molly has finished writing and testing each of the report and log analyzer scripts, she needs to set up their automated execution. To accomplish this task, she plans on using the built-in Task Scheduler service. Molly has decided to use the Scheduled Task Wizard to define the execution schedule for report and log files.
Molly has learned that in order for her scripts to run with the appropriate security permissions and privileges when they execute, she will need to set up a special user account, which she calls a service account, and then associate that account with her scheduled tasks. Molly has already set up a new user account to be used to run any scripts that need to execute on an automated time schedule. She named this account ScriptSchlr and set it up as a local administrator account on the Windows 2000 Server where the order/inventory system resides.
Creating a Scheduled Task for Each Script
Molly has discovered that in order to set up the scheduled execution of each script individually, she will have to repeatedly run the Scheduled Task Wizard and associate each individual script to run using the ScriptSchlr account. Although not a difficult task to perform, Molly is concerned about the long-term maintenance of these scripts and of the ScriptSchlr account.
Even though she created the ScriptSchlr account with a password that does not expire, Molly knows that she will have to manually change its password at least once every six months in order to comply with the company's IT audit policy. This means that every six months, she will have to remember to not only change the ScriptSchlr account's password but also to go to the Scheduled Tasks folder and modify the scheduled task for each report and log script. This introduces the possibility that she may make a mistake and mistype the password for one or more scheduled tasks when modifying its schedule.
Creating an Intermediary Scheduling Script
To simplify things and to limit the potential for mishap as much as possible when she has to change the ScriptSchlr account's password, Molly has decided to create a new script called MstrSched.vbs. This script will take responsibility for sequentially running each of the report and log analyzer scripts, as depicted in Figure 19.1.
Figure 19.1: Automating the execution of multiple scripts from a single VBScript
This way, Molly only has to configure one scheduled task in order to set up the automated execution of all her report and log analyzer scripts, and she will only have to modify the account password for one scheduled task every six months.
Using the WshShell Object's Run() Method
After spending some time looking through the Windows Script Technologies help file, Molly came across the Run() method. This method belongs to the WshShell object and provides the ability to execute a program or script as a new process. It also provides the ability to wait on a child script run using the Run() method to finish executing before allowing the calling script to continue its execution.
Note |
The Windows Script Technologies help file is a freely downloadable help file for the WSH (Windows Script Host). It provides a complete document of the WSH object model. In addition, it includes complete documentation of VBScript and JScript. To download a copy of the Windows Script Technologies help file, visit http://www.microsoft.com/scripting and look for a link called Scripting Documentation Available for Download. |
Ensuring the sequential execution of each report and log analyzer script is a key requirement for Molly because it allows her to create one script that can schedule the execution of additional scripts sequentially, in order to ensure that only one child script runs at a time. By forcing the report and log analyzer scripts to run sequentially, Molly does not have to worry about any errors that would otherwise occur if two or more of the report and log analyzer scripts tried to access and write to the summary report at the same time.
Note |
Detailed coverage of the Run() method is provided in the section "Working with the Windows Command Prompt" found in Chapter 13, "Scheduling Disk Maintenance." |
Testing Her Hypothesis
In order to ensure that the Run() method will work as she thinks it should, Molly decides to perform a quick test and writes the following script.
'************************************************************************* 'Script Name: Script 19.1.vbs 'Author: Jerry Ford 'Created: 03/22/03 'Description: This script demonstrates the ability of the WshShell object's 'Run() method to sequentially control the execution of multiple child 'scripts. '************************************************************************* 'Initialization Section Option Explicit On Error Resume Next Dim WshShl Set WshShl = WScript.CreateObject("WScript.Shell") 'Main Processing Section WshShl.Run "Notepad", 1, True WshShl.Run "Notepad", 1, True 'Terminate script execution WScript.Quit()
The script is designed to call the Notepad application, pause for as long as it executes, resume execution by starting another instance of the Notepad, and then pause again until the Notepad application is closed. The VBScript statement that makes this process work is the following.
WshShl.Run "Notepad", 1, True
In addition to passing the name of the Notepad application as a parameter to the Run() method, two more parameters are passed. The first parameter is a numeric value that specifies the Windows style with which the Notepad application should be opened. By specifying this value as a 1, the script will open Notepad in the exact same manner as if it were started from the Start menu. The second parameter passed to the script determines whether the script should wait on the Notepad application to finish running before resuming its own execution. By setting this value equal to True, Molly ensures the sequential execution of both instances of the Notepad application. Had she made the value of the second parameter equal to False, both instances of the Notepad application would have opened at the same time.
Monitoring Background Processes
When Molly executed her test script, she saw the first Notepad window appear. To verify that her VBScript was waiting in the background for the Notepad application to be closed, she opened the Windows Task Manager utility and verified that the script was still executing, as shown in Figure 19.2.
Figure 19.2: Verifying that the VBScript is still executing as a background task
Because she ran the script from the Windows desktop, it was processed by default using the WScript.exe execution host. Although the script itself does not appear in the list of active processes displayed by the Task Manager utility, the presence of an active WScript.exe execution host—when she knows that no other scripts are currently executing—is sufficient for her to infer that her test script is still running in the background. By leaving the Task Manager utility visible as she closes the first and second instances of the Notepad application, Molly is able to witness the termination of the test VBScript.
Setting Up an Intermediary Scheduling Script
Now that Molly is confident that she can use the WshShell object's Run() method to enforce the sequential execution of the report and log analyzer scripts, she begins work on developing the MstrSched.vbs script. To complete the development of this script, Molly will also have to learn how to work with a number of new built-in VBScript functions, as discussed in the following sections.
Creating Logic to Limit When the Script Can Execute
Molly plans to create a single script that will control the execution of both her report and log file analyzers and an archive management script that needs to be executed on the first day of each month. Molly plans to use the built-in VBScript Day() and Date() functions to ensure that the archive management script, which is named ArchiveManager.vbs, will only execute on the first day of each month. This way Molly can write a single script that can handle scheduling the execution of the MstrSched.vbs every day to run the report and log analyzer scripts, and still accommodate the monthly execution of the archive management script.
The syntax of the Date() function, which returns the current system date, is outlined below.
Date()
When executed, it returns the current system date in the form of mm/dd/yyyy, as demonstrated below.
strTodaysDate = Date() MsgBox strTodaysDate
When executed, the previous VBScript statement displays a pop-up dialog box, as demonstrated in Figure 19.3.
Figure 19.3: Using the Date() function to display the current system date
One way to use the information returned by the Date() function is to determine whether or not a VBScript is being run on the first day of the month would be to parse out the value of the day field and determine whether it is equal to 1. An easier way to achieve this same result is to use the value returned by the Date() function as input to the Day() function. The Day() function returns a numeric value indicating the day of the month. The syntax for the Day() function is outlined below.
Day(Date)
Date represents any expression that specifies a date. Therefore, by wrapping up the Date() function inside the Day() function, as shown below, you can easily determine the current day of the month.
strTodaysDate = Day(Date())
When executed on the first day of the month, the value of strTodaysDate would be set equal to 1. By testing the value of strTodaysDate, you can incorporate logic into a script that automatically terminates its execution if the day of the month is set to anything other than 1.
Writing the MstrSched vbs Script
The MstrSched.vbs script is very basic in its design. Given the script's relatively simple role and her tight project development schedule, Molly elected not to spend a lot of time on it or to give it too many bells and whistles. For example, she did not see the need to externalize its settings, nor did she add extra logic to subroutines that accept arguments in order to validate the receipt of any arguments or their validity.
The Initialization Section
The script's Initialization Section, shown below, enables the strict interpretation of variable names and error checking. This section also defines and instantiates the WshShell object.
Option Explicit On Error Resume Next Dim WshShl Set WshShl = WScript.CreateObject("WScript.Shell")
The Main Processing Section
The Main Processing Section, shown below, begins with a series of four procedure calls to a subroutine named RunScript(). This subroutine accepts one argument, the name of a script to execute. Each of these four statements passes the RunScript() subroutine a different script name. Because the MstrSched.vbs script will be run daily, these four scripts will always be processed and their execution will occur sequentially. The next several lines in the Main Processing Section are designed to provide for the monthly execution of the ArchiveManager.vbs script. An If statement is used to execute the Day() and Date() VBScript functions in order to ensure that the Archive Manager.vbs script will only be executed on the first day of the month. Finally, the last statement in this section uses the WScript object's Quit() method to terminate the script's execution.
RunScript("ErrorAnalyzer.vbs") RunScript("SalesAnalyzer.vbs") RunScript("ReturnsAnalyzer.vbs") RunScript("ProductionAnalyzer.vbs") If Day(date()) = 1 Then RunScript("ArchiveManager.vbs") End If 'Terminate script execution WScript.Quit()
The RunScript() Subroutine
The RunScript() subroutine, shown below, consists of three statements. The first statement identifies the name of the subroutine and defines the procedure's input argument. This argument represents the name of a report or log analyzer script and is used by the Run() method to specify the name of the script to be run. Each script run by this subroutine runs as a background task. In addition, this script will wait for each of the scripts that it calls to complete before returning processing control back to the statement that called it.
Sub RunScript(ScriptName) WshShl.Run ScriptName, 1, True End Sub
The WriteToEventLog() Subroutine
The WriteToEventLog() subroutine, shown below, uses the WshShell object LogEvent() method to store a message event in the Windows application event log. This way Molly can verify the execution of the script by examining the system log, which she can do remotely from her Windows XP Professional desktop using the Event Viewer snap-in found in the Computer Management console.
Sub WriteToEventLog() WshShl.LogEvent 4, "Report and Log Analyzer Scheduler Script executing." End Sub
Note |
The Event Viewer snap-in found in the Computer Management console is started on Windows XP Professional by clicking on Start, right-clicking on My Computer, and selecting Manage from the context menu that appears. This opens the Computer Management console. To view the application log on a Windows 2000 Server for which you have the appropriate security rights and permissions, right-click on the Computer Management (Local) node at the top of the console tree and select Connect to another computer. Then supply the name or IP address of the other computer and click on OK. All that you have to do is expand the System Tools node, followed by the Event Viewer node, and then select the Application node to view the events stored in the remote computer's applications log. |
The Fully Assembled Script
The entire VBScript is assembled below. When executed, it will run each of the report and log analyzer scripts sequentially. In addition, on the first day of each month it will run the archive management script.
'************************************************************************* 'Script Name: Script 19.1.vbs 'Author: Jerry Ford 'Created: 03/22/03 'Description: This script runs the report and log analyzer scripts, 'one at a time, waiting on each to complete before running the next script. '************************************************************************* 'Initialization Section Option Explicit On Error Resume Next Dim WshShl Set WshShl = WScript.CreateObject("WScript.Shell") 'Main Processing Section RunScript("ErrorAnalyzer.vbs") RunScript("SalesAnalyzer.vbs") RunScript("ReturnsAnalyzer.vbs") RunScript("ProductionAnalyzer.vbs") If Day(date()) = 1 Then RunScript("ArchiveManager.vbs") End If 'Terminate script execution WScript.Quit() 'Procedure Section Sub RunScript(ScriptName) WshShl.Run ScriptName, 1, True End Sub Sub WriteToEventLog() WshShl.LogEvent 4, "Report and Log Analyzer Scheduler Script executing." End Sub
Setting Up a Daily Automated Script Execution Schedule
Now that her script has been written, Molly needs to create a scheduled task to run it every morning, which she has decided to do at 4:00 A.M. The reports are generally ready for processing at midnight of each day and the nightly backup job that runs next on the server is typically finished at 2:00 A.M. Molly figures that by adding an additional two hours, she will be able to run her scripts without having to worry about whether the reports are ready or if the backup job is still processing.
Molly thought about creating another VBScript to set up the scheduled task for the MstrSched.vbs script. However, given that this is a one-time setup task, she decided that it was not worth the effort of writing another script just for this task. Instead, she will use the Scheduled Task Wizard as outlined in the following procedure.
- Click on Start and then Control Panel. The Control Panel opens.
- Click on Performance and Maintenance. The Performance and Maintenance folder opens.
- Click on Scheduled Tasks. The Scheduled Tasks folder opens, as shown in Figure 19.4.
Figure 19.4: The Scheduled Tasks folder provides a focal point for managing all scheduled tasks
- An icon is displayed for every currently scheduled task. To set up a new scheduled task, double-click on the Add Scheduled Task icon. The Scheduled Task Wizard starts. Click on Next.
- The wizard prompts you to select a program for which you would like to set up an automated schedule, as shown in Figure 19.5.
Figure 19.5: The Scheduled Task Wizard automatically presents a list of applications whose execution can be automated
- Click on Browse. The Select Program to Schedule dialog box appears. Use this dialog box to locate the MstrSched.vbs script, as shown in Figure 19.6.
Figure 19.6: Use the Select Program to Schedule dialog box to locate the VBScript that you wish to set up as a scheduled task
- Select your script and click on Open.
- The wizard prompts you to supply the name for the new scheduled task and to select a type of schedule for running it, as shown in Figure 19.7. Select Daily and click on Next.
Figure 19.7: The Scheduled Task Wizard assists you in setting up scheduled tasks using a variety of different schedules
- You are prompted to supply the specific time of day at which the scheduled task should run, as shown in Figure 19.8. Enter 4:00 P.M. in the Start Time field. Select the Every Day option located in the Perform this task section of the dialog box and then click on Next.
Figure 19.8: The Scheduled Task Wizard requires that you specify a time of day for the execution of the scheduled task
- Next you are prompted to specify the name of a user account and its associated password, as shown in Figure 19.9. This scheduled task will use the user account's access privileges when executing your scripts. Molly would type ScriptSchlr in the username field and the account's password in the dialog box's two password fields.
Figure 19.9: Provide the name of a user account with sufficient security permissions and access rights to run your scripts
- The wizard announces that it has successfully created a new scheduled task. Click on Finish. The new scheduled task will now appear in the Scheduled Tasks folder.
Summary
This chapter explained why Molly decided to write a new script that would be responsible for the execution of each of the report and log analyzer scripts. It demonstrated how to create this script using the WshShell object's Run() method and explained how to use this method to enforce the sequential execution of scripts. This chapter also outlined the steps involved in configuring the automated execution of scripts using the Scheduled Task Wizard.