Microsoft Windows XP Professional Administrators Guide
Windows Shell scripting is easier to learn than the WSH. Windows Shell scripting does not require advanced knowledge of another scripting language, such as JScript or VBScript. Windows Shell scripting is best used to automate tasks that can be performed from the Windows XP command prompt. These tasks can usually be easily automated using Shell scripting and do not require access to the advanced WSH core object model.
Windows Shell scripts are best suited to script tasks that use Windows commands or utilities with command line extensions. Windows Shell scripts are plain text files that contain Windows commands. These files are saved with a .bat file extension and can be run by double-clicking on them or by typing their filename at the Windows command prompt.
The Windows Shell is a text-based interface to the Windows XP operating system. Administrators interact with the Windows Shell using the command prompt located in Command Console as shown in Figure 14.4.
Working with the Windows XP Command Prompt
To display the Windows command prompt and begin working with the Windows Shell, the administrator must open a Command Console by clicking on Start/All Programs/Accessories and then clicking on Command Prompt.
Note | Clicking on Start/Run, typing CMD, and clicking on OK also opens the Command Console. |
In order to work with the Windows Shell, administrators must enter commands at the Windows command prompt. Each command has its own unique syntax that must be closely followed. However, in general, all commands follow a similar syntax, as demonstrated in Figure 14.5.
In general, command syntax is made up of the command followed by one or more arguments that further refine command behavior. An argument can consist of any of the following elements:
-
Parameters. Arguments passed to the command for processing
-
Switches. Arguments that alter command processing in the format of a forward slash followed by one or more characters
-
Modifiers. Arguments that modify switch behavior in the format of a colon followed by one of more characters
For example, the CMD command, which opens a Command Console and displays the Windows command prompt, has the following syntax:
cmd [ [/c | /k] [/q] [/a | /u] [/t:fg] [/x | /y] string]
Windows commands are not case-sensitive. Commands and arguments must be separated by spaces. Any arguments shown inside of brackets are optional. Any arguments located inside brackets but not in italic must be typed exactly as shown. Arguments in italic are placeholders for values that must be supplied by the user. Arguments separated by the | character are mutually exclusive. If an argument contains blank spaces, the entire argument must be placed within double quotes.
Note | For more information on the CMD command, refer to Appendix A, "Windows XP Command Reference." |
Closing the Command Console
The Command Console can be closed like any other Windows application by clicking on the close button in the upper right hand corner of the window. Typing EXIT and pressing the Enter key also closes the Command Console.
Note | The EXIT command is also used within Shell scripts to terminate script execution. |
Modifying the Command Prompt
The command prompt is a text interface to the Windows Shell. By default, the command prompt displays a drive letter followed by a semicolon, a back slash, and the greater-than character to indicate that it is ready to receive input, as demonstrated below:
C:\>
Typing PROMPT followed by one or more arguments changes the format of the command prompt. For example, the following command changes the command prompt to display the day and date.
C:\>prompt $d$g Mon 08/26/2002>
Note | The PROMPT command accepts a number of different arguments, which can be found in Appendix A, "Windows XP Command Reference." |
Changing the Command Console Colors
If desired, the background and foreground colors displayed in the command console can be changed using the COLOR command. The syntax of the COLOR command is:
Color bf
The letters b and f are used to specify alternative colors. For example, the following command changes the command console's foreground color to red and its background color to white.
color 47
Note | The COLOR command accepts a number of different background and foreground arguments, which can be found in Appendix A, "Windows XP Command Reference." |
Changing the Command Console Title
The TITLE command is used to change the text displayed in the Command Console's title bar and has the following syntax:
Title [string]
For example, the following command displays the word "Welcome!" in the Command Console's Title bar.
Title Welcome!
Displaying Text Messages
The ECHO command is used to display text messages in the Command Console. It is also used in Shell scripts to display script output in the Command Console windows.
The syntax of the ECHO command is:
Echo [on | off] [message]
For example, the following command displays a string of text in the Command Console.
C:\>echo Hello world! Hello world!
The ECHO command is used extensively within Shell scripts to display script output.
Typing ECHO OFF in a Shell script prevents the display of the script statements as scripts are processed and only displays command output. Typing ECHO ON reverses this effect.
Clearing the Command Console Display
The CLS command is used to clear any text displayed on the Command Console. Only the Windows command prompt remains. This reduces clutter and makes new command output easier to read. To execute this command, type CLS as shown below.
Cls
The CLS command is often used in Shell scripts to clear the display of the Command Console in preparation for the display of new output.
Modifying the Search Path
The PATH command is used to view and modify the Windows PATH variable. The PATH variable is used to locate commands for processing when the full path to the command is not specified as the path of the command. The syntax for this command is:
path [[drive:]path[;...]] [%path%]
Type PATH by itself to view the current search path, as demonstrated below.
C:\>path PATH=C:\WINNT\system32;C:\WINNT
The search path lists all the folders that the Windows Shell will search for to find the command in order to execute it.
One way to execute a command not located within the search path is to change to its location and run it. Another option is to add its location to the PATH variable, as demonstrated below. To add a new path to the search path, type %path% followed by a semicolon and the new path. For example, the following command adds C:\Temp to the search path.
Path %path%;c:\temp
Creating Shell Scripts
Shell scripts are plain text files that contain Windows commands and are saved with a .bat file extension. They can be created using any editor that can save plain text files, including the Windows XP Notepad application.
Scripts can be as little as one line of code or many hundreds or thousands of lines long. The following procedure outlines the steps involved in using Notepad to create and execute a one-line script that displays a message in the Command Console.
-
Click on Start/All Programs/Accessories and then Notepad. The Notepad application opens.
-
Type the following statement:
Echo This is my first shell script!
-
Click on File and select Save. Specify a file name of test.bat and save the script.
-
Close the Notepad application.
-
Click on Start/All Programs/Accessories and then Command Prompt.
-
Locate the folder where the script was saved, type test.bat, and press Enter.
-
The following output will be displayed.
C:\>test.bat C:\>Echo This is my first shell script! This is my first shell script! C:\>
-
Type Exit to close the Command Console.
Suppressing the Display of Script Statements During Execution
Shell scripts can be modified by reopening them and modifying their contents. For example, the output from the previous example can be cleaned up by appending the @ character to the beginning of the ECHO statement, as shown below.
@Echo This is my first shell script!
When executed, the script's output is shown below.
C:\>test.bat This is my first shell script! C:\>
Alternatively, the ECHO OFF and ECHO ON commands can be used to control script output. Open the script again, remove the @ character, and add ECHO OFF to the beginning of the script.
Clarifying Script Logic with Comments
A one-line script is easy to read, but as scripts grow in size, they can become difficult to understand, particularly if somebody else wrote them. To make scripts easier to read, they should be documented with comments. In Shell scripting, the REM command is used to add comments to scripts, as demonstrated below.
@echo off rem The previous statement turns echoing off rem Display a greeting message echo Good morning!
When executed, this script only displays the greeting message. All other commands are suppressed from display.
Reviewing Shell Scripting Statements
Windows XP Professional supports two types of commands: internal and external. Internal commands are commands that are built into the Windows command Shell. External commands are executable programs stored on the computer's hard drive. Table 14.1 provides a summary of Windows XP Professional's internal commands.
Command | Description |
---|---|
| |
Assoc | Displays and modifies file name extension associations |
Call | A Shell script statement that calls a procedure or external script without terminating the parent script |
Chdir (Cd) | Changes the current folder |
Cls | Clears the Command Console display |
Color | Sets Command Console foreground and background colors |
Copy | Copies files to another folder |
Date | Changes or displays the date |
Del | Deletes files |
Dir | Displays the contents of a folder |
Echo | Enables or disables command echoing |
Endlocal | Ends the localization of variables within scripts and restores previous variable values |
Erase | Deletes files |
Exit | Terminates a Command Console |
For | A Shell script statement that iterates through a set of files |
Ftype | Changes the file extension associated with a file type |
Goto | A Shell script statement that switches processing flow to a line identified with a label |
If | A Shell script statement that performs conditional processing |
Mkdir (Md) | Creates a folder |
Move | Moves files to another folder |
Path | Modifies the Windows search path |
Pause | A Shell script statement that suspends script execution until a key is pressed |
Popd | Changes the current folder to the folder stored by a Pushd command |
Prompt | Modifies the format and content of the Windows command prompt |
Pushd | Changes to a folder and stores the previous folder for later restoration by the Popd command |
Rd | Removes a folder |
Rem | Used to add comments to Shell scripts |
Rename | Renames files and folders |
Rmdir | Removes a directory |
Set | Displays, creates, changes, and deletes variables |
Setlocal | Stores variable values so that they later can be restored by the Endlocal command |
Shift | Modifies the position of parameters in a script |
Start | Opens a new command Shell |
Time | Displays or modifies system time |
Title | Modifies the message displayed in the Command Console's title bar |
Type | Displays a file's contents without opening the file |
Ver | Displays the Windows version number |
The rest of this chapter is devoted to demonstrating how many of the commands listed in Table 14.1 can be used in the development of Shell scripts. This information will provide administrators with the building blocks required to start developing Shell scripts that automate tasks and free them up to work on other opportunities.
Working with Arguments and Variables
An argument is a value passed to a script for processing during its execution. Arguments are passed to a script by typing the script's name followed by one or more values, each of which is separated by a space. Shell scripts assign arguments to parameters, as shown in Table 14.2.
Parameter | Description |
---|---|
| |
%* | Contains all arguments passed to the script (excluding the script's name) |
%0 | The script's name |
%1 | The first argument |
%2 | The second argument |
%3 | The third argument |
%4 | The fourth argument |
%5 | The fifth argument |
%6 | The sixth argument |
%7 | The seventh argument |
%8 | The eighth argument |
%9 | The ninth argument |
The following example shows a script that accepts two arguments and displays their value using a pair of ECHO commands:
@echo off echo action = %1 echo file = %2
Creating and Deleting Variables
A variable is a mechanism used to store a value for later reference within scripts. Variable names are not case-sensitive. The SET command is used to create and delete variables. The SET command has the following syntax.
Set VariableName=Value
For example, the following statement creates a variable name TempFolder and assigns it a value of c:\Temp:
set TempFolder=c:\Temp
Similarly, a variable can be deleted using the SET command by assigning a null value, as demonstrated below.
set TempFolder=
Note | Watch the placement of blank spaces within SET statements. A blank space before the equal sign will be interpreted as a part of the variable name, and a blank space after the equal sign will be interpreted as part of the variable's value. |
Understanding Variable Scope
By default, variables can be referenced from any location with a script, making them global in scope. However, this scope can be limited by localizing variable values using the SETLOCAL and ENDLOCAL commands. When the SETLOCAL command is used within a script, a new variable scope is created that remains in effect until the ENDLOCAL command occurs. When the scope ends, any changes that were made to variables within the new scope are discarded and variable values are reset to their previous value assignments.
The following example demonstrates the application of local variable scope.
@echo off rem Initialize script variables set username=Molly set group=Admin echo %username% echo %group% setlocal set username=William set group=Users echo %username% echo %group% endlocal echo %username% echo %group%
When executed, the following output is displayed, showing the values assigned to the script's two variables are restored to their original values when the ENDLOCAL command executes.
C:\>test Molly Admin William Users Molly Admin
Manipulating Variable Values
As has already been demonstrated, the equal sign is used to assign variable values. Windows Shell scripting also supports a number of other assignment operators, as shown in Table 14.3.
Operator | Description |
---|---|
| |
+= | Add and assign |
−= | Subtract and assign |
*= | Multiply and assign |
/= | Divide and assign |
%= | Modulus and assign |
For example, the following script defines a variable, assigns it an initial value, and then modifies the value assigned to the variable using the add and assign operator.
@echo off set /a unit_count = 10 set /a unit_count +=1 echo %unit_count%
When executed, the script displays the following result:
11
Note | The use of the /a switch after the SET command allows for the use of blank spaces in statements to make them easier to read. |
Windows Shell scripting also supports the assignment of numeric data to variable values. Frequently, numeric values are not known at the beginning of a script's execution and must be computed as the script executes. Table 14.4 lists the arithmetic operators supported by Shell scripting for manipulating numeric variable values.
Operator | Description |
---|---|
| |
+ | Adds two numeric values |
− | Subtracts the second value from the first value |
* | Multiples two numeric values |
/ | Divides the second value into the first value |
% | Determines the value of the remainder in a division operation |
For example, the following statements add two numbers together and assign the result to a variable name unit_count.
set /a unit_count = 5 + 5
Applying Conditional Logic
Windows Shell scripting provides the ability to switch between alternate execution paths based on the value of tested criteria using various forms of the IF statement. Each version of the IF statement tests a different type of criteria, as listed below.
-
IF. Executes a command if a condition evaluates to true
-
IF…ELSE. Provides an alternate execution path if a tested condition evaluates to false
-
IF NOT. Inverts a conditional test
-
IF DEFINED. Tests whether a variable exists
-
IF NOT DEFINED. Tests whether a variable does not exist
-
IF ERRORLEVEL. Tests the exit code from the previous command
-
IF CMDEXTENSION. Tests the Windows Shell's command extension version
-
IF EXIST. Tests for a file or folder's existence
IF
The simplest form of the IF command tests for a true condition. If the condition proves true, an action is taken. The syntax for this statement is:
if condition == value command
For example, the following statement compares the value assigned to a variable to determine whether or not to display a message. In this case, the message will only be displayed if the variable's value is equal to 5.
if %unit_count% == 5 echo Time to order more units
IF … ELSE
The IF…ELSE statement is used to test a condition and then to provide alternate execution paths based on whether the condition evaluates to true or false. The syntax for this statement is:
if condition (command) else (command)
For example, the following statement compares the value assigned to a variable to determine which message to display. If the variable equals 5, the first message is displayed. Otherwise, the second message is displayed.
If %unit_count% == 5 (echo Time to order more units) else (echo Thanks for your order!)
Note | The ECHO commands were placed inside parentheses in order for the Windows Shell to be able to recognize the ELSE portion of the command. |
IF NOT
The IF NOT statement is used to test for a false condition. For example, the following statement compares the value assigned to a variable to determine if it does not equal 5.
if not %unit_count% == 5 echo Thanks for your order!
IF DEFINED
The IF DEFINED statement is used to test whether a variable exists before an attempt is made to reference it. The syntax for this statement is:
if defined variable command
For example, the following statement displays a message only if the variable exists.
if defined unit_count echo The value of unit count is %unit_count%
IF NOT DEFINED
The IF NOT DEFINED statement tests to determine whether a variable does not exist before attempting to define it. The syntax for this statement is:
if not defined variable command
For example, the following statement tests for the existence of a variable, and if it does not exist, the variable is initialized and assigned a value of 0.
if not defined unit_count set /a unit_count = 0
IF ERRORLEVEL
The IF ERRORLEVEL statement is used to test the exit code of the previous command to determine if an error occurred. There are two forms of the IF ERRORLEVEL statement. The syntax for the first form is:
If errorlevel exitcode command
This form of the IF ERRORLEVEL statement tests whether the error code is equal to or higher than a certain value. For example, the following script issues a DIR command to see if any .log files are present in the current working directory. If no .log files are found, an error code of 1 is returned and a message is displayed.
@echo off dir *.log if errorlevel 1 echo No log files were found
The syntax for the second form of the IF ERRORLEVEL statement is:
if errorlevel == exitcode
This form of the IF ERRORLEVEL statement tests for a specific error value. For example, the following statement tests for an exist code of 1 and displays a message if the test evaluates to true.
if "%errorlevel%" == "1" echo No log files were found
IF CMDEXTVERSION
The IF CMDEXTVERSION statement tests the Windows Shell version. Windows XP Professional uses version 2 of the Windows Shell. This provides administrators with the ability to customize scripts based on a determination of the operating system on which they execute. The syntax for this statement is:
if cmdextversion version command
Note | Windows NT Workstation 4.0 uses Windows Shell version 1, and Windows 2000 and XP use Windows Shell version 2 |
For example, the following statement determines whether Windows 2000 or Windows XP is being used to execute the statement.
if cmdextversion 2 echo The statement executed on a Windows 2000 or Windows XP operating system.
IF EXIST
The IF EXIST statement tests for the existence of files, allowing administrators to make sure they exist before attempting to work with them. The syntax for this statement is:
if [not] exist file command
NOT is an optional parameter that inverts the test.
For example, the following statement looks for a file named datafile.txt in the root of the C: drive, and if the file is found, it is deleted.
if exist C:\datafile.txt del c:\datafile.txt
Nested and Multiline IF Statements
Windows Shell scripting provides the ability to place one IF statement inside another, thus allowing for the development of more complicated conditional tests. This technique is called nesting. In addition, Windows Shell scripting also allows multiple statements to be included inside IF statements by placing the statements within a pair of parentheses.
For example, the following script tests for the existence of a file before deleting it and then checks the error code of the delete statement to make sure the operation, if performed, is successful.
@echo off if exist C:\datafile.txt ( del c:\datafile.txt if errorlevel 1 echo Error occurred deleting datafile.txt! )
Looping through Larger Amounts of Data
Part of the real power of Windows Shell scripting is the ability to repetitively iterate through large amounts of information. Windows Shell scripting does this using the FOR command. The FOR command can be used to loop through a number of different types of data, including:
-
Counter-controlled iterations
-
Data strings
-
Output produced by Windows commands
-
Collections of files
-
Collections of folders
-
Data stored in text files
Each of these variations of the FOR loop is examined further in the sections that follow.
Controlling a Loop with a Predefined Counter
The FOR statement can be used to create a loop that iterates a specific number of times based on a starting value, an ending value, and an iteration value. Windows commands can then be executed at each iteration of the loop. The syntax for this version of the FOR statement is:
for /l %%variable in (begin,increment,end) do command
%%variable represents the iterator value. Its initial value is set to begin and it is incremented by the value of increment upon each iteration of the loop until its value exceeds the value specified by end. For example, the following script creates a loop that iterates three times and displays the value of the iterator during each execution.
@echo off for /l %%i in (1,1,3) do echo %%i
When executed, the script displays the following output:
1 2 3
Looping through a String of Data
The FOR statement can be used to create a loop that processes all of the words that make up a string of data. The syntax for this version of the FOR statement is:
for /f ["options"] %%variable in ("string") do command
The possible values for the OPTIONS parameter are defined in Table 14.5.
Option | Description |
---|---|
| |
delims=x | Specifies a substitute for default space and tab delimiters. |
eol=c | Specifies the end of a line comment character. |
skip=n | Specifies the number of lines to be skipped at the top of a file. |
tokens=a,b,a−c | Specifies the tokens used with each iteration. a,b specifies a list of tokens. a−c specifies a range of tokens. |
For example, the following script loops through a string of file extensions and deletes matching files.
@echo off set file_list=*.bak;*.bck;*.tmp;*.old for /f "delims=; tokens=1-4" %%i in ("%file_list%") do (del %%i %%j %%k %%l)
The command delims=; specifies that the entries in the list are deliminated by the ; character. The command tokens=1−4 specifies that the first four elements in the string are to be processed.
Iterating through Command Output
The FOR statement can be used to create a loop that processes the output produced by Windows commands. The syntax for this version of the FOR statement is:
for /f ["options"] %%variable in ('command') do command
Available values for OPTIONS are displayed in Table 14.5. For example, the following script executes the VER command (which displays Windows version information) and displays the version of Windows being used to run the script:
for /f "tokens=3" %%i in ('ver') do (echo This computer is running Windows %%i)
The output of the VER command on a computer running Windows XP Professional is:
Microsoft Windows XP [Version 5.1.2600]
When executed, this statement assigns the value of the third element in the command's output to %%i and displays the following message.
This computer is running Windows XP
Processing a Collection of Files
The FOR statement can be used to process all of the files located within a folder. This provides a powerful file management capability. The syntax for this version of the FOR statement is:
for %%variable in (collection) do command
Collection identifies the type of files to be processed. Multiple file types can be specified by separating each with a blank space. For example, the following statement will delete all the files with a .txt file extension in the currently working directory:
for %%i in (*.txt) do del %%i
Processing a Collection of Folders
The FOR statement provides another powerful file management capability by providing the ability to process all of the folders located within a parent folder. The syntax for this version of the FOR statement is:
for /d %%variable in (collection) do command
The /d switch instructs the FOR statement to process folders instead of files. For example, the following statement will display all the subfolders located in the current working directory:
for /d %%i in (c:\) do echo %%i
Reading Text Files
Windows Shell scripting also provides the ability to use the FOR statement to read and process text files. This allows scripts to collect and process data stored inside reports, configuration files, and logs. The syntax for this version of the FOR statement is:
for /f ["options"] %%variable in (filename) do command
Available values for OPTIONS are displayed in Table 14.5. FILENAME specifies the file to be processed. For example, a FOR loop can be used to process the contents of the following file.
*** Department Emergency Contact List *** Jerry Ford (804) 999-9999 (804) 999-8888 Alexander Ford (804) 888-8888 (804) 888-7777 William Ford (804) 777-7777 (804) 777-6666 Molly Ford (804) 666-6666 (804) 666-5555
When the following FOR statement executes, it skips the first line of the file and then displays the first four tokens (elements) of each remaining line.
for /f "tokens=1-4 skip=1" %%i in (contacts.txt) do echo %%i %%j %%k %%l
When executed, the following output is displayed.
Jerry Ford (804) 999-9999 Alexander Ford (804) 888-8888 William Ford (804) 777-7777 Molly Ford (804) 666-6666
Organizing Scripts with Subroutines and Procedures
Windows Shell scripting provides two mechanisms that can be used to improve the organization of scripts, subroutines and procedures. Both of these programming structures have their own particular set of advantages and disadvantages. For example, subroutines can, by default, access any arguments that were passed to the script, whereas procedures cannot. These and other differences between subroutines and procedures are explained in the sections that follow.
Creating Subroutines
Subroutines are created using the GOTO and LABEL statements. Subroutines have complete access to any arguments that were passed to the script. By default, Shell scripts are processed from beginning to end. However, using the GOTO statement, the processing control of a Shell script can be switched to a different location within a script. A LABEL statement identifies this location. Script execution continues from the label to the end of the script or until another GOTO statement is encountered.
The following example demonstrates the use of the GOTO and LABEL statements in creating a subroutine.
@echo off rem Prompt the user for confirmation before executing choice Do you wish to continue? if errorlevel == 2 goto :EOF if errorlevel == 1 goto :subroutine_1 goto :EOF :subroutine_1 echo: User chose to run the script! goto :EOF
In this example, the script begins executing. The CHOICE command is used to prompt the user as to whether the script should continue its execution. In this example, it displays the following message:
Do you wish to continue?[Y,N]?
Note | The CHOICE command is supplied with the Windows NT, 2000, and XP Resource Kits. |
If the user types an N, the goto :EOF statement is executed. If the user types a Y, the goto :subroutine_1 statement is executed. The goto :EOF statement simulates an end-of-file marker, causing the script to cease execution. This statement can be placed anywhere in a Shell script to terminate script execution. If the user elects to continue script execution, the goto :Subroutine_1 statement causes the script to jump to label :subroutine_1 and continue executing.
Organizing Scripting with Procedures
Windows Shell scripting also supports the organization of scripts into procedures. A procedure is similar to a subroutine. The CALL statement is used to switch processing control from one location to another location as identified by a LABEL statement. Unlike subroutines, procedures return processing control back to the statement following the CALL statement, allowing the script to continue executing from its previous location. In addition, the call statement can be used to execute external procedures by specifying the name of an external Shell script in place of an internal LABEL. When an external procedure is called, the parent script waits for the child script to complete its execution before returning processing control to the statement that follows the CALL statement.
The syntax of the CALL statement is similar to that of the GOTO statement and is shown below.
call :procedure_name
Likewise, procedures are formatted similarly to subroutines, as shown below.
:procedure_name Script statement go here goto :EOF
Arguments can be passed to a procedure, as demonstrated below.
call :procedure_name arg1 arg2 arg3 ......
Unlike subroutines, procedures do not have direct access to any arguments that were passed to a script when it started its execution. However, the following command can be used to pass script arguments to the procedure.
call :procedure_name %*
The following example shows a Shell script that is organized into two procedures.
@echo off rem Place script statements here call :procedure_1 rem Place script statements here call :procedure_2 rem Place script statements here goto :EOF :procedure_1 echo Procedure1 has been processed! goto :EOF :procedure_2 echo Procedure2 has been processed! goto :EOF
Practical Examples
The remainder of this chapter focuses on providing examples of Shell scripts that demonstrate different uses of Shell scripting. By using these examples as templates for more advanced scripts, along with information provided earlier in this chapter regarding the syntax and capability of individual Shell script statements, administrators will be able to write scripts that automate many of their daily tasks.
Creating Logs and Reports
Shell scripts can be used to generate reports and logs and various types of text files. To accomplish this task, Shell scripting provides a pair of redirection operators that take output from one source and redirect it to another source. The > character redirects standard command output to a specified location. For example, the following statement executes the VER command and then redirects its command output into a text file called sample.txt:
ver > c:\sample.txt
This command replaces any text already in the file with the new output. The >> characters can be used to append text to a file without replacing its original contents. For example, the following statement executes the DIR command and appends its command output to the end of a text file:
dir >> c:\sample.txt
The following example script further demonstrates how to generate reports using Shell scripts. In this case, the Shell script generates a report that contains information about the computer's TCP/IP configuration.
@echo off rem Script Name: MakeRpt.bat cls echo Generating the report......... rem Rename report if it already exists and delete archive of report if it exists if exist C:\temp\TCP_report.old del c:\temp\TCP_report.old if exist C:\temp\TCP_report.txt rename c:\temp\TCP_report.txt TCP_report.old rem Display date and time echo Date: %date% > C:\temp\TCP_report.txt echo Time: %time% >> C:\temp\TCP_report.txt echo ---------------------------->> C:\temp\TCP_report.txt rem Display the computer host name echo Hostname: >> c:\temp\TCP_report.txt hostname >> C:\temp\TCP_report.txt echo ---------------------------->> C:\temp\TCP_report.txt rem Display TCP/IP settings echo TCP/IP Settings: >> c:\temp\TCP_report.txt ipconfig >> C:\temp\TCP_report.txt echo ---------------------------->> C:\temp\TCP_report.txt rem text TCP/IP configuration echo Loopback Test: >> c:\temp\TCP_report.txt ping 127.0.0.1 >> C:\temp\TCP_report.txt cls echo TCP/IP report has been generated and can be found in C:\TEMP.
The script makes use of a number of different techniques to improve the presentation of the script and its report. It begins by using the CLS command to clear the Command Console's display. Next, it checks to see if an old copy of the report already exists (for example, c:\temp\TCP_report.old), and if it does, the report is deleted. The script then checks to see if a current copy of the report exists, and if it does, it renames the file to allow for the generation of a new report. The script then writes the current system date and time to the report by displaying system variables that contain this information and redirecting them to the report file. Next, the HOSTNAME variable is displayed. This variable displays the TCP/IP hostname assigned to the computer. The final two commands executed in the script display the computer's TCP/IP settings and perform a ping of its diagnostic loopback address. The script then ends after displaying a message that states the location of the report.
The following output shows an example of a report generated by this Shell script:
Date: Thu 08/29/2002 Time: 23:47:37.17 ---------------------------- Hostname: DeptFileSvr ---------------------------- TCP/IP Settings: Windows IP Configuration Ethernet adapter Local Area Connection: Connection-specific DNS Suffix . : ce1.client2.attbi.com IP Address. . . . . . . . . . . . : 192.168.1.101 Subnet Mask . . . . . . . . . . . : 255.255.255.0 Default Gateway . . . . . . . . . : 192.168.1.1 ---------------------------- Loopback Test: Pinging 127.0.0.1 with 32 bytes of data: Reply from 127.0.0.1: bytes=32 time<1ms TTL=128 Reply from 127.0.0.1: bytes=32 time<1ms TTL=128 Reply from 127.0.0.1: bytes=32 time<1ms TTL=128 Reply from 127.0.0.1: bytes=32 time<1ms TTL=128 Ping statistics for 127.0.0.1: Packets: Sent = 4, Received = 4, Lost = 0 (0% loss), Approximate round trip times in milli-seconds: Minimum = 0ms, Maximum = 0ms, Average = 0ms
Creating User Accounts
Shell scripts can also be used to assist in the administration of user and group accounts. Windows XP Professional supplies a number of commands that allow user and group accounts to be managed from the command line. These commands include:
-
NET USER. Displays and creates user accounts
-
NET LOCALGROUP. Administers local groups
-
NET GROUP. Administers global groups
-
NET ACCOUNTS. Administers password policies
The following Shell script demonstrates how to create local user accounts and add them to the local administrators group. The script is named MakeUser.bat and is run by typing its name, a space, and then the username to be created.
@echo off rem Script Name: MakeUser.bat rem Only allow script to run on NT, 2000 or XP if not "%OS%" == "Windows_NT" goto :exit rem Modify the text displayed in the Command Console titlebar title "Account creation script" rem Clear the display cls rem Ask user to confirm script execution echo This script will create a new user account for: %1%. echo To Continue press any key or press CTRL + C to abort. echo . pause rem Call procedure to create the new account call :create_account %1% rem Call procedure to add account to the local administrators group call :add_to_admins %1% goto :EOF :create_account echo Creating new user account for %1% rem create the local user account net user %1% * /add goto :EOF :add_to_admins rem Add the user account to the local Administrators group net localgroup Administrators /add %1% goto :EOF :exit echo This script can only run on Windows NT, 2000 or XP
The script begins by checking to see what operating system is being used to execute the script. Shell scripts are only supported on Windows NT, 2000, and XP. The %OS% variable will contain a value of Windows_NT if any of these operating systems is being used. If the test proves false, the :exit subroutine is executed. This subroutine terminates script execution.
Next, the script modifies the title of the Command Console titlebar. It then prompts the administrator for confirmation before continuing using the PAUSE command. To continue, the administrator must press any key. To abort account creation, Ctrl+C must be pressed.
The next two script statements call two procedures. The first procedure is passed the script's only argument (for example, username), which is then used to create the user account. The second procedure is passed the same argument, which it uses to add the user account to the local administrators group.
The following output demonstrates the output that is produced if the script is run and passed a username of Sue.
This script will create a new user account for: Sue. To Continue press any key or press CTRL + C to abort. Press any key to continue . . . Creating new user account for Sue Type a password for the user: Retype the password to confirm: The command completed successfully. The command completed successfully. C:\>
Scheduling Disk Maintenance Scripts
Using the Windows scheduling service Shell, scripts can be set up to run at times when the user is not logged on to the computer. For example, the following Shell script is designed to run the defrag.exe command, which defragments hard disk drives. It also saves a report that summarizes the work done by the defrag.exe command.
Note | For information on how to set up the scheduled execution of a script, refer to "Scheduling Tasks with the Scheduled Task Wizard" in Chapter 4, "Application Management." |
@echo off rem Script Name: DiskMaint.bat rem If a defrag.txt report exists delete it if exist C:\temp\defrag.txt del c:\temp\defrag.txt rem Create a new defrag.txt report echo Defragging C: at %time% on %date% > c:\temp\defrag.txt rem The defrag command cleans up disk fragmentation defrag c: /f >> c:\temp\defrag.txt
The script begins executing by checking to see if a previous output report exists, and if it does, it is deleted. Next, a new report is started and the current system time and date are written to it. The DEFRAG command is then executed. The/ f switch is used to force the script to run without prompting for confirmation. The command's output is then written to a report file.
The follow output demonstrates a typical report generated by this script.
Defragging C: at 23:07:03.11 on Thu 08/29/2002 Windows Disk Defragmenter Copyright (c) 2001 Microsoft Corp. and Executive Software International, Inc. Analysis Report 2.00 GB Total, 164 MB (7%) Free, 21% Fragmented (24% file fragmentation) Defragmentation Report 2.00 GB Total, 164 MB (7%) Free, 10% Fragmented (16% file fragmentation)
Remote File Administration
This final Shell script is designed to connect to remote network computers using the NET USE command and to copy all .log and .bak files found in each remote computer's c:\temp folder to a folder located on the local hard drive. All files stored in each remote computer's c:\temp folder are then deleted and the drive mapping is terminated.
@echo off rem Script Name: FileMaint.bat cls rem Map the C: drive on computer_1 net use x: \\computer_1\c rem Copy .log & .bak files to folders on the local computer copy x:\temp\*.log d:\LogArchive copy x:\temp\*.bak d:\BackupFiles rem Delete all files in the temp folder on computer_1 del /Q x:\temp\*.* rem Disconnect the drive mapping to computer_1 net use x: /delete rem Map the C: drive on computer_2 net use x: \\computer_2\c rem Copy .log & .bak files to folders on the local computer copy x:\temp\*.log d:\LogArchive copy x:\temp\*.bak d:\BackupFiles rem Delete all files in the temp folder on computer_2 del /Q x:\temp\*.* rem Disconnect the drive mapping to computer_2 net use x: /delete