command line script

   

Using && and || for Conditional Processing

When you use && between two commands in a single command line, the command interpreter

processes the first command and, if successful, processes the second command. On the other

hand, if you use || between two commands, the command interpreter processes the second

command only if processing of the first command failed. The syntax for using these two

symbols is:

 

Command1 && Command2

Command1 || Command2

With &&, the command interpreter processes the second command only if it is successful in

processing the first command. But with ||, the command interpreter processes the second

command only if processing of the first command failed. Check the following examples:

 

Cd C:/Reports/Mar98 && Copy Rep5.txt D:/Reports

Cd C:/Reports/Mar98 || Md C:/Reports/Mar98

In the first example, the file Rep5.txt is copied to the D:/Reports directory only if the

first command is able to change the current working directory to C:/Reports/Mar98. In the

second example, if the directory Mar98 does not exist, the second command is processed to

create this directory.

 

 

 

Grouping Sets of Commands with Parentheses

You can use sets of chained commands with parentheses to form groups of command sets. The

syntax is:

 

(Command1 & Command2) && Command3

The command interpreter processes Command3 only if both Command1 and Command2 are executed

successfully. You can reverse this condition using || as follows:

 

Command1 || (Command2 & Command3)

In this case, the command interpreter processes Command2 and Command3 only if Command1 does

not complete successfully.

 

 

2.6

Batch file Modifiers to Expand Parameter.

 

 

Creating Batch Files

Batch files are simply collections of multiple commands in a single file. They are also

called script files. They are useful for everyday administrative tasks for which you do not

want to remember commands or their syntax. You can create batch files using a text editor

such as Notepad; you save batch files with a .bat or .cmd extension. When a batch file is

run from the command prompt or called from within another batch file, the commands in the

file are executed one by one in the order in which they appear in the batch file. Batch

files are very useful in the following situations:

 

When you need to perform similar administrative tasks on a regular basis on a single

computer

 

When you need to perform a series of administrative tasks on a number of computers in the

network

 

When you want to run specific administrative tasks on remote computers and it is not

possible to go to the computer and work on a GUI

 

When you want to organize the output of commands run on a computer

 

When you need to repeat exactly the same administrative tasks on a number of computers

 

You do not need to be a programmer to create batch files. Batch files are simple

collections of commands combined with some operators and parameters. Just open Notepad and

write a few simple commands as follows:

 

Rem * This file is my first batch file *

Echo My First Batch File

Echo Off

Dir

Echo You Just Saw Directory Listing

Echo Bye For Now

 

When you are done writing these lines, save the file as Mybatch.bat. Open the command

prompt, type Mybatch, and press Enter. You will see the output of the batch file displayed

in the command shell window, as shown in Figure 2.3.

 

 

Figure 2.3: Output of a Batch File

You might have noticed that all commands used in the batch file are also displayed as they

are processed. Every time a command is processed, the command prompt is displayed along

with the command itself. To get around this problem, you can use the Echo Off command. This

stops commands from being displayed when they are processed. You use the Rem statement in

the beginning of the file to insert comments into the file. The text after the Rem command

is not processed. You use the Echo command to display a message. You will learn about batch

file commands in the next section.

 

 Note  Batch files are considered executable files. You do not need to add the .bat

extension from the command line when running batch files. This means that it does not make

any difference whether you type Mybatch.bat or Mybatch at the command prompt.

 

 

Batch File Commands

As we discussed earlier, batch files are simply text files that contain a number of

commands. When a batch file is run, these commands are processed one line at a time in the

order they appear in the file. Table 2.3 lists some of the commands that are commonly used

in batch files.

 

Table 2.3: Commands Commonly Used in Batch Files  Command

 Description

 

Call

 Used to call one batch file from within another batch file without stopping the processing

of the original batch file.

 

Choice

 Pauses batch file processing and displays a prompt to the user to choose one of the given

options using a specified key.

 

Echo

 Turns the echo on or off. Also used to display a message.

 

Endlocal

 Ends the localization of environment variables changed by the Setlocal command. The

variables are set back to their original values.

 

For

 Repeats the processing of a command for each file in a group of files.

 

Goto

 Directs the batch processing to a specified line identified by a label. After jumping to

the specified command line, the processing continues with the next command.

 

If

 Used to perform conditional processing of commands in a batch file.

 

Pause

 Suspends the processing of the batch file and prompts the user to press any key in order

to continue processing it.

 

Rem

 Used to add comments in batch files. The text after the Rem command is not processed.

 

Setlocal

 Starts the localization of environment variables in a batch file until a matching Setlocal

command is found.

 

Shift

 Used to change the position of batch parameters in a batch file.

 

 

In the following sections, we explain each batch file command.

 

Call

You use the Call command to call another batch file or to direct the file to another

location within the same file identified by a label. You can use this command only in batch

files; it does not have any effect when you use it at the command prompt. For example, if

you have two batch files named Mybatch1.bat and Mybatch2.bat in the C:/Myfiles folder and

you want to call Mybatch2.bat from within Mybatch1.bat, you can use the following command

in the Mybatch1.bat file:

 

Call C:/Myfiles/Mybatch2.bat

Besides using other files as the target of the call, the Call command also accepts a label

within the same file as the target of the call. A label is an argument within the same

file. Consider the following example:

 

Call: Label1

In this example, the Call command is used to call a label that is specified as Label1.

 

 Note  You can also use the Goto parameter to call another subroutine in a batch file. The

difference between the Call and Goto parameters is that you use Goto to call a subroutine

within the same file, and you use Call either to jump to a subroutine within the same file

or to transfer control to a different batch file.

 

 

Choice

You use the Choice command to suspend processing of a batch file and prompt the user to

make a choice from the given options. You can add a message before the available choices so

that the user understands what input she is required to provide for further processing, and

why. This makes batch file processing a little more interactive and ensures that the user

is making the correct choice. The command interpreter pauses until the user presses a key

corresponding to her choice. You can have the command interpreter wait for user input for a

specified time in seconds. A simple example of this command’s usage is:

 

Do you want to delete this file [Y/N]?

The syntax of this command is:

 

Choice [/c [keys]] [/n] [/cs] [/t Timeout /d KeyChoice] [/m Text]

Here is an explanation of the syntax used in the preceding command:

 

/c keys Displays the keys from which the user can make a choice, followed by a question

mark (?). If you do not specify any keys with the /c parameter, Y (yes) and N (no) are

displayed by default and are followed by a question mark. The keys are enclosed in brackets

[ ] and are separated by commas.

 

/n Used to hide the display of key options. For example, if you use the /c:YN and /n

parameters, the command interpreter will not display [Y,N]? at the command prompt, but the

options will still be available.

 

/cs Used if you want the key choices to be case sensitive. By default, the keys you specify

in the /c keys parameter are not case sensitive.

 

/t Timeout /d KeyChoice Specifies the number of seconds the Choice command will wait for

the user to press a key. If the user does not press any key, the command takes the default

key choice specified in the /d parameter. The value of /t can be anything from 0 to 9999

seconds. A value of 0 will cause the Choice command to take the default key choice from the

/d parameter without waiting for the user input. For example, /t 10 /d Y it will cause the

Choice command to wait 10 seconds for user input. Use the Y (yes) option if the user does

not press any key.

 

/m Text Used to display a text message just before the key choices. For example, you can

display “Do you want to continue?” by using the /m parameter.

 

The following is an example of using the Choice command:

 

Choice /c YNC /t 10 /d C /m "Press Y for Yes, N for No, or C to Cancel"

When you run this command from the command prompt, the following message will appear:

 

Press Y for Yes, N for No, or C to Cancel

The command prompt will wait 10 seconds for the user to press a key and then use C (cancel)

as the default choice. Note that the message must be enclosed in quotation marks;

otherwise, the command prompt will display an error message.

 

Echo

You use the Echo command to turn command echoing on or off, or to display a message. When

you use the Echo command without the On or Off parameter, the current echo setting is

displayed. The following is the syntax for the Echo command:

 

Echo [ON | OFF]

Echo Message

Echo is enabled (on) by default. The command interpreter displays every command in a batch

file as it is processed. You can turn this off by using the Echo off command at the

beginning of the file. It is interesting to note that when the Echo off command is

processed, it is also displayed. To get around this problem you can use the at sign (@)

just before the Echo off command, as follows:

 

@Echo off

 Note  You can use @ to suppress display of any command, but it is commonly used with the

Echo command.

 

 

You can use the Echo command to display a message when echo is turned off in a batch file.

You can also use the Echo command multiple times to display a long message spread over

several lines. The following example illustrates how you can display a message using the

Echo command:

 

Echo off

Echo This is my first batch file.

Echo I am testing some commands.

Echo I will use these commands in batch file.

Echo on

When you run these commands at the command prompt, the messages are displayed in three

lines, as follows:

 

