Windows Task Scheduler is a well-known GUI utility tool for automating recurring tasks. Many people don't realize that Task Scheduler does more than schedule scripts, programs, and documents to run at specific times. You can also use the tool to display message boxes and send out email messages. What's more, you can schedule tasks to run based on a number of event triggers, including startup, logon, and even custom events. This article will highlight these event triggers and explain how to get the most from the often overlooked Task Scheduler.

Times Have Changed

There was a time when Task Scheduler was thought to be quite basic and unconfigurable, compared with the cron jobs of UNIX and Linux systems. These days, Task Scheduler is both configurable and capable. So before looking at third-party utilities, determine whether Task Scheduler can already do what you want.

For the purposes of this article, I'll focus on the Windows Server 2008 OS. Although other OSs, such as Windows 7, might differ slightly, Task Scheduler should function in much the same way as described here.

Task Scheduler Basics

Just as you must learn the rules before you can break them, you must become familiar with the basic operation of Task Scheduler before delving into its more esoteric uses. It won't take long.

To open Task Scheduler, you need administrator access. You can use the Control Panel, the Manage command, or taskschd.msc for this task. Figure 1 shows what Task Scheduler looks like when it first opens.

Figure 1: Task Scheduler
Figure 1: Task Scheduler 

Creating a New Task

There are three ways to create a new task:

  • Create a basic task
  • Create a non-basic task
  • Import a task

The Create Basic Task menu item will do the job for those tasks that don't require advanced settings, such as task time limits or number of repetitions. Here's how to set up a scheduled task to launch Microsoft Outlook at startup:

1. Click Action from the menu bar, and then click Create Basic Task.

