Scheduling Disk Maintenance

This chapter addresses Tom's requirements for developing scripts that perform the scheduled execution of two different disk maintenance tasks, disk cleanup and disk defrag. In this chapter, you will learn how to develop scripts that perform these two tasks. You will also learn how to write a setup script that sets up the execution schedule for both disk maintenance scripts.

Working with the Windows Command Prompt

The WSH provides the ability to execute any Windows command or command line utility using the WshShell object's Run() method. This method runs the specified command or command-line utility as a new process. The Run() method has the following syntax:

WshShell.Run(Command, [WindowStyle], [WaitState])

Command identifies the command or command-line utility to be executed and may also include any arguments that need to be passed to the command or command-line utility. WindowStyle is an optional parameter that specifies the appearance of the window used to process the command or command-line utility. The value of WindowStyle is specified as an integer. Table 13.1 provides a list of the Windows style options supported by the Run() method. WaitState is an optional Boolean parameter that specifies whether the script will wait on the command or command-line utility to finish executing before continuing to run. Setting WaitState to True pauses script execution. The default is False.

Table 13.1: Run() Method Windows Style Options

Windows Style

Description

0

Hides and deactivates the window

1

Activates and displays a window, restoring it to its original position and size

2

Activates the window and minimizes it

3

Activates the window and maximizes it

4

Displays a window using its previous position and size without affecting the currently active window

5

Activates the window, displaying it using its current position and size

6

Minimizes the window and deactivates its focus

7

Displays a minimized window without affecting the currently active window

8

Displays the window using its current position and size without affecting the currently active window

9

Activates and displays the window restoring it to its original position and size

10

Uses the display status of the calling program to display the window

The following example demonstrates how to start the Windows Notepad application from within a VBScript using the Run() method.

Set WshShl = WScript.CreateObject("WScript.Shell")
WshShl.Run "%windir%
otepad"

The next example demonstrates how to start Notepad and pass it the name of a file to open.

Set WshShl = WScript.CreateObject("WScript.Shell")
WshShl.Run "%windir%
otepad c:docsActivity.doc"

This final example demonstrates how to start the Notepad application and have it display a copy of the script that opened it. In order to accomplish this trick, the script uses the WScript object's ScriptFullName property, which identifies the name of the currently executing script.

Set WshShl = WScript.CreateObject("WScript.Shell")
WshShl.Run "%windir%
otepad " & WScript.ScriptFullName


Disk Management Utilities and Command Line Utilities

In recent years, the capacity of hard disk drives has increased greatly. At the same time, the cost of hard drives has been decreasing. As quickly as disk capacity has grown, so have the storage requirements for new applications. As a result, careful disk drive management is an important consideration for many desktop administrators who are wary of continued complaints from the users that they support.

The policy at ABC, Inc. has been to ask all employees to run two Windows disk management utilities at the beginning of each month in order to help manage disk storage on their desktop computers. These utilities are Disk Cleanup and Disk Defragmenter. The Disk Cleanup utility frees up disk space by removing unnecessary files. The Disk Defragmenter reorganizes files that have been stored in fragments on disk drives.

Fortunately, like many Windows utilities, the Disk Cleanup and Disk Defragmenter utilities provide a command-line interface which exposes their functionality and makes it available to the Windows command line. Using the WshShell object's Run() method, you can execute either of these two utilities from within a VBScript.

Examining the Manual Disk Cleanup Process

Windows applications usually create temporary files while executing. Usually applications clean up these files when they close. However, events such as a system crash or a hung program often leave these files behind, unnecessarily using up disk space.

A computer's performance is directly related to the amount of free space available on its hard disk drives. As drives begin to fill up, a noticeable slowdown in performance will occur. Often the removal of unnecessary files will free up enough disk space to improve performance and prolong the storage capacity of the disk drive.

