TABLE 9-1 Schedule Types for Schtasks /Create
SCHEDULE TYPE
DESCRIPTION
MODIFIER VALUES
MINUTE
Task runs at a specified interval in minutes. By default, tasks run once a minute.
/mo 1-1439; the number of minutes between each run of the task. The default modifier is 1.
HOURLY
Task runs at a specified interval in hours. By default, tasks run once an hour.
/mo 1-23; the number of hours between each run of the task. The default modifier is 1.
DAILY
Task runs every day or every n days. By default, tasks run once a day.
/mo 1-365; the number of days between each run of the task. The default modifier is 1.
WEEKLY
Task runs every week or every n weeks, on designated days. By default, tasks run once a week on Mondays.
/mo 1-52; the number of weeks between each run of the task.
Optionally, use /d to specify the days of the week to run. Use MON, TUE, WED, THU, FRI, SAT, and SUN to specify days. Use * for every day of the week.
MONTHLY
Task runs every month or every n months on designated days. By default, tasks run the first day of every month.
/mo 1-12; the number of months between each run of the task.
Optionally, use /d MON-SUN; sets day of the week to run during the month. Use * to have the task run every day.
Second monthly variant for specific day of month. Use /mo and /m, or /m and /d.
/mo LASTDAY; last day of month.
/m JAN, FEB, . . ., DEC; sets the month(s).
/d 1-31; day of month.
Third monthly variant for specific week of the month.
/mo FIRST | SECOND | THIRD | FOURTH | LAST; sets week of month.
/d MON-SUN; sets day of week.
/m JAN, FEB, . . ., DEC; sets month(s).
ONCE
Task runs once at a specified date and time.
—
ONEVENT
Tasks run when a specified event or events occur in a specified event log.
/mo XPathString where XPath-String is the XPath event query string that identifies the event on which the scheduled task is triggered.
ONSTART
Task runs whenever the system starts.
—
ONLOGON
Task runs whenever a user logs on.
—
ONIDLE
Task runs whenever the system is idle for a specified period of time.
/i 1-999; the number of minutes the system has to be idle before the task starts.
To see how you can use Schtasks /Create, consider the following examples:
Task runs once immediately and then doesn’t run again:
schtasks /create /tn "SysChecks" /tr c:\scripts\sch.bat /sc once
Task runs when the system starts:
schtasks /create /tn "SysChecks" /tr c:\scripts\sch.bat /sc onstart
Task runs whenever the system is idle for more than 10 minutes:
schtasks /create /tn "SysChecks" /tr c:\scripts\sch.bat /sc
onidle /i 10
Task runs every 15 minutes on the local computer:
schtasks /create /tn "SysChecks" /tr c:\scripts\sch.bat /sc minute
/mo 15
Task runs every five hours on the local computer:
schtasks /create /tn "SysChecks" /tr c:\scripts\sch.bat /sc hourly
/mo 5
Task runs every two days on the local computer:
schtasks /create /tn "SysChecks" /tr c:\scripts\sch.bat /sc daily /mo 2
Task runs every two weeks on Monday (the default run day):
schtasks /create /tn "SysChecks" /tr c:\scripts\sch.bat /sc weekly /mo 2
Task runs every week on Monday and Friday:
schtasks /create /tn "SysChecks" /tr c:\scripts\sch.bat /sc weekly /d mon,fri
Task runs on the first day of every month:
schtasks /create /tn "SysChecks" /tr c:\scripts\sch.bat /sc monthly
Task runs on the fifth day of every other month:
schtasks /create /tn "SysChecks" /tr c:\scripts\sch.bat /sc monthly /mo 2 /d 5
Task runs the last day of every month:
schtasks /create /tn "SysChecks" /tr c:\scripts\sysch.bat
/sc monthly./mo lastday
Task runs the first Monday of April, August, and December:
schtasks /create /tn "SysChecks" /tr c:\scripts\sysch.bat /sc
monthly /mo first /d mon /m apr,aug,dec
When the path of the specified task includes a space, enclose the file path in double quotation marks as shown in the following example:
schtasks /create /tn "SysChecks" /tr "c:\My Scripts\sch.bat" /sc onstart
If you do not enclose the file path in quotation marks, an error will occur when Schtasks attempts to run the task. Further, if you want to pass arguments to a program, utility, or script, simply follow the Task To Run file path with the arguments you want to use. Any argument that contains spaces should be enclosed in quotation marks so that it is properly interpreted as a single argument rather than multiple arguments. Here are examples:
schtasks /create /tn "SysChecks" /tr c:\scripts\sch.bat 1 Y LAST
/sc onstart
schtasks /create /tn "SysChecks" /tr "c:\My Scripts\sch.bat" Y N
/sc onstart
schtasks /create /tn "SysChecks" /tr "c:\My Scripts\sch.bat" "Full Checks"
You can also schedule tasks for remote computers as well as tasks that should run with different user permissions. The key detail to remember when scheduling tasks on remote computers is that the computer you are using should be in the same domain as the remote computer or in a domain that the remote computer trusts. To do this, you must use the expanded syntax, which includes the following parameters:
/s Computer /u [Domain\]User [/p Password]
where Computer is the remote computer name or IP address, Domain is the optional domain name in which the user account is located, User is the name of the user account whose permissions you want to use, and Password is the optional password for the user account. If you don’t specify the domain, the current domain is assumed. If you don’t provide the account password, you are prompted for the password.
To see how you can add the computer and user information to the syntax, consider the following examples:
Use the account imaginedlands\wrstanek when creating the task on the local computer:
schtasks /create /tn "SysChecks" /tr c:\scripts\sch.bat /sc onstart
/u imaginedlands\wrstanek /p RoverSays
Set the remote computer as mailer01 and the account to use as adatum\wrstanek:
schtasks /create /tn "SysChecks" /tr c:\scripts\sch.bat /sc onstart
/s mailer01 /u imaginedlands\wrstanek /p RoverSays
Using the /Ru and /Rp parameters, you can specify the credentials for the user account under which the task should run. If you want a task to run only when a specific user is logged on, use the optional /It parameter, which specifies that the task should run interactively and only when the user who owns the task is logged on. With tasks that work only with local resources, you can use the /Np parameter to specify that no password should be saved with a user’s credentials. When you don’t allow Task Scheduler to save a password, the task only has access to local resources and runs non-interactively as the specified user.
Tasks run with standard user privileges by default. If you want a task to run with the highest privileges of the specified user, such as may be necessary for administrative tasks, you can set the /Rl parameter to Highest rather than the default value Limited.
To see how you can add alternate credentials and privileges to the syntax, consider the following examples:
Configure the task to run using the credentials of imaginedlands\thomasv:
schtasks /create /tn "CleanUp" /tr c:\scripts\cleanup.bat /sc onlogon /ru imaginedlands\thomasv /rp DingoE
Set the remote computer as server18, the account to use for creating the task as imaginedlands\wrstanek, and configure the task to run using the credentials of imaginedlands\thomasv:
schtasks /create /tn "CleanUp" /tr c:\scripts\cleanup.bat /sc onlogon /s server18 /u imaginedlands\wrstanek /p RoverSays /ru imaginedlands\thomasv /rp DingoE
Run the task without saving the user password on server18 using the account imaginedlands\wrstanek:
schtasks /create /tn "CleanUp" /tr c:\scripts\cleanup.bat /sc onlogon /s server18 /u imaginedlands\wrstanek /np
Run the task with the highest privileges:
schtasks /create /tn "SysChecks" /tr c:\scripts\sch.bat /sc onlogon /rl highest
Finally, if desired, you can add specific start times and dates, as well as end times and dates, using the following values:
TIP If you specify an end date or time, you can also specify the / Z parameter, which tells Task Scheduler to delete the task upon completion of its schedule.
To see how you can use specific start times and dates, as well as end times and dates, consider the following examples:
Start the hourly task at midnight:
schtasks /create /tn "SysChecks" /tr c:\scripts\sch.bat /sc hourly /st 00:00
Start the hourly task at 3:00 A.M. and stop it at 7:00 A.M.:
schtasks /create /tn "SysChecks" /tr c:\scripts\sch.bat /sc hourly /st 03:00 /et 07:00
Start the weekly task at 3:00 A.M. on February 20, 2015:
schtasks /create /tn "SysChecks" /tr c:\scripts\sch.bat /sc weekly /st 03:00 /sd 02/20/2015
Start the weekly task at 3:00 A.M. on February 20, 2015 and end at 2:59 A.M. on March 15, 2015:
schtasks /create /tn "SysChecks" /tr c:\scripts\sch.bat /sc weekly /st 03:00 /sd 02/20/2015 /et 02:59 /ed 03/15/2015
NOTE Date and time formats are determined by the Regional And Language Options settings used by the computer. In these examples, the date format preference is English (United States).
With Schtasks /Create, you can create scheduled tasks that start when the operating system or a Windows component writes specific events or types of events to one of the event logs. The basic syntax for event-triggered tasks is as follows:
schtasks /create /tn TaskName /tr TaskToRun /sc ONEVENT
/ec LogName /MO EventString
where TaskName sets the task name string, TaskToRun specifies the file path to the program, command-line utility, or script that you want to run, LogName sets the name of the event log to monitor, and EventString sets the XPath event query string that identifies the event or events on which the scheduled task is triggered.
Using /Sc ONEVENT with the schedule task definition is what schedules the task to trigger based on an event. With the /Ec parameter, you specify the command-line compatible name of the event log to monitor. You can use the Wevtutil el command to list all available event logs on a computer in a command-line compatible format. With the /Mo parameter, you define the query by specifying the XPath event query string.
You don’t have to try to create query strings from scratch. Instead, use Event Viewer to create a filter that identifies the exact event or events you want to monitor. Then, copy the related XPath query to Notepad or any standard text editor. Once you’ve copied the query to Notepad, you should save the query so that you have the original settings and then try to extract the necessary event query string. Generally, the event query string you need is the text between the begin <Select> tag and the end </Select> tag within the Query element. Consider the following example:
<QueryList>
<Query Id="0" Path="Application">
<Select Path="Application">*[System[(Level=1 or Level=2 or Level=3)]]</Select>
</Query>
</QueryList>
In this example, the event query string is:
*[System[(Level=1 or Level=2 or Level=3)]]
This query string creates a filter that looks for critical, warning, and error events in the applicable event log. The following example uses this query to create a scheduled task called Track Application Issues to run Event Viewer whenever critical, warning, and error events are written to the applicable event log:
schtasks /create /tn "Track Application Issues" /tr wevtvwr.msc /sc ONEVENT
/ec Application /MO "*[System[(Level=1 or Level=2 or Level=3)]]"
Note that because the task name and the query string contain spaces, they are enclosed in double quotation marks. While this type of query string is probably too broad, it is a good example of what a query string looks like. A better query is one that identifies a specific event by its event identifier. The event query string syntax for specifying a single event identifier is:
*[System[(EventID=EventNumber)]]
where EventNumber is the identifier number of the event to monitor. In the following example, you create a scheduled task that runs whenever event id 3210 is written to the System log:
schtasks /create /tn "Computer Authentication Issues" /tr wevtvwr.msc
/sc ONEVENT /ec System /MO "*[System[(EventID=3210)]]"
REAL WORLD Events with Event ID 3210 are written to the System log when a computer is unable to authenticate in the domain. This error can occur because the computer’s password needs to be reset. This error can also occur if another computer on the network has the same name.
By extending the query string with or statements, you can enter multiple event identifiers. The extended syntax looks like this:
*[System[(EventID=EventNumber or EventID=EventNumber or ...)]]
In the following example, you create a scheduled task that runs whenever event id 3210 or event id 5722 are written to the System log:
schtasks /create /tn "Computer Authentication Issues" /tr wevtvwr.msc
/sc ONEVENT /ec System /MO "*[System[(EventID=3210 or EventID=5722)]]"
REAL WORLD Events with Event ID 5722 are written to the System log when a computer is denied access to a resource. This error can occur because the computer account has been disabled or deleted.
You use Schtasks /Change to change key parameters associated with scheduled tasks. The basic syntax of Schtasks /Change is
schtasks /change /tn TaskName ParametersToChange
where TaskName is the name of the task you want to change and ParametersToChange are the parameters you want to change. Parameters you can work with include the following:
To see how you can change tasks, consider the following examples:
Change the script that is run:
schtasks /change /tn "SysChecks" /tr c:\scripts\systemchecks.bat
Change the runas user and password:
schtasks /change /tn "SysChecks" /ru adatum\hthomas /rp gophers
Change task to start weekly at 7:00 A.M. on March 1, 2015 and end at 6:59 A.M. on March 30, 2015:
schtasks /change /tn "SysChecks" /st 07:00 /sd 03/01/2009 /et 06:59 /ed 03/30/2015
NOTE As mentioned previously, date and time formats are determined by the Regional And Language Options settings used by the computer. Here, the date format is English (United States).
When you change a task, Schtasks displays a message that states whether the changes succeeded or failed, such as:
SUCCESS: The parameters of the scheduled task "SysChecks" have been changed.
If you are working with a remote computer or aren’t logged in with a user account that has permission to change the task, you can specify the computer and account information as necessary. The syntax is
schtasks /change /tn TaskName /s Computer /u [Domain\]User
[/p Password]
where Computer is the remote computer name or IP address, Domain is the optional domain name in which the user account is located, User is the name of the user account whose permissions you want to use, and Password is the optional password for the user account. If you don’t specify the domain, the current domain is assumed. If you don’t provide the account password, you are prompted for the password.
In the following example, the remote computer is mailer01 and the user account that has authority to change the SysChecks task is wrstanek’s Imaginedlands domain account:
schtasks /change /tn "SysChecks" /tr c:\scripts\systemchecks.bat
/s mailer01 /u imaginedlands\wrstanek
Because a password isn’t specified, Schtasks will prompt for one.
You can also quickly enable or disable tasks by name. Use the following syntax to enable tasks:
schtasks /change /tn TaskName /enable
Use this syntax to disable tasks:
schtasks /change /tn TaskName /disable
where TaskName is the name of the task you want to enable or disable, such as:
schtasks /change /tn "SysChecks" /disable
You can quickly determine what tasks are configured on a computer by typing schtasks /query at the command prompt and, as necessary for a remote computer, you can specify the computer and the account information needed to access the computer using the following form:
schtasks /query /s Computer /u [Domain\]User [/p Password]
where Computer is the remote computer name or IP address, Domain is the optional domain name in which the user account is located, User is the name of the user account with appropriate access permissions on the remote computer, and Password is the optional password for the designated user account.
In the following example, the remote computer is mailer01 and the user account is wrstanek’s imaginedlands domain account:
schtasks /query /s mailer01 /u imaginedlands\wrstanek
Because a password isn’t specified, Schtasks will prompt for one.
The basic output of Schtasks /Query is in table format and provides TaskName, Next Run Time, and Status columns. You can also format the output as a list or lines of comma-separated values using /Fo List or /Fo Csv, respectively. The list output works best with the /V (verbose) parameter, which provides complete details on all task properties and which you can use as shown in the following example:
schtasks /query /s mailer01 /u imaginedlands\wrstanek /fo list /v
Another useful parameter is /Nh, which specifies that table-formatted or CSV-formatted output should not have headings.
TIP You may wonder why you’d want to use the various formats. It’s a good question. I recommend using the verbose list format (/Fo List /V) when you want to see all details about tasks configured on a system and when you are troubleshooting, and I recommend using comma-separated values when you want to store the output in a file that may later be exported to a spreadsheet or flat-file database. Remember that you can redirect the output of Schtasks to a file using output redirection (> or >>).
The /Xml parameter is one of the parameters we haven’t talked about for Schtasks /Create. When you use this parameter with Schtasks /Create, you can specify the XML configuration file that defines the new task you are creating. The basic syntax is:
schtasks /create /tn TaskName /xml XmlFile
where TaskName is the name of the task to create and XmlFile specifies the name or full file path to the XML configuration file containing the task settings, such as:
schtasks /create /tn "Housekeeping Task" /xml housekeepingtask.xml
As at other times when you are creating tasks, you can use the /S parameter to specify a remote computer, /U to specify the user context for creating the task, and /P to specify the user password. Although the XML configuration file for a task can define alternate credentials under which the task runs, you can also specify the alternate credentials using the /Ru and /Rp parameters.
Rather than having the actual user password in the file, you may want to set the password to blank or “*”. If you do this, you can specify the required password when you create the task using the /Rp parameter.
The following is an XML configuration file that defines a scheduled task and its settings:
<?xml version="1.0" encoding="UTF-16"?>
<Task version="1.2" xmlns="http://schemas.microsoft.com/windows/2015/02/mit/task">
<RegistrationInfo>
<Date>2015-10-01T18:10:12</Date>
<Author>WilliamS</Author>
</RegistrationInfo>
<Triggers>
<EventTrigger>
<StartBoundary>2015-10-01T18:10:00</StartBoundary>
<Enabled>true</Enabled>
<Subscription><QueryList><Query><Select Path='system'>*[System[(Level=1 or Level=2 or Level=3)]
]</Select></Query></QueryList></Subscription>
</EventTrigger>
</Triggers>
<Settings>
<IdleSettings>
<Duration>PT10M</Duration>
<WaitTimeout>PT1H</WaitTimeout>
<StopOnIdleEnd>true</StopOnIdleEnd>
<RestartOnIdle>false</RestartOnIdle>
</IdleSettings>
<MultipleInstancesPolicy>IgnoreNew</MultipleInstancesPolicy>
<DisallowStartIfOnBatteries>true</DisallowStartIfOnBatteries>
<StopIfGoingOnBatteries>true</StopIfGoingOnBatteries>
<AllowHardTerminate>true</AllowHardTerminate>
<StartWhenAvailable>false</StartWhenAvailable>
<RunOnlyIfNetworkAvailable>false</RunOnlyIfNetworkAvailable>
<AllowStartOnDemand>true</AllowStartOnDemand>
<Enabled>true</Enabled>
<Hidden>false</Hidden>
<RunOnlyIfIdle>false</RunOnlyIfIdle>
<WakeToRun>false</WakeToRun>
<ExecutionTimeLimit>PT72H</ExecutionTimeLimit>
<Priority>7</Priority>
</Settings>
<Actions Context="Author">
<Exec>
<Command>wevtvwr.msc</Command>
</Exec>
</Actions>
<Principals>
<Principal id="Author">
<UserId>IMAGINEDL\WILLIAMS</UserId>
<LogonType>InteractiveToken</LogonType>
</Principal>
</Principals>
</Task>
As you can see, this file is fairly complex, but don’t worry. You don’t have to create the XML configuration file from scratch. Using the techniques discussed in the section titled “Copying Tasks to Other Computers” earlier in this chapter, you can export the settings for an existing task into an XML configuration file and then use this file to create the same task on other computers.
At the command line, you can display a task’s status and its XML configuration using Schtasks /Query. Simply use the /Tn parameter followed by the name of the task to work with and the /Xml parameter to display the XML configuration as well as the status. This example displays the status and XML configuration for the “Computer Authentication” task:
schtasks /query /tn "Computer Authentication" /xml
If you redirect this output to a file with the .xml extension and then edit this file to remove the status details, you’ll have a complete XML configuration file that you can use to create the task. In the following example, the configuration for the “Computer Authentication” task is written to a file called ComputerAuthTask.xml:
schtasks /query /tn "Computer Authentication" /xml > ComputerAuthTask.xml
When working with remote computers, you can use the /S parameter to specify a remote computer, /U to specify the user context for creating the task, and /P to specify the user password.
Once you gain a working knowledge of how the XML configuration files work, you may want to start manually editing XML configuration files as necessary. When you do, make sure to test your changes on a test or development system rather than a production system. That said, let’s go through the essentials.
The RegistrationInfo element specifies when the task was originally created and by whom:
<RegistrationInfo>
<Date>2015-10-01T18:10:12</Date>
<Author>WilliamS</Author>
</RegistrationInfo>
The Triggers element specifies under which conditions the task runs. Within this element, the following is true:
Boot, idle, and registration triggers are the easiest to define because they are either enabled or not enabled, as shown in this example:
<Triggers>
<BootTrigger>
<Enabled>true</Enabled>
</BootTrigger>
</Triggers>
Actions elements define the commands to run, the e-mail to send, or the message to display. Commands to run are defined within Exec elements. The following example runs a script called CleanUp.bat:
<Actions Context="Author">
<Exec>
<Command>c:\scripts\cleanup.bat</Command>
</Exec>
</Actions>
E-mail messages to send are defined within SendEmail elements. The following example defines an e-mail message to send to admins@imaginedlands.com via the mailer15.adatum.com mail server:
<Actions Context="Author">
<SendEmail>
<Server>mailer15.imaginedlands.com</Server>
<Subject>Possible Database Outage</Subject>
<To>admins@imaginedlands.com</To>
<From>williams@imaginedlands.com</From>
<Body>The CRM Database appears to be down.</Body>
<HeaderFields />
</SendEmail>
</Actions>
Messages to display on the desktop are defined within ShowMessage elements. The following example displays a warning about a possible application outage:
<Actions Context="Author">
<ShowMessage>
<Title>Application Outage Warning</Title>
<Body>The CRMComms application is having write errors.</Body>
</ShowMessage>
</Actions>
Finally, the Principals element defines the user context under which the task runs, including whether the task can run interactively, and the run level. In the following example, the task runs interactively with least privileges under the user account of WilliamS:
<Principals>
<Principal id="Author">
<UserId>IMAGINEDL\williams</UserId>
<LogonType>InteractiveToken</LogonType>
<RunLevel>LeastPrivilege</RunLevel>
</Principal>
</Principals>
You can configure the task to run whether the user is logged on or not, or to run with highest privileges. To run whether the user is logged on or not, you set LogonType to Password. To run with highest privileges, you set RunLevel to HighestAvailable. Here is an example using these options:
<Principals>
<Principal id="Author">
<UserId>IMAGINEDL\williams</UserId>
<LogonType>Password</LogonType>
<RunLevel>HighestAvailable</RunLevel>
</Principal>
</Principals>
If you don’t want Task Scheduler to store the password associated with the user account, you can set the LogonType to S4U, as shown in this example:
<Principals>
<Principal id="Author">
<UserId>IMAGINEDL\williams</UserId>
<LogonType>S4U</LogonType>
<RunLevel>HighestAvailable</RunLevel>
</Principal>
</Principals>
You can run a task at any time using the following syntax:
schtasks /run /tn TaskName
where TaskName is the name of the task you want to run, such as
schtasks /run /tn "SysChecks"
Running a task does not affect its schedule and does not change the next run time for the task. If the task can be successfully started, you should see a message stating this. Additionally, you can specify the name of the remote computer on which the task is configured and, as necessary, the account to run the task as, including an optional password, as in the following examples:
schtasks /run /tn "SysChecks" /s 192.168.1.100
schtasks /run /tn "SysChecks" /s 192.168.1.100 /u imaginedlands\wrstanek
NOTE If you specify a user and don’t provide a password, you will be prompted immediately to enter the password.
You can stop a task at any time using the following syntax:
schtasks /end /tn TaskName
where TaskName is the name of a task that is currently running and should be stopped, such as
schtasks /end /tn "SysChecks"
The task is only stopped if it is running. If successful, the output message should be similar to the following:
SUCCESS: The scheduled task "SysChecks" has been terminated successfully.
You can also specify the name of the remote computer on which the task is configured and, as necessary, the account with authority to stop the task, including an optional password, such as
schtasks /end /tn "SysChecks" /s 192.168.1.100
or
schtasks /end /tn "SysChecks" /s 192.168.1.100 /u imaginedlands\wrstanek
Because a password isn’t specified, Schtasks will prompt you for one.
You can delete tasks by name on local and remote computers using the following syntax:
schtasks /delete /tn TaskName [/s Computer /u [Domain/]User [/p Password]]
where TaskName is the name of a task that should be deleted and the rest of the parameters optionally identify the remote computer, the user account to use when deleting the task, and the password for the account, such as
schtasks /delete /tn "SysChecks"
or
schtasks /delete /tn "SysChecks" /s 192.168.1.100 /u imaginedlands\wrstanek /p frut5
NOTE If you specify a user name and don’t provide a password, you will be prompted immediately to enter the password.
After entering the Schtasks /Delete command, you should see a warning asking you to confirm that you want to remove the task. Press the appropriate letter on your keyboard. If you don’t want to see a warning prompt use the /F parameter, such as
schtasks /delete /tn "SysChecks" /f
Here, you force Schtasks to delete the task without a warning.
In addition, if you want to delete all scheduled tasks on the local computer or the specified remote computer, enter an asterisk (*) as the task name, such as
schtasks /delete /tn *
Confirm the action when prompted.