2. Type a name for the task (we'll use Launch Outlook in this example) and an optional description, and then click Next.

3. You now have the option of scheduling the task to run

  • on a calendar-based interval, such as Daily, Weekly, Monthly, or One Time only
  • at common recurring events, such as when the computer starts or when you log on
  • on specific events, such as when a specific event is logged

Select the Triggers tab and then click New.

4. From the Begin the task drop-down list, choose At log on.

5. Choose 1 minute or 2 minutes from the Delay task for drop-down list, to let your PC complete its startup tasks. (I'll explain more about the benefits of this decision later.)

6. Make sure that the Enabled check box is checked, and then click OK to close the New Trigger dialog box.

7. The Action screen, which Figure 2 shows, gives you three actions to choose from:

  • Start a program
  • Send an e-mail
  • Display a message

Select Start a program and then click Next.

Figure 2: Starting a program action
Figure 2: Starting a program action 

8. On the Start a Program screen, click the Browse button to locate outlook.exe. In Windows 7, this file will be in one of the following locations:

  • For 64-bit Windows -- C:\program files\microsoft office\office14\
  • For 32-bit Windows -- C:\program files (x86)\microsoft office\office14\

9. Click Next to proceed to the Finish screen.

10. The Finish screen shows the task summary and a check box to display more options after the task is created. Click Finish to create the task, which then is added to the Active Tasks list.

Running the Task on Demand

From the Active Tasks window, you can double-click any scheduled task to open its properties. Any task can be run on demand so that you can manually run it for convenience, testing, or debugging (although the latter can be built in to some extent). Here's how to run a task on demand:

1. In Task Scheduler's central pane, in the Active Tasks list, double-click an item to bring up its properties. The right-hand Actions pane shows options for the Selected Item, as Figure 3 shows.

Figure 3: Run command
Figure 3: Run command 

2. Click Run to start the task. You can click the Stop button to abort the process.

Modifying an Existing Task

You can disable a task from its Selected Item menu. To permanently remove the selected task, use the Delete button.

The center pane displays the properties for the selected task. However, these properties are read-only. To gain access to this information in an editable form, click Properties under Selected Item. This action opens a Properties window that provides more fine-grained control to the task's triggers, actions, conditions, and settings, as Figure 4 shows.

Figure 4: Task Settings tab
Figure 4: Task Settings tab 

The remainder of this article focuses on these settings and how to use them to set up more intricate scheduled tasks:

  • Schedule a delayed startup script
  • Schedule shutdown after the server has been idle for a certain length of time
  • Execute a Windows PowerShell script
  • Schedule a task based on a specific event
  • Test your tasks
  • Fine-tune an event-triggered task via the Task Scheduler Developer API

How to Schedule a Delayed Startup Script

Delaying the launch of a startup script or application so that the server can finish booting is usually a good idea. There's an option for that in the Advanced Settings section of the New Trigger dialog box.

Now, you might be wondering why you would need such a scheduled task trigger when the Startup folder offers the same functionality. There are a couple good reasons. First, boot-up and logon already place a sizeable load on your computer. Starting processes directly at logon places an additional burden on your computer and can render it unresponsive for quite some time. Using a delayed scheduled task allows you to wait until the computer has finished its business. The second (and more important) reason is that scheduled tasks can be run with more rights than items in the Startup folder, which run under the logged-on user's credentials. User Account Control (UAC) requires an elevated token when attempting to perform certain tasks:

  • Backing up and restoring data
  • Changing group memberships
  • Setting user and group security
  • Creating administrative scripts
  • Creating logon scripts
  • Creating user and group accounts
  • Deploying and upgrading software

Let's create a task to perform a backup after logon. Because we want to configure advanced settings, we'll create a regular task rather than a basic one. The steps are much the same as the ones we used to create our Launch Outlook task, except that you'll start with the Create Task action (instead of Create Basic Task).

On the Create Task dialog box, which Figure 5 shows, you'll set the account and privileges that the task will use. With UAC, users of the admin group have two tokens. The filtered token represents standard user rights. When you click an executable and select Run as administrator, the full token -- which contains admin rights -- is used.

Figure 5: Task Security options
Figure 5: Task Security options 

Likewise, when you select Run with highest privileges in the Security options area of the Create Task dialog box, the full token is used. This setting works only when the user is in the admin group, because only those users have two tokens. To run a program with admin rights from a standard user account, you must select Run whether user is logged on or not and then select a user that is a member of the admin group.

Enter the username in the form computername\username -- for instance, server01\administrator. Enter the password as well.

On the Triggers tab, click the New button to open the New Trigger dialog box, which Figure 6 shows. The Delay task for drop-down list gives you six choices, ranging from 30 seconds to 1 day. Unfortunately, you can't define your own delay time; you must make do with the selection that is closest to what you're looking for. In our case, one minute should suffice. Click OK to close the dialog box.

Figure 6: New Trigger dialog box
Figure 6: New Trigger dialog box 

On the Actions tab, click the New button. Click the Browse button and locate C:\program files\cwrsync\cwrsync.cmd in the New Action dialog box. (Note that several actions can be associated with the same task.) Click Next to proceed to the Finish screen, and then click Finish to create the task.

How to Schedule Server Shutdown

Here's a scheduled task that uses the Windows Sysinternals PsShutdown utility to shut down a server that has been idle for a certain amount of time. This is a great way to conserve system resources while not in use.

1. Create a new task, as you did in the previous section.

2. In the Program/script text box, enter the following command:

C:\Adminutils\PsShutdown.exe

3. Enter the following in the Add arguments text box:

-s -f -c -t 10

4. You can choose to delay the task so that it runs only after the PC has been idle for a certain amount of time. Select 30 minutes from the Delay task for drop-down box.

How to Execute a PowerShell Script as a Scheduled Task

PowerShell is the most powerful administrative tool in Windows, so it's only natural that Windows admins would want to use Task Scheduler to automate their PowerShell scripts. It turns out that these two tools are a perfect match.

You’ll need to set the execution policy to execute PowerShell scripts. To execute a PowerShell command directly, specify the command parameter, and then use the ampersand (&), a pair of curly braces ({}), and the PowerShell command that you want to run:

powershell -NoLogo -executionpolicy RemoteSigned -command &{get-process>>C:\fso\mytestprocesses.txt}

I recommend using the Run command, as Figure 7 shows, to test your command syntax prior to scheduling your task.

Figure 7: Running a PowerShell script
Figure 7: Running a PowerShell script 

To execute the script, simply replace the -command flag with -file flag:

powershell.exe -noprofile -executionpolicy RemoteSigned -file %public%\myscript.ps1

Note that you can include environment variables in the paths by delimiting them with percentage characters (%), as with any Cmd.exe command.

How to Schedule a Task Based on an Event

Windows events are perhaps the most complicated of all the task triggers, one reason being that Windows events encompass a whole range of potential triggers. To open the Event Viewer, which is part of the Server 2008 Administrative Tools, click Start, Control Panel, System and Security, Event Viewer.

The Event Viewer, which Figure 8 shows, displays information about hardware, software, and system problems.

Figure 8: Event Viewer
Figure 8: Event Viewer 

Events are categorized by type:

  • Error -- a significant problem, such as loss of data or functionality (e.g., logged if a service fails to load during startup)
  • Warning -- not necessarily significant, but might indicate a future problem (e.g., logged when disk space is low)
  • Information -- information about the successful operation of an application, driver, or service (e.g., logged when a network driver loads successfully)
  • Success Audit -- a successful audited security access attempt (e.g., a user's successful attempt to log on to the system)
  • Failure Audit -- a failed audited security access attempt (e.g., a user's failed attempt to access a network drive)

You can bind an event to any of these event types by right-clicking the event in Event Viewer and selecting Attach Task To This Event in the pop-up menu. This action launches the Create Basic Task Wizard, in which you can configure task options.

Fine-Tuning an Event-Triggered Task

Since Windows Vista, Task Scheduler has contained new interfaces for C++ developers, scripting objects for VBScript developers, and a schema for defining tasks in XML. These avenues offer more flexibility than ever before for both task creation and fine-tuning.

Case in point: Suppose you want to run a task when a user is added to a specific domain local group. You'll need to hook into Audit system events, which relate to system security. Each event has a code to help identify it:

  • 4730 -- A security-enabled global group was deleted.
  • 4731 -- A security-enabled local group was created.
  • 4732 -- A member was added to a security-enabled local group.
  • 4733 -- A member was removed from a security-enabled local group.
  • 4734 -- A security-enabled local group was deleted.
  • 4735 -- A security-enabled local group was changed.
  • 4737 -- A security-enabled global group was changed.

Open the Create Basic Task Wizard, and then follow these steps to schedule the task:

1. Select When a specific event is logged on the Task Trigger screen.

2. Code 4732 identifies the addition of a member to a security-enabled local group. Enter that code in the Event ID field on the When a Specific Event Is Logged screen, as Figure 9 shows.

Figure 9: Logged event trigger details
Figure 9: Logged event trigger details 

3. To find the Log and Source for an event, open Event Viewer; in the left pane, select Windows Logs, Security and open the Properties dialog box. The General tab contains both the Log Name and Source fields. The latter is liable to be truncated, but when you position the mouse pointer over the name, a tooltip appears with the full text, as Figure 10 shows.

Figure 10: Determining Log and Source
Figure 10: Determining Log and Source 

4. On the Action screen, select Display a message.

5. Click Finish to create the new task.

By default, a message will be displayed every time a new local group is added. If you want to target a specific group, you need to edit the XML. To do so, you first need to export the task:

1. Double-click the new task in the Task Scheduler Active Tasks list, as Figure 11 shows.

Figure 11: Local Group Added task
Figure 11: Local Group Added task 

2. Click Export in the Selected Item list, as Figure 12 shows, and save the XML file to a location of your choosing.

Figure 12: Exporting XML
Figure 12: Exporting XML 

3. Open the XML source in your favorite text editor. You'll see code that looks like Listing 1. Add the TargetUserName code to the EventTrigger section, as callout A shows.

Now the scheduled task will respond to event 4732 only when the TargetUserName (i.e., the Local Security Group Name) is SECURE NETWORKS.

You can also filter on certain users, by using MemberName instead of TargetUserName. You can see more details about how the filter works in the XML view of an event. Simply open the event properties, go to the Details tab, and choose the XML View option, as Figure 13 shows. The full code is shown in Figure 14. You can use the data from this event in the action. To allow the EventData parameter to pass the MemberName to the action, you need to add the code at callout B in Listing 1 to the exported XML file, just before the line.

Figure 13: Local Group Added task in XML view
Figure 13: Local Group Added task in XML view 

You can now use the $(MemberName) variable in an action. The following code displays this variable in the message box:





Local Group Added

The $(MemberName) local group has been added.




When you've modified and saved the XML, delete the original task from Task Scheduler. You can then import the modified XML. In the right pane of the Task Scheduler window, under Actions, click Import Task. Your custom task is now ready to go!

More Than Capable

Through the manipulation of triggers, actions, and events, Server 2008 Task Scheduler offers more than ample flexibility to manage the most mundane of tasks to the most intricate. Moreover, most properties are readily available via the Task Scheduler Wizard. You can achieve more fine-grained control through the Scheduled Task API and XML schema.

Listing 1: XML Code to Trigger Event on Specific Security Group Name and to Pass MemberName to Task

Action



 

    true

   

       

           

               

           


       


   


# BEGIN CALLOUT B

   

      Event/EventData/Data[@Name='MemberName']

   


# END CALLOUT B