This is my first batch file.

I am testing some commands.

I will use these commands in batch file.

You should leave echo on when you are testing a batch file so that you can see how each

command is processed. When you turn echo off, you will not be able to see the commands or

the command prompt, and this may cause trouble when you are testing a batch file.

 

Endlocal

The Endlocal command ends the localization of environment variables set by the Setlocal

command and restores the variables to the values they held before the Setlocal command was

used. If you use the Setlocal command but forget to add the Endlocal command, the command

interpreter automatically restores the environment variables to the values they held before

the Setlocal command was used. This command is not effective when used outside a batch

file. Please refer to the example given with the Setlocal command later in this section.

 

For

You use the For command to run a specified command for each file for a given set of files.

This is called iteration. You can use this command both at the command prompt and in batch

files or scripts. The command has the following syntax:

 

For %%variable IN (set) do Command [Command-options]

Here is an explanation of each parameter of the For command:

 

%% variable A required parameter that is replaced by its actual value and controls the

execution of the command. This variable is case sensitive. The %% variable is also called

the iterator. If you want to run the For command from the command prompt, you would use the

% variable instead. Note that from the command prompt only one % is used with the variable.

 

(Set) Defines a set of files, a set of directories, a range of values, or a set of text

strings. These are the values that you want to process with the command. The values or text

strings must be enclosed within parentheses.

 

Command Specifies the command that you want to process for each file, directory, value, or

text string defined in the (Set) argument.

 

Command parameters Parameters for the command that you want to process for the variables.

 

As discussed earlier, the For command can work for a group of files, a group of

directories, a range of values, and a collection of text strings. When the For command is

executed, the type of variable takes its values from the specified set, one by one, and

processes the command for each file, directory, or value. The following sections explain

different forms of variables used in the For command.

 

Group of Files

The syntax of the For command when working with a group of files is as follows:

 

For %% variable in (FileSet) do Command [Command Parameter]

You can specify a single file or a group of files in the FileSet parameter. When using a

group of files, you can use a wildcard such as *.txt or *.doc. It is also possible to use

files with different extensions, each separated by a space, such as *.txt *.doc *.exe,

feb*.txt april2*.doc, and so on. The command is processed for each file specified in

FileSet. For example, if you want to list all files in a directory named C:/Myfiles that

have an extension of .doc, you can use the following command:

 