One way to reclaim lost space is to manually search for and delete unnecessary files. This not only is time consuming, but also opens up the possibility that a critical system or application file may accidentally get deleted in the process. Fortunately, Windows XP provides the Disk Cleanup utility. This utility provides users with a tool for manually tracking down and deleting many types of unnecessary files from their computer. The disk Cleanup utility can be used to delete any of the following types of files:

  • Downloaded program files
  • Temporary Internet files
  • Files found in the Recycle Bin
  • Temporary files
  • WebClient/Publisher temporary files
  • Catalog files for the Content Indexer

The employees at ABC, Inc. have been instructed to run the Disk Cleanup utility at the beginning of every month. Unfortunately, when Disk Cleanup is running, working on the computer is a painful process. Most users have fallen into the habit of either not running it as requested or using it as an opportunity to take extended coffee breaks.

In order to understand how Disk Cleanup works, it is helpful to run it at least once. The following procedure outlines the basic steps involved in performing this process.

  1. Click on Start/All Programs/Accessories/System tools and then select Disk Cleanup. If more than one hard disk drive is installed, the Select Drive dialog box will appear, as shown in Figure 13.1.

    click to expand
    Figure 13.1: Specifying the disk drive to be cleaned up by the Disk Cleanup utility

  2. Select a disk drive and click on OK. The dialog box shown in Figure 13.2 appears. The options that are displayed will vary depending on the drive that is selected.

    click to expand
    Figure 13.2: Specifying the files to be removed by the Disk Cleanup utility

  3. Select the types of file to be deleted and click on OK.
  4. Click on Yes when prompted for confirmation.
  Note

The Disk Cleanup utility can also be run from the Windows command prompt by invoking its executable. To initiate its execution in this manner, click on Start/Run and then type cleanmgr and click on OK.

Configuring Disk Cleanup

After doing some research on the Internet, Tom has learned that the Disk Cleanup utility provides a command-line interface. Therefore, its execution can be initiated by a VBScript. Once scripted, Tom plans to set up an automated execution schedule for the script. This way it can be scheduled to run after hours, when the users are not using their computers.

Before the execution of the Disk Cleanup utility can be automated, it has to be configured. Unfortunately, this is a manual process. But the good news is that it only has to be done once. The following procedure outlines the steps involved in configuring the Disk Cleanup utility.

  1. Click on Start and then Run. The Run dialog box appears.
  2. Type cleanmgr /sageset:1 as shown in Figure 13.3 and then click on OK.

    click to expand
    Figure 13.3: Configuring the command-line execution of the Disk Cleanup utility

  3. The Disk Cleanup dialog box appears. Select the options that specify the types of files to be removed and then click on OK.
  Note

You can create additional sageset profiles by specifying a different number. The Disk Cleanup utility will support up to 65,536 difference profiles. By creating two or more difference profiles, you can break up the cleanup process into small chunks and vary the scheduled execution of each profile.

Creating the Cleanup Script

Once the Disk Cleanup utility has been configured to support command-line execution, its execution can be scripted, as demonstrated by the following example.

'*************************************************************************
'Script Name: Script 13.3.vbs
'Author: Jerry Ford
'Created: 02/24/03
'Description: This script schedules the execution of the Cleanup utility
'at 20:00 on the first day of each month. This utility removes unnecessary
'files from the local disk drive.
'*************************************************************************


'Initialization Section

Option Explicit

Dim WshShl, FsoObject, LogFile

Set WshShl = WScript.CreateObject("WScript.Shell")

Set FsoObject = WScript.CreateObject("Scripting.FileSystemObject")


'Main Processing Section

CheckForCleanupLog()

PerformCleanup()

WScript.Quit()


'Procedure Section

'This procedure ensures that a cleanup.log file exists
Sub CheckForCleanupLog()
 If (FsoObject.FileExists("D:cleanup.log")) Then
 Set LogFile = FsoObject.OpenTextFile("D:cleanup.log", 8)
 LogFile.WriteLine "Cleanup process Started on " & Date & " at " & Time
 Else
 Set LogFile = FsoObject.OpenTextfile("D:cleanup.log", 2, "True")
 LogFile.WriteLine "Cleanup process Started on " & Date & " at " & Time
 End If
End Sub

'This procedure executes the cleanup utility
Sub PerformCleanup()
 WshShl.Run "C:WINDOWSSYSTEM32cleanmgr /sagerun:1"
End Sub

The Main Processing Section executes a subroutine called CheckForCleanupLog(), which begins by writing a message to a file named cleanup.log on the computer's D:drive. This log is used to keep a record of the script's execution, making it easy to later check and see the last time that the script ran. If cleanup.log does not exist, which will be the case the first time the script is run, it is created by the statement shown below.

Set LogFile = FsoObject.OpenTextFile("D:cleanup.log", 8)

This statement uses the FileSystemObject object's OpenTextFile() method to open the specified file so that it can be written to. The method is passed two parameters. The first parameter is the name and location of the file, and the second parameter is an integer that specifies how the file is to be opened. The following options are available.

  • ForReading. As specified by a value of 1
  • ForWriting. As specified by a value of 2
  • ForAppending. As specified by a value of 8

Once the file is opened, the subroutine executes the following statement:

LogFile.WriteLine "Cleanup process Started on " & Date & " at " & Time

This statement uses the FileSystemObject object's WriteLine() method to write an entire line of text to the file and then performs a line feed and carriage return.

Once a record of its execution has been recorded, the script processes the PerformCleanup() subroutine. This subroutine runs the Disk Cleanup utility as shown below. Note that this time the sagerun parameter is passed to the cleanmgr command-line utility and that the number of the previously configured profiles is provided.

WshShl.Run "C:WINDOWSSYSTEM32cleanmgr /sagerun:1"

Now that the script has been written, Tom can set up its scheduled execution, as described later in this chapter.

Examining the Manual Disk Defrag Process

Over time, all disk drives fill up. As free space becomes scarce, Windows is forced to begin breaking files up into smaller pieces that are then stored in different locations on the disk drive, wherever space permits. Because the files are not stored in contiguous disk space, it takes longer to read and write to them, thus slowing the computer's overall performance.

In order to limit the amount of fragmentation and keep computers running efficiently, Tom plans on developing a VBScript to automate the execution of the defrag process. Up to this point in time, employees at ABC, Inc. have been responsible for defragging their own hard disk drives using Windows XP's Disk Defragmenter utility. The Disk Defragmenter provides a command-line interface in the form of an executable called defrag.exe, thus providing the ability to execute it from the Windows command prompt.

Running the Disk Defragmenter Utility

In order to understand how the Disk Defragmenter utility works, it is helpful to manually run it at least once. The following procedure outlines the basic steps involved in performing this process.

  1. Click on Start/All Programs/Accessories/System Tools and then select Disk Defragmenter. The Disk Defragmenter console opens.
  2. Select a hard disk drive and click on Analyze to view the fragmentation status of the disk drive, as demonstrated in Figure 13.4.

    click to expand
    Figure 13.4: Analyzing the fragmentation status of the computer's hard disk drive

  3. Click on Defragment to initiate the defrag process.
  4. A pop-up dialog box will appear announcing when the defrag process has completed. Click on Close.

Running Defrag.exe

Using the defrag.exe command, you can defrag hard disk drives from the Windows command prompt. The defrag.exe command has the following syntax:

defrag <volume:> [/a] [/f] [/v]

Volume specifies the disk drive to be defragged. All remaining parameters are optional. The /a parameter displays an analysis of the specified drive's current fragmentation status. By default, defrag.exe requires 15 percent of free space on the disk drive in order to execute. The /f parameter provides the ability to force the execution of defrage.exe when less than 15 percent of free space is available. The /v parameter provides for verbose output.

  Note

Schedule the Disk Cleanup utility to run before defrag.exe to ensure that as much free space as possible is available.