For %%A in (C:/Myfiles/*.doc) do (echo %%A)

The command is initialized by the %%A variable. The value of the %%A variable is replaced

in each file with a .doc extension found in the C:/Myfiles directory and the Echo command

is processed for each of these files. The final output echoes or displays a list of all

files.

 

Directories

The syntax of the For command when working with directories is:

 

For /D %% variable in (DirSet) do Command [Command Parameter]

You can specify a single directory or a group of directories in the DirSet parameter. This

command syntax is similar to the command syntax for files, except that you specify

directory paths rather than file paths. When you are working with a directory with multiple

subdirectories, the command takes the following syntax:

 

For /R [[Drive:[path]] %% variable in (DirSet) do Command [Command Parameter]

In this case, the command is executed for each directory in the directory tree. Note that

the /D parameter is replaced with the /R parameter when working with the directory tree.

 

If you do not specify any drive letter or path with the /R parameter, the current directory

is assumed by default.

 

Range of Values

The syntax of the For command when working with a range of values is as follows:

 

For /L %% variable in (Start#,Step#,End#) do Command [Command Parameter]

In this case, you specify a start number to set the starting value of the variable, a

number to set the step value, and an end value to specify the stop number. When the command

is executed, the values of the start and end numbers are compared. The end number must be

larger than the start number for the command to execute successfully. When the value of the

variable becomes larger than the value of the end number, execution of the For loop is

stopped. The following example illustrates the use of this form of the For command:

 

For /L %%A in (0,4,20) do echo %%A

In this command, we specified a start value of 0, a step value of 4, and an end value of

20. When this command is executed, the %%A variable takes the values of 0, 4, 8, 12, 16,

and 20, and the Echo command is executed for each of these values. The final output is:

 

 0

 4

 8

12

16

20

It is also possible to use negative step values. You can use the following example with a

negative step value. The command will appear as:

 

For /L %%A in (20,-4,0) do echo %%A

The output will be:

 

20

16

12

 8

 4

 0

Parsing Text Strings

Parsing file contents and text strings involves somewhat complex iterations with the For

command. You can use the parsing techniques with names of files and directories and other

text strings. These commands work well for output of commands as well as for the contents

of specified files. You use the variables to define the string you want to parse or

examine. You use parsing keywords to further modify the parsing. The three different forms

of the syntax are:

 

For /F ["Parsing Keywords"] %% variable in (FileNameSet) do Command [Command Parameter]

For /F ["Parsing Keywords"] %% variable in ("LiteralString") do Command [Command Parameter]

For /F ["Parsing Keywords"] %% variable in ('Command') do Command [Command Parameter]

Table 2.4 lists parsing keywords, along with an explanation and examples for each.

 

Table 2.4: Parsing Keywords Used with the For Command  Parsing Keyword

 Description

 Example

 

eol=c

 Specifies the end-of-line character. You can use only one character. Anything after the

end-of-line character is considered a string.

 “eol=;”

 

skip=N

 Specifies the number of lines that should be skipped at the beginning of the file.

 “skip=5”

 

delims=xxx

 Sets delimiters to use for fields that replace the default space and tab delimiters.

 “delims=,.:”

 

Tokens=X,Y,M-N

 Specifies the tokens that you should use from each source line for each iteration of the

For command. You can specify a maximum of 26. The M-N specifies a range of tokens.

 “tokens=1,3,5”

 

tokens=1-6”

 

tokens=*”

 

usebackq

 Specifies that you can use quotation marks to enclose filenames in FileNameSet. A back-

quoted string is executed as a command and a single-quoted string is treated as a literal

string.

 ---

 

 

Let’s consider an example from the stock file of an electronics store. This file is a text

file named Stock.txt that contains the name of the items, their part number, the number

currently in stock, their reorder level, and the total number sold. The first line of this

file reads as follows:

 

Calculators    CA5600125    75    15    45

You can parse the file using the For command as follows:

 

For /F "tokens=1-5" %%A in (stock.txt) do )@echo Item: %%A Part Number: %%B In Stock: %%C

Reorder: %%D Sold: %%E)

The command specifies that the first five fields are to be processed identified by the

token=1-5” parameter. The fields are separated by spaces or tab characters. They will be

identified by variables from %%A to %%E. The Echo command will be executed for each field

or variable. When this command is executed, the output is displayed as:

 

Item: Calculators Part Number: CA5600125 In Stock: 75 Reorder: 15 Sold: 45

If you do not want to use all of the fields from the file, you can specify the token value

to get only the fields you need. For example, if you want to extract only the item name and

balance in the previous example, you can replace “token=1-5” with “token=1,3”.

 

 

 

Swiss Army Knife…One or Two Percent Signs?

You should use a single % with the variable parameter when you want to use the For command

directly at the command prompt. Within batch files, you must use %%. For example, the

command For %%A in (C:/Myfiles/*.doc) do (echo %%A) in a batch file would read as For %A in

(C:/Myfiles/*.doc) do (echo %%A) at the command prompt.

 

 

 

 

 

Goto

You use the Goto command in a batch file to transfer control of the command interpreter to

another section of the file identified with a specified label. This is different from the

Call command, which can transfer control to a section within the batch file or can call

another batch file. The Goto command works only within the batch file that is currently

being processed. A label is a text string within the batch file that identifies another

section of the file. The Goto command is commonly used with the If command for conditional

processing of commands. The following is a simple example of the Goto command:

 

@Echo off

Echo Please insert a disk in drive A

Pause

Chkdsk A: /f

If not errorlevel 1 goto End

Echo An error occurred while performing disk check.

:End

 

In this example, :End is a text string known as a label. The batch file first prompts the

user to insert a floppy disk in drive A:. The user would insert the disk and press the

Enter key. If the Chkdsk command runs successfully, the Goto command transfers control to

the line identified by the :End label and the program ends. Otherwise, an error message is

displayed.

 

If

You use the If command for conditional processing of commands in a batch file. Large and

complex batch files usually perform multiple tasks, and you can program tasks to run if

certain conditions are satisfied. In some cases, you might want to verify that a previous

command has completed without generating any errors before processing the next command. In

other cases, you might want to process a certain command if the condition is satisfied, but

process a different one if the condition is not satisfied. The following is the syntax for

the If command:

 

If [not] errorlevel Number Command [else Expression]

If [not] String1==String2 Command [else Expression]

If [not] exist FileName Command [else Expression]

You might have noticed the use of the not operator in each command syntax. This is an

optional operator that is often used to perform a reverse condition check. This operator

specifies that the following command should be processed only if the given condition is not

satisfied. The else clause is used to tell the command interpreter to execute the command

that follows the else clause whether the command is satisfied or not (if the not operator

is used). The else clause must be on the same line as the If command.

 

The first command syntax uses a not operator with the error level. Different commands have

different error levels that start with zero. Error levels may also vary depending on the

type: a user’s error, a command-execution error, or an application error. In most cases,

error level zero represents no error, meaning that the command or the task was executed

successfully. The error levels are also sometimes known as exit codes for applications. The

exit code is actually a number that indicates whether the application processed

successfully.

 

Table 2.5 lists exit codes for the Format command.

 

Table 2.5: Exit Codes for the Format Command  Exit Code

 Description

 

0

 The format process completed successfully, without errors.

 

1

 Incorrect parameters were supplied with the Format command.

 

4

 A fatal error occurred during the format process. This may be any error other than errors

1, 4, and 5.

 

5

 The user pressed the N key to stop the format process when prompted with “Proceed with

Format (Y/N)?”

 

 

In the second command syntax shown in the preceding code snippet, two strings are compared.

If the value of the first string is equal to the value of the second string, the following

command is executed. Otherwise, the command following the else clause is executed. You may

use this command syntax to compare user input with a preconfigured string and decide on the

next command to be processed based on the input.

 

The third command checks whether the specified filename exists. If it does exist, the

following command is executed; if it doesn’t exist, the command following the else clause

is executed. You may use this If command syntax when working with files.

 

The following example illustrates use of the If command with errorlevel and else clauses:

 

@Echo off

:Begin

Format A: /s

If errorlevel 1 goto End

Echo An error occurred during the formatting process.

:End

This file has two labels named :Begin and :End. If the Format command encounters an error

during formatting, it displays an error message and control is transferred to the section

labeled :End. Let’s look at another example:

 

@Echo off

 

:Begin

If exist C:/Myfile.txt goto Copyfile

Echo Cannot copy the file because it does not exist.

Goto End

 

:Copyfile

Copy C:/Myfile.txt C:/Myfile2.txt

Goto End

 

:End

This file checks whether the file named Myfile.txt exists in the C: drive. If the file

exists, control is transferred to the section labeled Copyfile. Otherwise, the file

displays the message “Cannot copy the file because it does not exist.” and then jumps to

the section labeled as :End. The Copyfile section (or procedure) copies the file to another

file named Myfile2.txt and then transfers control to the section labeled :End.

 

Pause

The Pause command suspends processing of the batch file and prompts the user to press any

key to continue processing. This command is most commonly used when you want the user to

insert a floppy disk or a CD-ROM and then press any key to continue. For example, if you

want the user to insert the Windows Server 2003 installation CD-ROM in the CD drive E:, you

can use the following:

 

@Echo Off

:Begin

Copy E:/Suptools/*.*

Echo Please insert Windows Server 2003 CD-ROM in the CD drive

PAUSE

Goto End

 

:End

When the command interpreter encounters the Pause command, it suspends processing until the

user presses any key. The user now has time to insert the CD-ROM and can then press a key

so that the batch file can continue processing. You may have noticed the @Echo Off command

at the beginning of this example, and you might be aware that the Echo Off command turns

off echo but the command itself appears when it is processed. The function of the @ before

the Echo Off command is to hide the command itself. When you run these commands in a batch

file the command interpreter copies all files in the E:/Suptools folder. But prior to that

it pauses and displays the following output in the command shell window:

 

Please insert Windows Server 2003 CD-ROM in the CD drive

Press any key to continue…

:Begin and :End in this example are the labels. When you insert the CD-ROM and press a key,

the processing continues and the command interpreter reaches the Goto command, which sends

control back to the start of the file that has the :Begin label.

 

Terminating a Batch Job

When you use the Pause command in a batch file and the previous message appears, you also

have the option to terminate batch processing by using the Ctrl + C key combination. When

you do this the following message is displayed:

 

Terminate batch job: (Y/N)?

If you want to stop or terminate further processing of the batch file, press Y (yes) and

the command interpreter will return to the command shell window. In fact, you can terminate

the processing of any batch file using this key combination at any time during the

execution of the file.

 

 

 

Swiss Army Knife…Suspend or Terminate?

The Pause command has two functions: It can either suspend the program or terminate it. You

can pause the batch file and wait for a key press while you insert a floppy disk or a CD-

ROM, or change media. If you are unsure about what will happen next, you can just press the

Ctrl + C key combination to terminate the processing of the batch file. While this may

facilitate the author who has written the batch file, it may also give another user the

option to terminate the batch file before it completes processing. As you may not want this

to happen, you should be very careful when using the Pause command.

 

 

 

 

 

Rem

The Rem command allows you to insert comments into a batch file. You use this command to

organize different parts of the batch file. This command is useful in understanding a batch

file when you did not create it, or when you are troubleshooting a file that causes errors

when it is processed. The command interpreter does not process or display the text written

after the Rem command. This is different from the Echo command, where the text after the

command is displayed on the screen. The following example illustrates use of the Rem

command:

 

@Echo off

Rem *File Name: CDCopy.bat*

Rem *This batch file copies the contents of a CD-ROM drive E

Rem * To a folder C:/test on the hard drive*

Rem *Author-Gary B.*

Rem

Echo Insert the CD-Rom in CD drive

Pause

Xcopy E:/*.* C:/test

The text after the Rem command cannot include quotation marks or pipes.

 

 

 

Master Craftsman…A Neatly Written Batch File

You use the Rem (remarks) command to insert comments in a batch file. You should make it a

habit to use this command as often as possible to neatly organize different sections of

your batch file. When working with several batch files on a regular basis, you will

obviously be dealing with a large number of files every day. It is quite possible that

after a while you will start forgetting their purpose. Inserting comments in the beginning

of a file helps you immediately recognize its purpose. If it is a large file containing

several sections, these comments not only help you organize different file sections (or

subroutines), but they also help with troubleshooting. And if someone else is working on a

file you created, your comments will make it easy for him to understand how the file is

supposed to work. The Rem command helps keep your work neatly organized for yourself and

others.

 

 

 

 

 

Setlocal

The Setlocal command starts the localization of environment variables in a batch file. This

localization continues until a matching Endlocal command is found. You should use the

Setlocal and Endlocal commands only inside a batch file. Outside a batch file or a script

file, these commands have no effect. The following is an example of this command:

 

@Echo off

Rem This command sets local variables

Rem Localization ends when

Rem Processing of Mybatch2.bat file is complete

Setlocal

Path=%path%;C:/Myfiles;D:/Myscripts

Call Mybatch2.bat

Endlocal

It is also possible to place one Setlocal command within another. This is called command

nesting. If you do not use the Endlocal command, the command interpreter restores the

environment variables to the values they were at before the Setlocal command was used.

 

Shift

The Shift command changes the position of the parameters in a batch file from %0 through %

9. Each parameter is copied into the previous parameter. If you are using parameters from

%0 through %4, the Shift command would shift the value of %5 to %4, %4 to %3, and so on.

Since you can use only %0 through %9 parameters, use the Shift command when you need to

work with more than 10 parameters.

 

It is important to note that the Shift command works in one way only. If you use it to

accommodate an eleventh parameter (because you can use only 10 parameters at a time), the

values of the parameters will start shifting and the value of the %0 parameter will be

lost. Once the shift has been completed, you cannot recover the value of the %0 parameter.

 

Batch File Parameters

You use parameters in batch files to get information about environment settings. These

parameters are denoted by the expansion variables %0 through %9. The %0 variable is

replaced with the name of the batch file currently being processed. You can specify other

variables from %1 to %9 inside the batch file using argument types at the command prompt.

For example, if you have two folders named Folder1 and Folder2, and you want to copy all

the files and subfolders in C:/Folder1 to D:/Folder2, you would use the following command

at the command prompt:

 

Xcopy C:/Folder1/*.* D:/Folder2

Using batch file parameters, you would create a batch file named Mybatch.bat and include

the following command:

 

Xcopy %1/*.* %2

Save the file and run the following command from the command prompt:

 

Mybatch1.bat C:/Folder1 D:/Folder2

In this command, the variable %1 refers to C:/Folder1 and the variable %2 refers to

D:/Folder2. When the command is run, all the files and folders from C:/Folder1 will be

copied to D:/Folder2.

 

Using Variable Modifiers

You can replace the parameter variables we discussed in the previous section with

modifiers. Modifiers use the current drive and directory information to expand batch

parameters to make them directory names. A tilde (~) is placed between the % and the

modifier. The syntax for using the modifiers always remains as follows:

 

%~modifier

 

Table 2.6 provides a list of available modifiers.

 

Table 2.6: Batch File Modifiers to Expand Parameters  Modifier

 Description

 

%~1

 Expands the variable specified by %1 and removes the surrounding quotation marks.

 

%~f1

 Expands %1 to a fully qualified path name.

 

%~d1

 Expands %1 to only a drive letter.

 

%~p1

 Expands %1 to a path.

 

%~n1

 Expands %1 to only a filename.

 

%~x1

 Expands %1 to a file extension.

 

%~s1

 Expands the path variable to a full name and then changes it to the short names.

 

%~a1

 Expands %1 to file attributes.

 

%~t1

 Expands %1 to the date and time of the file.

 

%~z1

 Expands %1 to the size of the file.

 

%~f1

 Searches the directories specified in the Path variable for the file specified by the %1

parameter. Expands the first file that it finds to its fully qualified name. If no matching

file is found, an empty string is returned.

 

 

Using a Combination of Modifiers

Along with using modifiers individually in command parameters, you can use a combination of

them to obtain the desired output. The following examples show how you can combine two or

more modifiers to obtain the desired output:

 

%~dp1 Modifiers d and p are used together to obtain the drive letter and path of the %1

variable.

 

%~fs1 Modifiers f and s are used together to obtain file information using the short names.

 

%~nx1 Modifiers n and x are used together to obtain a filename and its extension.

 

%~ftza1 Modifiers f, t, z, and a are used together to produce a complete listing similar to

the output of a dir command.

 

%~dp$PATH:1 Modifiers d and p are used together to obtain the drive letter and path for a

file from the path specified by the Path parameter. The output only contains information

about the first file found.

 

 

Summary

In this chapter, we discussed how to work safely with the command line using a

nonadministrative account that has just enough privileges to run the command. While working

with the command shell, we sometimes need to specify a path where commands or batch files

are located. We can change or modify the command path by modifying the environment variable

either from the command prompt or from System Properties.

 

We also discussed how we can change command input and output from the standard keyboard and

the command shell window, respectively, and how to handle errors generated by commands.

Then we discussed the concept of batch files and how to create simple batch files. We

learned about commonly used commands in batch files and how to use each command inside a

batch file.

 

You can run batch files directly from the command prompt or schedule them to run at a

specified time. In the next chapter, we will focus our attention on scheduling batch files

to run at specified times. Running batch files at preconfigured schedules requires

configuration of the Task Scheduler service. In the next chapter, we will discuss how tasks

such as batch file processing can be scheduled and managed from GUI wizards, as well as

from the command line.

 

 

 

Chapter 3: Managing Scheduled Tasks

Introduction

Although administrators can perform most of their everyday administrative functions during

office hours, they must carry out certain tasks during off-hours or on the weekend. System

and data backups are good examples of such tasks. Backups consume a significant amount of

network bandwidth; when performed during office hours, backups could consume the bandwidth

employees need to get their jobs done. Furthermore, administrators cannot be expected to be

in the office at all times.

 

This is why administrators rely on batch files and scripts that run automatically at

predefined times. Using such programs, administrators can perform certain tasks, such as

system and data backups, at any time of the day or night. Windows operating systems depend

on a built-in service known as the Task Scheduler to run these tasks automatically. In this

chapter, we will learn about the Task Scheduler, the components on which it depends, and

how to configure tasks using the Task Scheduler Wizard as well as from the command line.

 

 

 

Scheduling Tasks

The Task Scheduler service in Windows is an automation utility that helps administrators

run commands, batch files, scripts, utilities, and other applications on preconfigured

schedules. The configured task runs automatically in the background—without requiring any

interaction from the administrator. It is not necessary to schedule all administrative

tasks to start or finish during off-hours. The service allows you to configure any task to

start and stop at any time, and repeat it every hour, every day, every week, or every

month. You may also schedule the task to run just once. To automatically run tasks at

predetermined schedules, you can use either the Task Scheduler or the command-line utility,

schtasks. Both provide more or less similar functionality and depend on the task scheduler

service, which must be running when the tasks are scheduled to run.

 

The Task Scheduler

The Task Scheduler is a graphical user interface (GUI) utility that you can use to schedule

applications or batch files using configuration wizards. These easy-to-use wizards help you

create tasks, view and modify scheduled tasks, and check whether the scheduled tasks are

running. You can also enable or disable a scheduled task, or delete a task completely if it

is not required to run anymore.

 

schtasks

Choosing to use a command-line utility depends on how comfortable you feel working with the

Windows command prompt. schtasks is a little more advanced than its GUI counterpart, and it

is a more powerful version of the older AT command-line utility in Windows. Windows still

supports the AT command but we will discuss only schtasks in this chapter.

 

You can use both the Task Scheduler GUI and schtasks to create and manage scheduled tasks

on either local or remote computers. You do not have to be at the console of the remote

computer in order to run a task on it. Task scheduling makes it easy to run batch files,

scripts, programs, or other applications automatically, anywhere in the network. You can

also combine these two utilities to perform a complex task if you feel that using only one

will not be enough. Since you can use these utilities together, this chapter will discuss

both of them. Each scheduled task on a Windows system runs only one script or program at a

time. For multiple tasks, you will need to schedule each task independently.

 

 

 

Swiss Army Knife…The AT Utility

The AT utility has been used for a long time on Windows computers. You may still use it for

performing simple jobs. All batch jobs created using the AT utility run as a background

process. The output is never displayed on the screen but you can redirect the output to a

file using the redirection operator (>). Like schtasks, AT also uses the task scheduler

service. Jobs created by AT appear in the Scheduled Tasks window. Starting and stopping the

task scheduler service does not remove any jobs from the Scheduled Tasks window. AT has

several limitations compared with schtasks, and you may soon find that you are better off

with the latter for automating your routine administrative jobs.

 

 The Task Scheduler Service

As discussed earlier, scheduling tasks to run automatically at predetermined times requires the task scheduler service. It does not matter whether you create tasks using the GUI wizard or the schtasks utility; both require the task scheduler service to be running. The Task Scheduler service is enabled by default on Windows XP and Windows Server 2003 computers and runs automatically on startup as a background service. In some situations, you may need to start the service manually or restart a stopped service, or even enable it if some of your previous administrators have disabled it. You can start, stop, pause, restart, and enable/disable this service from the Services snap-in located in the Computer Management Console.

Accessing the Task Scheduler Service

You can access the Task Scheduler service (see Figure 3.1) either from the My Computer icon on the local computer, or by creating a custom Microsoft Management Console (MMC). The Services node in the Computer Management console contains Task Scheduler. To access the Computer Management Console from the My Computer icon on the local computer, follow these steps:

1.   Right-click the My Computer icon on the desktop and select Manage. This opens the Computer Management Console.

2.   Click the + sign next to the Services and Applications node to expand it.

3.   Click Services to view the services running on the computer.

4.   Locate the Task Scheduler service.

 
Figure 3.1: Task Scheduler Service Running Automatically on Computer Startup

You also can access the Services snap-in in one of the following ways:

§            From Administrative Tools in the Start menu

§            From the Control Panel

§            By running the SERVICES.mmc from the Run dialog box in the Start menu

It does not matter what method you use to access this snap-in; the same Services window opens.

Creating a Custom MMC for Services

Another way to open the Services snap-in and access the task scheduler service is to create a custom MMC. A custom MMC for the Services snap-in will allow you to manage the Task Scheduler and other services on local computers as well as any remote computer on the network. To use the MMC, follow these steps:

1.   Click Start | Run.

2.   Type MMC in the Run dialog box and click OK or press the Enter key.

3.   In the empty Microsoft Management Console, click File and select Add/Remove Snap-in.

4.   In the Add/Remove Snap-in window, click Add.

5.   Select Services from the Add Stand Alone Snap-ins window. Click Add.

6.   The next dialog box allows you to add the snap-in for the local computer or another computer on the network. Click Local Computer if you want to manage services on the local computer or type the name of a remote computer in the Another computer box (see Figure 3.2).


Figure 3.2: Adding the Services Snap-in for a Local or Remote Computer

7.   Click the Browse button if you do not know the name of the remote computer. When you click Browse, a Select Computer dialog box appears where you can specify the computer name or any other attributes of the remote computer to find it in the Active Directory database.

8.   Click Finish to add the Services snap-in to the MMC.

As shown in Figure 3.1, the task scheduler service runs using the Local System account by default. You can change to another account if you are concerned about the security of the current account. Also, notice that the status of the service is in Started state and its startup type is shown as Automatic.

When you right-click the service, you can select one of the following options:

§            Start If the service is stopped or if the startup type of the service is configured as Manual.

§            Stop If the service is running.

§            Pause To temporarily pause the service.

§            Resume To resume a service that is currently paused.

§            Restart To stop and restart the service automatically.

§            Properties To open detailed property pages of the task scheduler service.

These options are enabled or disabled depending upon the state of the service. For example, if the service is started, you cannot start or resume it. If the service is stopped, you can only start it—all other options are disabled.

Configuring the Properties of the Task Scheduler Service

You configure and manage the properties of the Task Scheduler service from its properties pages. To open the task scheduler service properties, either right-click the Task Scheduler service and select properties or just double-click the Task Scheduler service. Four different tabs on the properties pages allow you to configure the service, as explained in the following sections.

The General Tab

The General tab allows you to configure the startup service type. You can start, stop, pause, and resume the task scheduler service from this tab. You can configure the startup type in one of the following ways:

§            Automatic The service starts automatically when the system starts. It remains in the started state until it is manually stopped or it fails.

§            Manual The service is not started when the system starts. It starts when some application calls for it or when an administrator starts it from the Services snap-in or from the command prompt.

§            Disabled The service remains in a disabled state on system startup. If some applications or scripts are configured to run on the system, they do not run until the service is re-enabled.

The Log On Tab

The Log On tab allows you to change the user account that the service uses to run. By default, the task scheduler service uses the Local system account. If you feel that this account should not be used for security reasons, you can specify a more secure user account from this tab. If multiple hardware profiles are configured on a computer, you can enable or disable the service for a particular profile.

The Recovery Tab

The Recovery tab allows you to configure how the system behaves when the service fails. In its default configuration, the service restarts on first and second failures. You can configure the first, second, and subsequent failures of the service in one of the following ways:

§            Take No Action The system does not take any action when the service fails. You will have to restart the service manually from the Services snap-in or from the command prompt.

§            Restart the Service The system attempts to restart the service when it fails.

§            Run a Program You can specify an application or a script to run when the service fails. For example, you can run a script that sends you an e-mail that informs you that the service has failed.

§            Restart Computer The computer restarts when the service fails. You should choose this option only if other attempts to restart the service have failed.

The Recovery tab also allows you to reset the fail count (the number of times the service has failed) as well as specify the number of days when the fail count should be reset to zero. You can also specify the number of minutes the system should wait before restarting the service when it has failed.

Swiss Army Knife…Service Recovery

In its default configuration, a Windows Server 2003 computer will restart the service when it fails for the first and second times. The wait time to restart the service is also set to zero, meaning that the system will immediately attempt to restart the service. The system will not take any action when the service fails more than twice a day. It is interesting to note that the fail count is also reset every day. This means that the system will attempt to restart the service twice a day and take no action if it fails again. Another method is to create a script that will inform you about the service failure when it fails for the first time. This configuration is very important on mission-critical servers where you might have scheduled a task to run automatically every day and you find that the task did not even start.

 

The Dependencies Tab

The Dependencies tab displays the services that are required for the task scheduler service to run. You can also view the services that depend on this service. The task scheduler service depends on the Remote Procedure Call (RPC) service to run. If for some reason, the RPC service has failed, the task scheduler service will also fail. If you find that the task scheduler service has failed and you are not able to restart it, you should check the RPC service.

 

 

 

Managing Tasks Using the Task Scheduler

Scheduled Tasks is a type of GUI you can use to create and manage scheduled tasks. The Scheduled Tasks GUI is located in the System Tools folder under the Accessories category in Program Files. If you use this utility very frequently, you should create a shortcut to it on your desktop.

If you are using the Classic version of the Start menu, you can open the Scheduled Tasks window as follows:

1.   Click Start | Control Panel to open the Control Panel window.

2.   Double-click the Scheduled Tasks icon in the Control Panel window.

To open Scheduled Tasks on a network computer, follow these steps:

1.   Right-click the My Computer icon on the desktop and click Explore.

2.   Click the + sign next to My Network Places.

3.   Click the + sign next to Microsoft Windows Network.

4.   Click the + sign next to the Windows domain where the remote computer is located.

5.   Continue expanding the tree until you locate the computer.

6.   Click the computer name and the Scheduled Tasks icon will appear in the right-hand-side details pane.

Figure 3.3 shows the Scheduled Tasks window with two scheduled jobs.


Figure 3.3: Scheduled Tasks Window with Tasks Scheduled on the System

It does not matter whether you have scheduled tasks by using the Scheduled Task Wizard or by using the schtasks utility; the tasks will always show in the Scheduled Tasks window. You can access the Scheduled Tasks window for any computer on the network and manage the scheduled tasks. You can use the Scheduled Tasks window to change the properties of scheduled tasks, rename them, or even delete them—and you can do this for any computer where you have permission to perform these actions.

In Figure 3.3, two tasks have been scheduled to run automatically. The first task, Windows Update, is configured to run on a weekly basis: every Monday at 8.30 a.m. The second task, the Mybatch.bat file, was scheduled to run only once, at 8.20 p.m. on June 10, 2006. The window also shows the Next Run Time, the Last Run Time, and the status of both of the scheduled tasks, telling you immediately the last time the task ran and the next time it will run. You can manage these properties—as well as several properties of the scheduled task—from this window.

Managing the Properties of Scheduled Tasks

You can right-click any task in the Task Scheduler window to access its properties. From these properties pages you can modify scheduled tasks as you wish. You can change when the task should run, change the account under which the task should run, and delete the task that is scheduled to run only once after it has been completed. You can also set security permissions for scheduled tasks so that an unauthorized user cannot accidentally or deliberately delete them or modify their properties. We explain the different tabs of the Scheduled Task properties in the following sections.

The General Tab

The General tab of the Scheduled Task properties allows you to enable or disable a scheduled task and even change the program application of a script that is to be run. You can change the user account used to run the task and set a new password for the account, as well.

The Schedule Tab

The Schedule tab of the Scheduled Task properties shows the current schedule of the task. If you need to change the preconfigured schedules’ settings, you can do that here. This page offers so many timing and frequency options that it will take you some time to explore them all. We will discuss these options very briefly in this section. Figure 3.4 shows the Schedule properties page.


Figure 3.4: The Schedule Tab of the Scheduled Task Properties

The Schedule Task drop-down menu gives you the following options to run a task at desired times and frequencies:

§            Daily Used when you want the task to run daily at specified timings. You can also set the frequency as daily, every other day, or every three days.

§            Weekly Used when you want the task to run weekly at specified times and days. You can choose any day from Monday through Sunday, or choose multiple days when the task should run automatically. You can also choose every week or alternate weeks.

§            Monthly Used when you want the task to run on either a certain day of the month or a certain date. Additionally, you can choose the months (January to December) from the Select Months window by clicking the Months button.

§            Once Used when you want the task to run only once. This option is good for when you want to install an application on the local or remote system. The Run On box opens the calendar (where you can select the month and day of the month when the task should run).

§            At System Startup Used when you want the task to run every time the system is started. This option also allows you to specify the number of minutes to wait before starting the task (after the system starts up). The task will continue to run in the background until it is completed or terminated, or when the system is shut down.

§            At Logon Used when you want the task to run when someone logs on to the system. Once the task starts running, it will continue to run in the background until it is completed or the user terminates it, provided she has permission. The task can run with or without user intervention. If the task has been configured with a user account and some other user logs on, it will run using the originally configured user account. The task will not stop, even when the user logs off.

§            When Idle Used to configure certain tasks that require that the system be idle for a certain amount of time before it can be started. The When Idle tab allows you to configure such tasks by setting the amount of idle time in minutes. For example, you can configure a batch job or application to run when the system idles continuously for 10 minutes. Once the task starts, it continues to run, even if someone starts working on the system and it is no longer idle.

In all of these schedules, the Advanced button opens up another dialog box where you can set the Start Date and End Date for the scheduled task. This is useful when you want a task to run for a few days, weeks, or months. You can also configure the task to repeat itself at predetermined times during the day. The times are set in minutes.

The Settings Tab

The Settings tab allows you to configure the following properties for a scheduled task:

§            Delete the task that is scheduled to run only once when it has completed.

§            Stop the task if it continuously runs for a specified number of hours. This option is enabled by default and is set to 72 hours.

§            Run the task only if the system is idle for a specified amount of time in minutes. By default, this option is not enabled.

§            Stop the task when it has already started if the system is no longer idle. By default, this option is not enabled.

§            For portable computers, the task should not be started if the computer is running on batteries, and a running task should be stopped if the computer switches to battery mode. These two options are enabled by default.

The Security Tab

The Security tab of the Scheduled Task properties allows you to set permissions for the scheduled task. When you create a task that is configured to run under a user account, you need to give appropriate permissions so that the task can be run with the account. For tasks that are critical to network function (services such as performing backups or collecting security event logs), you should be very careful about who gets access. A small mistake in configuring access control for scheduled tasks can ruin the entire task—as well as create trouble for you as the administrator.

Monitoring Tasks in the Scheduled Tasks Window

All scheduled tasks appear in the Scheduled Tasks window of Windows Server 2003 and Windows XP systems. This is the best place to monitor and manage scheduled tasks on either a local or a remote computer. It does not matter whether the task was created using the schtasks command-line utility or the Scheduled Task Wizard; it appears in the Scheduled Tasks window. By default, the window shows the following information for every task, in a single line:

§            A list of scheduled tasks

§            A schedule for the task

§            The next run time

§            The last run time

§            The task’s status

§            The last result of the task

§            The user who created the task

§            Whether the task is disabled

If a task is disabled, it will show as Disabled in the Scheduled and Next Run Time columns.

Viewing the Scheduled Task Logs

The task scheduler service writes information about scheduled tasks in a log file. This log file is named SchedLgU.txt and is stored in the %SystemRoot% folder of the local computer. You can open the file either using Notepad or in the Scheduled Tasks window. This file contains detailed information about the task scheduler service, as well as tasks that have completed. If an error occurred when running a scheduled task, it is also written in this file.

To open the log file from the Scheduled Tasks window, click Advanced in the menu bar and select View Log. Figure 3.5 shows a sample file.


Figure 3.5: Scheduled Tasks Log

Creating New Tasks

The Scheduled Task Wizard makes creating a new task pretty straightforward. Once you have decided which task you want to run and its schedule, the rest of the job is fairly simple. The following steps will help you understand the procedure:

1.   Open the Scheduled Tasks window using any of the methods discussed earlier in this section.

2.   Double-click the Add Scheduled Task icon to start the Scheduled Task Wizard.

3.   Select the application from the list and click Next (as shown in Figure 3.6). Alternatively, you can click the Browse button to locate a file, script, or application.


Figure 3.6: Selecting an Application in the Scheduled Task Wizard

4.   On the next page, select the frequency of the task from the available options. The options are Daily, Weekly, Monthly, One time only, When my computer starts, and When I log on (see Figure 3.7). Click Next.


Figure 3.7: Selecting a Frequency for the Task

5.   If you selected the Daily schedule, you’ll see the page shown in Figure 3.8.


Figure 3.8: Setting the Daily Schedule for the Task

6.   In this page, you can set the time, frequency, and start date for the task. In the Perform this task section, select whether the task should run Every Day (seven days a week), Weekdays (Monday through Friday), or Every N days, where N is any number.

7.   If you selected the Weekly schedule in step 4, as shown in Figure 3.7, you’ll see the page that appears in Figure 3.9.


Figure 3.9: Setting the Weekly Schedule for the Task

8.   On this page you can set the start time, weekly frequency, and days of the week when the task should run. In the Select the day(s) of the week section, you can choose the days you want the task to run.

9.   If you selected the Monthly schedule in step 4, you’ll see the page shown in Figure 3.10.


Figure 3.10: Setting the Monthly Schedule for the Task

10.   On this page, you can select the start time, day, and month from a wide range of options. You can choose a particular day from the selected months or select a particular day of the week. You can also specify whether the task should run on a particular day in the first, second, third, fourth, or last week of the month. This option does not allow you to choose a particular day of the week.

11.   When you have made your selections, click Next. The next page prompts you to set the username and password that the task will use to run. Every scheduled task on a Windows computer needs a user account. Select the user account in the Enter the user name box. Specify the username in the Domain/User format. Type and confirm the password as shown in Figure 3.11.


Figure 3.11: Setting the User Account and Password for the Task

12.   Click Next to go to the final page of the wizard.

13.   Click Finish to create the task. It will appear in the Scheduled Tasks window.

Another way to create a new task is to click the File menu option, select New, and select Scheduled Task. A task named New Task that starts on the following day and is scheduled to run every day at 9:00 a.m. is created. You can edit the properties of this task to customize it to fit your requirements.

Master Craftsman…Misconfigured Tasks

When you are creating a task using the Scheduled Task Wizard, you may enter incorrect information—either because you don’t realize the information is incorrect or because you mistyped something. The best way to deal with this is to click the Back button and check all the information on each page before clicking the Finish button on the final page. If you type an incorrect username or password, the wizard will display an error message. Interestingly, the task will still be created. Once the task is created, you can always edit its properties and change any incorrect information. If you let the task run with incorrect parameters, it will fail and an error entry will be created in the Scheduled Tasks log file. If you later find that the scheduled task did not run on schedule, you can check the SchedLgU.txt log file. You can open this file by selecting View Log from the Advanced menu in the Scheduled Tasks window.

 

Deleting a Scheduled Task

Deleting a scheduled task from the Scheduled Tasks window is fairly simple but you must have the appropriate permission to do so. Right-click the task and select Delete from the context menu. This will delete the scheduled task. Remember that deleting a task from the Scheduled Tasks list does not affect the actual program or file that the task was scheduled to run.

Running a Scheduled Task Immediately

You can run a scheduled task immediately from the Scheduled Tasks window. Running a task does not affect its actual schedule. The task will still start at its scheduled time even if it has been run off-schedule. To run a task, right-click the task and select Run from the context menu.

Once the task has completed, you can view the scheduled tasks menu to check whether it completed successfully. This feature is good for testing scheduled tasks to make sure their configurations are correct. If you configure a complex task, you must perform a test run to verify that the configuration is correct. The most common configuration mistake made is incorrect specification of the username and password used to run the task. By running a task immediately after creating it, you verify that these parameters are correctly configured.

Enabling or Disabling a Scheduled Task

In some situations, you may feel that a configured task needs to be disabled for a while so that you can carry out certain changes in its configuration. This is particularly important when the task is scheduled to run very frequently. For example, you may need to disable a task that is scheduled to run every hour because you want to make changes to the script the task is running. It may take a few hours to carry out and test the changes. If the task is enabled, it will generate errors, as the task scheduler service won’t be able to run the script file.

You can disable scheduled tasks from the Task Properties page. When you open it, the Task tab is displayed by default. At the bottom of this page is a check box (enabled by default) indicating that the task is enabled. Clear this check box to disable the task. The task will then be shown as Disabled in the Scheduled Tasks window. You can re-enable a disabled task by clicking the check box again.

Ending a Running Task

Stopping or ending a running task is as easy as running it from the Scheduled Tasks window. Right-click the task and click End Task in the context menu. This will immediately stop the task from running. Ending a scheduled task in this manner does not affect the task’s regular schedule. The task will again start at its scheduled date and time.

Event-Based Tasks

Tasks that are scheduled to run when some system event happens are known as event-based tasks. These tasks are scheduled to run automatically when one of the following conditions is met:

§            When the system is started

§            When a user logs on to the system

§            When the system is idle

§            When an application triggers the task

These tasks start as soon as the event takes place and continue to run until finished. Any user who has appropriate permission can terminate them. You can configure these tasks using the Scheduled Task Wizard or the schtasks command-line utility.

Swiss Army Knife…Accessing Remote Systems

If you are working in the Scheduled Task Wizard or using the schtasks utility to configure tasks on remote computers, you need to be aware that these utilities require that the File and Printer Sharing for Microsoft Networks service is running on all the systems where the tasks will be running. Scheduled tasks frequently require access to resources located on local or remote systems and you cannot access these resources if the File and Printer Sharing for Microsoft Networks service is not running. In Windows XP and Windows Server 2003 computers this service is installed and configured to run automatically when networking is installed. When you are troubleshooting a failed scheduled task, you should also make sure that this service is not the cause of the problem.

 

 

The schtasks Command-Line Utility

schtasks is a command-line utility that provides all the functions of the Scheduled Tasks GUI utility. It helps with creating new tasks and running them at scheduled times. You can also start and stop tasks, display the settings of a particular task, and modify tasks if required. You can query a scheduled task and delete it if it is no longer required or has completed. schtasks has replaced the AT utility, which provided similar but limited functions for scheduling tasks in older versions of the Windows operating system.

schtasks has several parameters and arguments that are required to perform a specific function using this command. These parameters are as follows:

§                    schtasks /Create Used to create new scheduled tasks.

§                    schtasks /Query Used to display the settings of an existing scheduled task.

§                    schtasks /Change Used to change or modify existing tasks.

§                    schtasks /Run Used to run tasks that have been scheduled.

§                    schtasks /End Used to stop a running scheduled task.

§                    schtasks /Delete Used to delete a scheduled task.

We discuss these commands in the following sections. If you run the schtasks command without any parameters on the local computer, it performs a query and returns the results shown in Figure 3.12.


Figure 3.12: Output of schtasks When Run without Parameters

Creating and Running Tasks Using schtasks /Create

You use the schtasks command with the /Create parameter to create new scheduled tasks from the command line. The task you create can be run on any computer and you can specify the username and password that the task will use to run. You also can specify a start time and end time with a predetermined interval, and schedule the task to run every minute, hour, day, week, or month as specified in the optional modifier argument /mo used with the /sc parameter. The syntax of this command is as follows:

schtasks /create /sc ScheduleType /tn TaskName /tr TaskRun [/s Computer [/u [Domain/]User [/p Password]]] [/ru {[Domain/]User | System}] [/rp Password] [/mo Modifier] [/d Day[,Day...] | *] [/m Month[,Month...]] [/i IdleTime] [/st StartTime] [/ri Interval] [{/et EndTime | /du Duration} [/k]] [/sd StartDate] [/ed EndDate]

We describe each parameter in the following sections.

/sc

The /sc parameter specifies the schedule type and its frequency. The schedule types are Minute, Hourly, Daily, Weekly, Monthly, OnIdle, Once, OnStart, and OnLogon. You use this parameter with the /mo, /m, and /d optional parameters, known as modifiers, to specify the exact schedule and interval when the task should run. Table 3.1 defines different types of schedules and modifiers that you can configure.

Table 3.1: Schedule Types and Their Modifiers

Schedule Type

Description

Modifier /mo

Minute

The task runs once a minute by default. You can specify an interval in minutes.

You can set the interval as once every one to 1,439 minutes. The default interval is one minute.

Hourly

The task runs every hour by default. You can specify an interval in hours.

You can set the interval from one to 23 hours.

Daily

The task runs every day by default. You can specify an interval in days.

You can set the interval from one to 365 days.

Weekly

The task runs every week by default on the specified days. You can specify the interval in weeks.

You can set the interval from one to 52 weeks. Optionally, you can use the /d modifier to specify one or more days of week, such as Mon, Tue, Wed, Thu, Fri, Sat, and Sun. By default, the task runs every Monday ( MON).

Monthly

The task runs every month by default on the specified days.

You can set the interval in months from one to 12. You use the /mo LASTDAY modifier to run the task on the last day of the specified month. Optionally, you can use the /m and /d modifiers along with the /mo modifier to specify the months and days of the month. You can set the /m modifier as JAN, FEB, and so on, and the /d modifier from one to 31 days.

Onidle

The task runs when the system is idle for a specified number of minutes. You can specify a date for the task, or the task will run automatically the next time the system is idle.

You can set the time the system should be idle before the task starts. You can set the /I modifier from one to 999 minutes.

The default is 10 minutes.

Once

The task runs only once on the specified date and time.

--

Onstart

The task runs every time the system is started. You can specify a start date, or the task will run the next time the system is started.

--

Onlogon

The task runs whenever some user logs on to the system. You can specify a start date, or the task will run the next time any user logs on to the system.

--

/tn

The /tn parameter specifies the name of the scheduled task. You must specify the task name for every task. It cannot be more than 238 characters in length. If the name includes blank spaces, you must enclose it in quotation marks, (e.g., “System Backup”).

/tr

The /tr parameter specifies the name of the command, script, or application that is to be run on the specified schedule. You must include the complete path of the command, script, or application. The name cannot have more than 262 characters. If you do not specify the complete path, it is assumed that the command, script, or application is located in the default path—that is, %SystemRoot%/System32 folder.

/s Computer

The /s Computer parameter specifies the name or Internet Protocol (IP) address of the remote computer on which the task is scheduled to run. (It is run on the local computer by default.) Optionally, you can use the /u and /p parameters for the username and password of the account that will be used to run the task on the remote computer.

/u [Domain/]User /p Password

The /u and /p parameters specify the username and password, respectively, for the user account that runs the scheduled task on a local or remote computer. When working in a domain, you will need to specify the domain name as well. If the password is omitted, the system will prompt you for a password when the task is run.

/ru {[Domain/]User | System}

The /ru parameter runs the task with the permission of the specified user account. By default, the task takes the permission granted to the current user of the local computer or the user specified by the /u parameter. Alternatively, you can use the SYSTEM account to utilize the local system account that is normally employed to run services on the computer.

/rp Password

The /rp parameter specifies the password for the user account specified by the /ru parameter. If you do not provide a password, the system will prompt you for one. If you are using the SYSTEM option with the /ru parameter, you should not use the /rp parameter.

/mo Modifier

The /mo parameter specifies a modifier for the schedule type parameter, /sc. Modifiers give you granular control over the frequency of scheduled tasks. Refer to Table 3.1 for an explanation of the different types of modifiers.

/m Month

The /m parameter specifies the frequency of the tasks as months of the year. Valid values for Month are JAN, FEB, MAR, APR, MAY, JUN, JUL, AUG, SEP, OCT, NOV, and DEC. This parameter is required only if you are using the LASTDAY parameter.

/i IdleTime

You use the /i parameter when you want to schedule the task to run when the system is idle for a specified number of minutes. The number of minutes can vary from one to 999. You can also set a start date. Otherwise, the task starts running the next time it finds the system idle.

/st StartTime

The /st parameter specifies the time when the task should start on the chosen month, date, or day. You can use it with the ONCE, MINUTE, HOURLY, DAILY, WEEKLY, or MONTHLY schedule. It is required for the ONCE schedule.

/ri Interval

The /ri parameter defines the repetition interval for the task. You cannot use it when you are using the ONCE, MINUTE, HOURLY, DAILY, WEEKLY, or MONTHLY schedule.

/et EndTime | /du Duration

You use the /et and /du parameters only with the MINUTE and HOURLY schedules; they specify the time when the task should end. By default, EndTime is not specified. Optionally, you can specify the duration of the task. EndTime and Duration both use the 24-hour format, HH:MM:SS.

/sd StartDate

/sd is an optional parameter that specifies the date when the task should start. It uses the current date on the local computer by default. The format for the /sd parameter is MM/DD/YYYY. Check with your regional options to specify the correct date format.

/ed EndDate

The /ed parameter is optional; it specifies the date when the task should end. You cannot use it with the ONCE, ONLOGON, ONSTART, and ONIDLE schedule types.

Examples of Using schtasks /Create Effectively

schtasks is one of the most complex command sets available in the Windows Server 2003 operating system. It takes a little while to get used to its different parameters. If at any point in time, you need to review the command parameters or need help using the command properly, you can type Schtasks /? or Help Schtasks at the command prompt. In this section, we have tried to provide you with some examples of how to effectively use the schtasks /Create command.

Scheduling a Task That Runs Only Once

The following command creates a task named “Run Once” and runs the batch file, Mybatch.bat, located in the C:/MyFiles folder on the local computer. The task runs only once, on June 6, 2006 at 6:00 p.m. Note that the task name has a space in it and is enclosed in quotation marks:

Schtasks /create /tn "Run Once" /tr C:/MyFiles/Mybatch.bat /sc once /sd 06/01/06 /st 18:00

If you want the schtasks utility to delete the task when it has completed, you can use the /z parameter. This command is supported only in Windows Server 2003 and not on the Windows XP operating system.

Scheduling a Task That Runs When a User Logs On

The following command creates a task named LogonTask and runs it whenever a user logs on to the system. The task runs the file named Dskchek.bat from the C:/Utilities folder on the local computer. Note that the /sc logon is used as the schedule type option.

Sctasks /create /tn LogonTask /tr C:/Utilities/Dskchek.bat /sc logon 
Scheduling a Task That Runs When the System Starts

The following command creates a task named “Startup Task” and runs it every time the system starts or is restarted. The task runs a file named Dskchek.bat in the C:/Utilities folder on a remote computer named HRSvr02. Note that the /s Computer parameter is used to specify a remote computer and that the schedule type option is used as /sc onstart.

Schtasks /create /tn "Startup Task" /tr C:/Utilities/Dskchek.bat /sc onstart /s HRSvr02
Scheduling a Task That Runs When the System Is Idle for 15 Minutes

The following command creates a task named “Idle Task” and runs a file named Mybatch.bat located in the C:/MyFiles folder on the local computer. Note that the schedule type option is specified as /sc onidle and the /i 15 parameter specifies that the system should be idle for at least 15 minutes before the task starts.

Schtasks /create /tn "Idle Task" /tr C:/MyFiles/Mybatch.bat /sc onidle /i 15

Master Craftsman…Specifying Names with schtasks

You should enclose all names specified with the schtasks command-line utility in quotation marks (“ ”) when there is a space in the name. This includes path names for files and folders. It is not unusual these days to have a file, folder, or computer name with two, three, or more words because most of the newer versions of Windows operating systems support long names. You may omit the quotation marks if the name is spelled as one word. For example, you do not need quotes when writing Myfile or HRServer. But when you use names such as My File or HR Server, you should enclose them in quotation marks: i.e., “My File” and “HR Server”. It is good practice to always use quotes with names, regardless of whether the name contains a space. If for some reason, you forget to enclose the filename or path, the schtasks utility will generate an error when the task is run and will write an entry in the log file.

 

Scheduling a Task That Runs Every 10 Minutes

The following command creates a task named MinTask and runs it every 10 minutes on the local computer. The task runs a batch file named Mybatch.bat from the C:/MyFiles folder on the local computer. Note that the schedule type option is specified as /sc minute and the interval is set at 10 minutes using the /mo 10 modifier.

Schtasks /create /tn MinTask /tr C:/MyFiles/Mybatch.bat /sc minute /mo 10

Now, check the following command, which creates a task to run every 30 minutes starting at 8:00 every night and ending the next day at 7:00 a.m. This command is useful for scheduling a task that should start after office hours and stop before the office reopens. The /st and /se parameters have been used for start and end time, respectively. In addition to this, you can set the /k parameter to stop the task at 7:00 a.m. if it is still running.

Schtasks /create /tn MinTask /tr C:/MyFiles/Mybatch.bat /sc minute /mo 30 /st 30:00 /et 07:00
Scheduling a Task That Runs Every Four Hours

The following command creates a task named MinTask and runs it every four hours on the local computer. The task runs a batch file named Mybatch.bat from the C:/MyFiles folder on the local computer. Note that the schedule type option is specified as /sc hourly and the interval is set at four hours using the /mo 4 modifier.

Schtasks /create /tn MinTask /tr C:/MyFiles/Mybatch.bat /sc hourly /mo 4
Scheduling a Task That Runs Every Day

The following command creates a task named “Daily Task” and runs it every day on the local computer. The task runs a batch file named Mybatch.bat from the C:/MyFiles folder on the local computer. Note that the schedule type option is specified as /sc daily and /sd and /ed parameters are used to specify the start and end dates, respectively. Since we are not using the /mo modifier in this command, the task will run every day with a default value of 1.

Schtasks /create /tn "Daily Task" /tr C:/MyFiles/Mybatch.bat /sc daily /sd 03/01/2006 /ed 09/30/2006
Scheduling a Task That Runs Every 10 Days

The following command creates a task named 10DayTask and runs it every 10 days on the local computer. The task runs a batch file named Mybatch.bat from the C:/MyFiles folder on the local computer. Note that the schedule type option is specified as /sc daily with the modifier /mo 10, which means every 10 days. The /sd and /ed parameters are used to specify the start and end dates, respectively. The /st parameter specifies the time when the job should start.

Schtasks /create /tn 10DayTask /tr C:/MyFiles/Mybatch.bat /sc daily /mo 10 /sd 03/01/2006 /st 12:00 /ed 09/30/2006
Scheduling a Task That Runs Every Week on Wednesday

The following command creates a task named WedTask and runs it every week on Wednesday on the local computer. The task runs a batch file named Mybatch.bat from the C:/MyFiles folder on the local computer. Note that the schedule type option is specified as /sc weekly with the modifier /d wed, which means every Wednesday.

Schtasks /create /tn WedTask /tr C:/MyFiles/Mybatch.bat /sc daily /d wed
Scheduling a Task That Runs Every Alternate Week on Monday and Friday

The following command creates a task named 2WeekTask and runs it every alternate week on Monday and Friday on the local computer. The task runs a batch file named Mybatch.bat from the C:/MyFiles folder on the local computer. Note that the schedule type option is specified as /sc weekly with the modifier /d mon,fri, which means every Wednesday and Friday. The /mo 2 modifier sets the interval at every two weeks.

Schtasks /create /tn 2WeekTask /tr C:/MyFiles/Mybatch.bat /sc weekly /mo 2 /d mon,fri
Scheduling a Task That Runs on the First Day of Every Month

The following command creates a task named “First of Month” and runs it on the first day of every month on the local computer. The task runs a batch file named Mybatch.bat from the C:/MyFiles folder on the local computer. Note that the schedule type option is specified as /sc monthly. Since the /mo modifier is not used, the task defaults to the first day of every month.

Schtasks /create /tn "First of Month" /tr C:/MyFiles/Mybatch.bat /sc monthly
Scheduling a Task That Runs on the Fifteenth of Every Month

The following command creates a task named “Day 15 Every Month” and runs it on the fifteenth of every month on the local computer. The task runs a batch file named Mybatch.bat from the C:/MyFiles folder on the local computer. Note that the schedule type option is specified as /sc monthly. Since the /mo modifier is not used, the default interval of one month is used. The modifier /d 15 sets the task to run on the fifteenth of every month.

Schtasks /create /tn "Day 15 Every Month" /tr C:/MyFiles/Mybatch.bat /sc monthly /d 15
Scheduling a Task That Runs on the Last Day of Every Month

The following command creates a task named “Last Day of Month” and runs it on the last day of every month on the local computer. The task runs a batch file named Mybatch.bat from the C:/MyFiles folder on the local computer. Note that the schedule type option is specified as /sc monthly. The /mo lastday modifier sets the interval to the last day of every month.

Schtasks /create /tn "Last Day of Month" /tr C:/MyFiles/Mybatch.bat /sc monthly /mo lastday
Scheduling a Task That Runs on the Second and Fourth Friday of Every Month

The following command creates a task named “Two Fridays” and runs it on the second and fourth Friday of every month on the local computer. The task runs a batch file named Mybatch.bat from the C:/MyFiles folder on the local computer. Note that the schedule type option is specified as /sc monthly. The /mo second,fourth modifier sets the interval to the second and fourth and the /d fri parameter sets the day to Friday.

Schtasks /create /tn "Two Fridays" /tr C:/MyFiles/Mybatch.bat /sc monthly /mo second,fourth /d fri 

In the preceding command, the weeks of the month have been specified as second and fourth with the /mo parameter. Valid options for this modifier are first, second, third, fourth, and last.

Scheduling a Task That Runs on the Second Friday in March, June, September, and December

The following command creates a task named “Selected Days and Months” and runs it on the second Friday of the months of March, June, September, and December on the local computer. The task runs a batch file named Mybatch.bat from the C:/MyFiles folder on the local computer. Note that the schedule type option is specified as /sc monthly. The /mo second modifier sets the interval to the second and the /d fri parameter sets the day to Friday. The /m mar,jun,sep,dec parameter sets the months to March, June, September, and December, respectively.

Schtasks /create /tn "Selected Days and Months" /tr C:/MyFiles/Mybatch.bat /sc monthly /mo second /d fri /m mar,jun,sep,dec
Scheduling a Task That Runs on a Remote Computer with a User Account

The following command creates a task named “Remote Task” to run every 30 minutes on a remote computer named HR File Server01. The task is run with the username garyb from the Syngress domain. The task starts at 8:00 every night and ends the next day at 7:00 a.m. This command is useful for scheduling a task that should start after office hours and stop before the office reopens. The /st and /se parameters have been used for start and end time, respectively. You can also use the /k parameter to stop the task at 7:00 a.m. if it is still running.

Schtasks /create /tn "Remote Task" /s "HR File Server01" /u Syngress/Garyb /tr C:/MyFiles/Mybatch.bat /sc minute /mo 30 /st 30:00 /et 07:00

In this example, we have not specified a password for the user account. The system will prompt for a password when the task starts. You can add the password using the /p parameter but this is not recommended unless you have created a special user account for the task. You should not use the administrator account or any other account with high privileges to run a scheduled task.

 

Tip 

Different date formats are used in different parts of the world. If you are working for a large multinational organization and are scheduling one or more tasks to run on remote computers located in different parts of the world, you need to be very careful about date formats. Microsoft Windows has three different formats for dates. They are configured according to the Locale settings in the Regional and Language Options in the Control Panel. Windows supports the following three types of date formats:

§        MM/DD/YYYY Used for countries that use the name of the month first, then the date, followed by the year.

§        DD/MM/YYYY Used for countries that use the date first, followed by the name of the month and then the year.

§        YYYY/MM/DD Used for countries that use the year first, followed by the name of the month and then the date.

Before you finalize a script or schedule a task to run your script, you must make sure that the dates in the file conform to the date format used by the remote computer.

Different Forms of the /d Parameter

You might have noticed in the examples given in the preceding section that the /d parameter is used to specify the day. The /d parameter is used only when you use the schedule type /sc as weekly or monthly. It is not a valid parameter for other schedule types such as onlogon, once, or startup. In some examples, we used First, Second, and so on, with the /d parameter, and in other examples we used numbers such as one, two, and 15. This is because the value of the /d parameter changes with the modifier (/mo). Table 3.2 lists valid values for the /d parameter.

Table 3.2: Valid Values for the /d Parameter

Schedule Type

Modifier

Value of Day

Description

Weekly

1 to 52

MON, TUE, WED, THU, FRI, SAT, SUN

This is an optional parameter. If you include an asterisk (*), the task will be performed every day. The default value is MON.

Monthly

FIRST, SECOND, THIRD, FOURTH, LAST

MON, TUE, WED, THU, FRI, SAT, SUN

This value is required if you want the task to run on specific days.

MONTHLY

1 to 12

1 to 31

This is an optional parameter. Use it if you are not using the /mo parameter or are using the /mo parameter with the 1 to 12 value. The default value is 1, which means the first day of every month.

 

 
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值