The following procedure demonstrates how to run defrag.exe from the Windows command prompt.

  1. Click on Start/All Programs/Accessories and then Command Prompt. A Windows console opens and displays the Windows command prompt.
  2. Type defrag volume: /a and press Enter to view an analysis of the specified disk drive.
  3. Type defrag volume: /f and press Enter to defrag the specified disk drive.

Creating the Defrag Script

The following example demonstrates how to script the execution of the Disk Defragmenter utility.

'*************************************************************************
'Script Name: Script 13.2.vbs
'Author: Jerry Ford
'Created: 02/24/03
'Description: This script schedules the execution of the Windows defrag.exe
'at 22:00 on the first day of each month. This utility defrags disk drives.
'*************************************************************************


'Initialization Section

Option Explicit

Dim WshShl, FsoObject, LogFile

Set WshShl = WScript.CreateObject("WScript.Shell")

Set FsoObject = WScript.CreateObject("Scripting.FileSystemObject")


'Main Processing Section

CheckForDefragLog()

PerformDefrag()

WScript.Quit()


'Procedure Section

'This procedure ensures that a defrag.log file exists
Sub CheckForDefragLog()
 If (FsoObject.FileExists("D:defrag.log")) Then
 Set LogFile = FsoObject.OpenTextFile("D:defrag.log", 8)
 LogFile.WriteLine "Defrag.exe Started on " & Date & " at " & Time
 Else
 Set LogFile = FsoObject.OpenTextfile("D:defrag.log", 2, "True")
 LogFile.WriteLine "Defrag.exe Started on " & Date & " at " & Time
 End If
End Sub

'This procedure executes the defrage.exe command line utility
Sub PerformDefrag()
 WshShl.Run "c:WindowsSystem32defrag C: /f"
End Sub

The Main Processing Section starts things off by executing a subroutine called CheckForDefragLog(). This subroutine works exactly as the similarly named subroutine in the previous cleanup script by creating a log file if it does not already exist and writing a message that records the execution of the script.

Next the PerformDefrag() subroutine is executed. This subroutine executes the following statement:

WshShl.Run "c:WindowsSystem32defrag C: /f"

As you can see, the WshShell object's Run() method is used to run the defrag.exe command, which is passed the /f parameter to ensure its execution in the event that the hard disk drive is beginning to run low on space.


Scheduling Script Execution

Windows XP provides a background service called the Task Scheduler as a tool for setting up the scheduled execution of applications, utilities, commands, and scripts. By leveraging the capabilities of this service, you can schedule the execution of scripts at times that are more appropriate and convenient.

Windows XP provides two ways of interacting with the Task Scheduler, as outlined below.

  • at command. A command-line interface that can be used to create and manage scheduled tasks from the Windows command prompt.
  • Scheduled Tasks folder. A special folder that can be used to view, delete, and configure scheduled tasks. This folder also provides access to the Scheduled Task Wizard, which walks you through the process of manually setting up new scheduled tasks.
  Note

When you manually run a VBScript, it executes using the security privileges and permissions assigned to your user account. This allows VBScripts to perform any task that you are authorized to complete. However, scripts executed by the Task Scheduler service are run using a different set of security privileges and permissions. By default, the Task Scheduler service is configured to run using the Local System account. This account has limited security access and may not be able to run all of your VBScripts. One way around this dilemma is to associate a user account with a specific script when scheduling it, thus allowing the script to run using that account's security privileges and permissions.

  Tip

Another problem faced by scripts run by the Task Scheduler service is that they do not have access to the same execution environment that is available when run by you. For example, if you wrote a script that depends on the existence of a mapped network drive that you set up, the script will fail when run by the Task Scheduler service. Resources such as mapped network connections are associated with individual profiles, which are available to scripts only when run by a logged-on user. One way to work around this type of situation is to provide the script with the ability to set up its own temporary network drive connections, as provided by the WshNetwork object's MapNetworkDrive() method.

In order to understand how to schedule the execution of your VBScripts using the Scheduled Task Wizard or the at command, it is helpful to manually go through the process of using each tool. The next two sections briefly outline the steps involved in manually scheduling the execution of a VBScript using both of these options.

Working with the Scheduled Task Wizard

One of the resources found on the Scheduled Tasks folder is a link to the Scheduled Task Wizard. This wizard guides you through the process of creating new scheduled tasks, as demonstrated by the following procedure.

  1. Click on Start/All Programs/Accessories/System Tools and then Scheduled Tasks. The Scheduled Tasks folder opens.
  2. Double-click on the Add Scheduled Task icon. The Scheduled Task Wizard appears.
  3. Click on Next.
  4. A list of Windows XP applications is displayed. Click on Browse, locate your script, and click on Open.
  5. Type a descriptive name for the scheduled task, select a time frame for its execution, as shown in Figure 13.5, and click on Next.

    click to expand
    Figure 13.5: Specify an execution schedule for your script

  6. Specify additional execution time frame options, as demonstrated in Figure 13.6, and click on Next. The specific time frame options shown will vary depending on the type of time frame previously selected.

    click to expand
    Figure 13.6: Fine-tuning a script's execution schedule

  7. Next, you are prompted to specify an optional user name and password under which the scheduled task can be run, as shown in Figure 13.7. Click on Next.

    click to expand
    Figure 13.7: Specify a user name and password for scripts that require additional security privileges and permissions in order to execute

      Note

    You may want to consider creating a special user account with administrative privileges and a nonexpiring password to support the execution of scripts that require greater security access than that provided by the Local System account.

  8. Click on Finish. The task that you just created will now be visible on the Scheduled Tasks folder.

Using the Windows at Command

The at command is a command-line interface for working with the Task Scheduler service. Its syntax is shown below.

at [\ComputerName] [[id] [/delete] | /delete [/yes]]
at [\ComputerName] time [/interactive] [/every:date[,...] | /next:date[,...]] com-
mand

ComputerName is the name of the computer where the task is to execute. If omitted, the task will execute on the computer where it is defined. The rest of the parameters supported by the at command are outlined below.

  • id. Specifies the ID number assigned to an existing scheduled task
  • /delete. Terminates the specified scheduled task
  • /yes. Requires a confirmation before performing the specified action
  • Time. Specifies the task's execution time using a 24-hour clock (hh:mm)
  • /interactive. Allows interaction with the logged-on user
  • /every:date[,…]. Specifies the tasks execution schedule based on specified days of the week or month; valid dates include M, T, W, Th, F, S, Su or 1–31 and are separated by commas
  • /next:date[,…]. Sets the task to execute on the next occurrence of the specified date
  • Command. Identifies the task, application, or script to be scheduled

You work with the at command from the Windows command prompt. To view all currently scheduled tasks, type the at command and press the Enter key, as demonstrated below.

C:>at
Status ID Day Time Command Line
-------------------------------------------------------------------------
 1 Each 1 8:00 PM c:Cleanup.vbs
 2 Each 1 10:00 PM c:Defrag.vbs

As you can see, there are currently two scheduled tasks. The first task has been assigned an ID of 1 and the second task has an ID of 2. Both tasks are scheduled to run on the first day of each month, the first at 8 P.M. and the second at 10 P.M.

The following command demonstrates how to set up a third scheduled task that executes every Monday, Wednesday, and Friday at 11 P.M.

at 23:00 /every:M, W, F cmd /c "Script 13.1.vbs"

If you reissued the at command, you would see that the Task Scheduler is now managing three tasks, as shown below.

C:>at
Status ID Day Time Command Line
-------------------------------------------------------------------------
 1 Each 1 8:00 PM c:Cleanup.vbs
 2 Each 1 10:00 PM c:Defrag.vbs
 3 Each M W F 11:00 PM cmd /c "Script 13.1.vbs"

The following statement demonstrates how to schedule the execution of a task on a different network computer.

\Desktop10 23:00 /every:M, W, F cmd /c "Script 13.1.vbs"

The at command also provides the ability to delete scheduled tasks by specifying the task's ID assignment, as demonstrated below.

at 3 /delete


Creating a Scheduler Script

Once you understand the basic elements of task scheduling, you can develop VBScripts that can interact with and manage the task execution. To accomplish this, you will need to use the WshShell object's Run() method and the Windows at command.

The following example shows the script that Tom developed to schedule the execution of the cleanup and defrag VBScripts.

'*************************************************************************
'Script Name: Script 13.1.vbs
'Author: Jerry Ford
'Created: 02/24/03
'Description: This script schedules the execution of the Windows
'Cleanup.exe utility.
'*************************************************************************


'Initialization Section

Option Explicit

Dim WshShl

'Instantiate the WshShell object
Set WshShl = WScript.CreateObject("WScript.Shell")

'Main Processing Section

ScheduleScripts()

WScript.Quit()


'Procedure Section

'This procedure schedules the execution of other VBScripts
Sub ScheduleScripts()
 'Use the WshShell object's Run() method to run the at command
 WshShl.Run "at 20:00 /every:1 c:Cleanup.vbs"
 WshShl.Run "at 22:00 /every:1 c:Defrag.vbs"
End Sub

As you can see, the ScheduleScripts() subroutine is responsible for scheduling the execution of both scripts.

Configuring the Task Scheduler Service

At this point, Tom has written three VBScripts. One is to automate the execution of the Disk Cleanup utility. Another is to run the defrag.exe, and a third script is to schedule the first two scripts. In addition, Tom knows that in order to run the Disk Cleanup script, he must first configure a sageset profile for it on each computer.

One last pair of tasks still remains. The default Local System account used by the Task Scheduler service lacks sufficient access privileges and permissions to run either the Disk Cleanup or Disk Defragmenter scripts. In order to run the Disk Defragmenter VBScript, Tom will have to configure the task that runs the script to use a user account with sufficient security privileges and permissions. This account will be named MaintTasks. Its creation will be automated in Chapter 15, "Creating Administrator Accounts."

The Disk Cleanup script has a slightly different requirement. Although it does not require administrative privileges in order to run, it must be associated with a specific user account in order to perform certain tasks, such as emptying the user's Recycle Bin.

The following procedure outlines the steps required to associate a user account with an existing scheduled task.

  1. Click on Start/All Programs/Accessories/System Tools and then Scheduled Tasks. The Scheduled Tasks folder appears.
  2. Double-click on the schedule to open its properties dialog box.
  3. Type the name of the account to be associated with the tasks in the Run as field, as shown in Figure 13.8.

    click to expand
    Figure 13.8: Type the name of a user account with sufficient privileges to run the script

  4. Click on Set password, specify the password associated with the user account, and then click on OK.
  5. Click on OK to close the Scheduled Task Properties dialog box.
  Note

Tom will be able to configure and set up both the Disk Defragmenter and Disk Cleanup tasks while setting up the computers in the build area. However, he will have to wait until he delivers the desktops to the users in order to finish configuring the Disk Cleanup task, because he needs the users to log in and type their passwords. Also, unless the users have an account whose password never expires, the users will have to repeat this process whenever they change their passwords. Otherwise, the scheduled tasks will fail the next time the users change their passwords.


Summary

In this chapter, you learned more about the WshShell object's Run() method. You learned how to use it to create scripts that interact with the Disk Cleanup and Disk Defragmenter utilities, as well as the Task Scheduler service. You also learned how to configure individual scheduled tasks so that they could run using the security privileges and permissions of user accounts other than the Local System account.






Microsoft VBScript Professional Projects
Microsoft VBScript Professional Projects
ISBN: 1592000568
EAN: 2147483647
Year: 2005
Pages: 366
Simiral book on Amazon

Flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net