command prompt procedures set
intro
In this chapter, you take a look at several command prompt utilities and a few graphical utilities. Even in the age of Windows, statements that can be issued from command prompt are still required knowledge for support professionals. This knowledge will help you automate processes — such as batch files — and solve problems when the graphical operating system is not functioning. After reading this chapter, you should have a good understanding of many of the basic commands that are available from the command prompt. As an added benefit, you find out how to build a basic batch file with some controls in it. I put this information at the end of the chapter because you won't be tested directly on that knowledge, but it will sure come in handy on the job. As an A+ Certified Professional, you will want to use the full range of tools that are available to you. This chapter introduces you to many of the command- line tools that allow you to quickly diagnose and repair problems with operating systems. Using command.com and cmd.exe Just as many utilities in Windows 9x are command-line-based, many of the really useful utilities in Windows 2000 and Windows XP are command-linebased. Windows 2000 and Windows XP give you two options for running command-line utilities: command.com and cmd.exe. 614 Using command.com and cmd.exe When you worked with MS-DOS and Windows 9x, the file command.com was the command-line interpreter, and it served as the basic method of executing programs in the OS. Some of the programs that were executed were programs internal to command.com, while others were external and could be found on the hard drive. Windows NT-based OS, like Windows 2000 and Windows XP, use cmd.exe as the basic command-line interpreter for issuing commands. When using cmd.exe, you are using a Windows 32-bit application from the point of view of memory management and application stability. command.com still exists on these operating systems, but it exists for backward compatibility for older applications. Typically, when you want to use a command prompt within Windows XP, you should run cmd.exe by choosing Start➪Run, typing cmd.exe and clicking OK. cmd.exe can also be found in the Start menu under All Programs➪ Accessories➪Command Prompt. This runs as a 32-bit Windows application and thereby can spawn other applications or support standard memory management. Each copy of cmd.exe that you execute appears on the process list in Task Manager. If you run cmd.exe, the first two lines tell you what has executed: Microsoft Windows XP [Version 5.1.2600] (C) Copyright 1985-2001 Microsoft Corp. command.com on the other hand, is a 16-bit MS-DOS application. It loads a simulated 16-bit environment in the form of ntvdm.exe (NT Virtual DOS Machine). You will see ntvdm.exe listed on the process tab in Task Manager. The first two lines that will be listed in this window are: Microsoft(R) Windows DOS (C)Copyright Microsoft Corp 1990-2001. You will notice that, in this case, you are running DOS and Windows XP. You will also notice that your long filenames are no longer supported. If you use the command prompt to launch other 16-bit Windows applications, then they will be launched within the NTVDM that is executing. The NTVDM is the environment that all 16-bit MS-DOS applications and 16-bit Windows applications run in. For more information about supporting these applications, refer to Book VI, Chapter 2. cmd.exe is used when running all other applications. It is a 32-bit command prompt with a number of enhancements, including: ✦ The ability to run 16-bit and 32-bit command-line utilities ✦ The ability to run Posix and OS applications ✦ Built-in doskey support for saving and executing commands Book V Chapter 5 Command Prompt Procedures Managing Directories 615 Windows 2000 and Windows XP use cmd.exe as the main command-line interface and provide command.com for backward compatibility. Managing Directories All files that are saved on a disk are stored in a hierarchical directory structure. All the files could be placed at the top of this structure, but it would be disorganized, and therefore poorly managed. Also, most top-level directories, or root directories, can hold a limited number of files. This directory structure can hold as many nested subdirectories as you want. The commands discussed in the following sections let you get listings of files as well as create and delete directories on your disk. dir The first command that you will see is the directory command (dir). This command is used to get a listing of the files that are in a directory on your disk. Typing dir by itself gives you the listing of your current directory. The current directory is usually listed in the command prompt, like this: C:\WINDOWS\COMMAND>_ The dir command is very useful and has several options that are discussed later in this section. First, though, you need a firm grasp of wildcards, relative paths, and absolute paths. Two wildcards can be used to modify what results you are given back: * and ?. The * represents one or more characters. Here is an example of its usage to retrieve a list of files that match a certain pattern. The command dir WIN*XE returns the following: WINMINE.EXE WINHELP.EXE WINHLP32.EXE WININIT.EXE WINVER.EXE WINFILE.EXE WINPOPUP.EXE WINIPCFG.EXE WINREP.EXE The results include all files that start with win and end with xe, with any number of characters in between — even zero. These wildcards are also useful with copy commands, which I discuss later in the chapter. 616 Managing Directories The ? works a little different than the * because it represents one or zero characters. Here is an example of the ? in action, as it looks for all files that were created on the fifth of any month after Jan 01, 2000. The command dir ??052???.TXT would return the following list of files: 1052000.TXT 5052000.TXT 10052000.TXT 11052000.TXT 12052000.TXT 4052002.TXT 12052003.TXT 6052008.TXT The ? in the command doesn't return any files that have more than two characters before the 05 and doesn't return any more than three characters after the 2 in the dir statement. This is often helpful when files in a directory are named with six- or eight-character numeric dates with the pattern of mmddyyyy. txt, and you are looking for all of the files that are named for the fifth of any month. When you type dir, you are given a directory listing for your current directory. If you want to see the listing for a different directory, Table 5-1 provides several options for choosing a different directory. All the command examples in the table use the c:\parent_dir\child_dir\grandchild_dir directory structure, with the current directory set to c:\parent_dir\child_dir. Table 5-1 Ways to Specify Directory Paths Command Directory Result dir Returns the listing for the current directory, c:\parent_ dir\child_dir. dir c: Returns the listing for the current directory on the C drive c:\parent_dir\child_dir. dir c:\parent_dir Returns the listing for c:\parent_dir. dir \ Returns the listing for the root of the current drive c:\. dir .. Returns the listing for the parent directory of the current directory c:\parent_dir. dir ..\.. Returns the listing of the parent directory of the parent directory of the current directory c:\.. dir ..\child_dir Returns the listing of a directory named child_dir, which is a child of the parent directory c:\parent_dir\child_dir. Book V Chapter 5 Command Prompt Procedures Managing Directories 617 Command Directory Result dir grandchild_dir Returns the listing of a child directory named grandchild_dir, c:\parent_dir\child_dir\ grandchild_dir. Whenever a full path is specified, starting with the drive letter, it is referred to as an absolute path. If you do not specify the full path, you are using a relative path. Care should always be taken when using relative paths with commands. Look, for example, at the following code sample: dir sub_dir del *.* In this example, a directory listing is taken of asubdirectory, while the following delete command was working on the entire contents of the current directory. This is an easy mistake to make. When working with relative paths, the double period (..) notation refers to a parent directory, and the single period (.) refers to the current directory. Most programs and commands can have their actions modified by providing options on the command line. These options are usually represented by one or more letters and are introduced to the command with either / or -. The - is usually used with commands that come from (converted from) the UNIX OS, while most MS-DOS programs have implemented the /. These options are referred to as switches. dir /on /s is an example of the dir command using switches. Table 5-2 summarizes some of the most important switches for the dir command. Table 5-2 Switches for dir Switch Description /ax The /a switch is short for "attributes." This switch provides a listing of files that have matching attributes. This switch must be used in conjunction with an additional letter to provide results. There are five letters that may be used: (d)irectory, (a)rchive, (h)idden, (s)ystem, and (r)ead-only. Using a minus sign with any five of the letters to reverse the listing, for example, /a-d, shows you things that are not directories. /b The /b command displays a bare listing. The bare listing does not include a separate section in the output that tells you the directory that you are working with, but rather displays a single-line listing, like this: c:\windows\hosts.txt c:\windows\lmhosts.txt (continued) 618 Managing Directories Table 5-2 (continued) Switch Description /ox The /o switch is short for "order by." This switch is similar to /a in that /o by itself will not work; it requires an additional letter to tell it how to order or sort. The options that are available for sorting are: (n)ame, (s)ize, (e)xtension, (a)ccessed date — earliest first — and (d)ate modified — earliest first. If you use a minus sign (for example, /o-d), the order is reversed. If you use the letter g after the o (for example, /ogd), then directories will be grouped at the top of the list rather than mixed in. /p This switch pauses the screen after each full screen of text and waits for a key to be pressed. If you do not use this option, you can use the pipe-more command, which looks like this: dir c:\windows\*.exe | more. /s This switch will include listings for each subdirectory under in the directory listing. /w This switch will display the text in a wide listing. It enables more text to be displayed on a screen by using multiple columns. /x This switch is used on Windows 2000 and Windows XP computers to display the short filenames, as well as the long filenames. If you want to use the same set of switches each time you execute the dir command, you can use the dircmd environment variable. This variable can be set in the autoexec.bat file or at a command prompt, like this: set dircmd=/on /w Now, every time you type dir, you will get output that looks like this: Volume in drive D is DRIVE_D Volume Serial Number is FFFF-FFFF Directory of D:\DOS [.] [..] CHOICE.COM DELTREE.EXE DOSHELP.HLP DOSKEY.COM EXPAND.EXE FC.EXE FDISK.EXE HELP.COM HELP.HLP HIMEM.SYS INTERLNK.EXE INTERSVR.EXE LOADFIX.COM SMARTDRV.EXE TREE.COM 15 File(s) 525,943 bytes 2 Dir(s) 446,431,232 bytes free You should note that the list is presented in wide format and sorted by name. If you are using Windows 2000 or Windows XP and you want the setting of the dircmd variable to be saved, then you should add the variable by using the Environment Variables settings in the System Control Panel, which you can get to using Start➪Control Panels➪System, to open the System Properties dialog box; then click the Advanced tab and the Environment Variables button. Book V Chapter 5 Command Prompt Procedures Managing Directories 619 mkdir mkdir, or md, is used to create directories; there is no difference between the two commands other than their spelling. Many of the commands that are used with MS-DOS originated in other operating systems, and in some cases, new short forms were created to make them easier to use. In an effort to provide backward compatibility, support for the older spelling of the command was also kept. The directory created will be in the current directory unless you provide an alternative path to the command, like this: mkdir "c:\temp\my new directory" chdir chdir, or cd, is used to change the current directory for a drive to another directory. The drive need not be your current drive; this command can set a current directory on another drive. For example, if your current drive is C:, you could still type cd d:\my_dir_on_d to change the current directory for the D: drive. You will not see a difference on your screen, but if you change to the D drive by typing d:, you will see that the current directory is set to d:\my_dir_on_d. The current directory is important when you want to use other file operation commands, such as copy. If you only specify the drive that you want to work with, then you will be working with the current directory on that drive. Take a look at this example: C:\Documents and Settings\ed\>c: C:\>cd \ C:\>mkdir d:\old_configs C:\>cd d:\old_configs C:\>copy a*.bat d: C:\>copy c:\c*.sys d:\old_configs The first line changes your current drive to C:. The second changes to the root directory of the current drive (c:\). The third creates a new directory on the D: drive, and the fourth line sets old_configs as the current directory on the D: drive. You will see the copy command in the section "copy," later in this chapter, but the fifth line copies all files in the current directory that start with a and end with .bat to the current directory on the D: drive (currently old_configs). The last line copies all files from c:\ that start with c and end with .sys to d:\old_configs. Lines 5 and 6 copy files from the same directory (c:\), while the relative path is used in line 5 and the absolute path is used in line 6. The destination directory in line 6 is also absolute, while the relative path or current directory is used in line 5. In both statements (lines 5 and 6), the same directories are used as the source and destination directories. Relative paths can save on typing, but they can also cause errors if you are not careful. 620 Copying and Moving Files rmdir rmdir, or rd, is used to remove or delete directories from your drive. Two rules are imposed on you: Before you delete a directory, the directory must be empty, and it cannot be the current directory. You can empty a directory by using the del command to delete the files. To remove a directory, just specify its location after the rmdir command: rmdir c:\remove_me If you are using Windows 2000 or Windows XP, there is an optional switch, /s, that will automatically delete subdirectories and files. All of the command-line tools in this section have not changed substantially since MS-DOS. Copying and Moving Files Doesn't it seem like when you finally get things organized, it's time to start all over again? When organizing and backing up files, you will often be required to copy or move files to new locations, either in another directory or on another disk. The following sections provide an overview of the commands that let you do this. copy The copy command expects you to give at least the name of the file you would like to copy. If you provide only one filename, then the selected file is copied into the current directory. If you provide a source filename and a destination directory by using a command like copy c:\source\myfile.txt c:\destination then the file will be copied into the destination directory. You can also rename files while you are copying them by using a command like this: copy c:\source\*.bat c:\destination\*.old The previous command would copy all of the files with an extension of .bat from the source directory and rename them with an .old extension in the destination directory. If you are about to overwrite an existing file, you will be prompted to confirm the operation. This can be suppressed if you use /Y at the end of your copy command. /Y answers "yes" to the copy command's confirm overwrite Book V Chapter 5 Command Prompt Procedures Copying and Moving Files 621 questions. If you want to consistently overwrite destination files, you can set the copycmd environment variable to /Y in the same manner that you set the dircmd variable in the "dir" section, earlier in this chapter. xcopy Many times, you will have to copy entire directory structures from one location to another. If you were to do this with the copy command, you would first have to create all of the destination directories by using the md command. With the xcopy command, you can perform this task in a minimal amount of time. To copy an existing directory named source to a new directory named destination, you would type the following command: xcopy c:\source\*.* c:\destination\*.* If you wanted to copy all the subdirectories as well, you would use: xcopy c:\source\*.* c:\destination\*.* /s To also include empty directories, add /e (empty) to the end of the command. To include just files with the archive attribute set, add the /a (archive) switch. Like the copy command, adding /Y will overwrite files without asking for confirmation. The /Y tells the command to answer "yes" to all overwrite prompts. move The move command moves files from one directory to another. It is also used to rename directories. To use the move command, you have to specify the name of the files you want to move and then specify the destination directory, like this: move c:\source\source_file.txt c:\destination\ This example moves the file source_file.txt into the directory c:\ destination\. If the destination directory does not exist, then you will see an error message. If you want to rename the directory c:\source, you use: move c:\source destination
more
Locating a command When you type a command at a command prompt, in a batch file, or at the Run command, your computer follows a set of steps to locate the command. The steps include: 1. The computer checks the current directory for the command. 2. If the command is not found in the current directory, the computer checks all directories listed in the Path environment variable. If the command is not located, possibly because you misspelled it, then you see the following message: Bad command or file name If you see this message, check the spelling of the command and try again. The path variable can be set in the autoexec.bat file for all Microsoft operating systems. It is the only environment variable that can be set without using the set command. To set the path variable, you can use either set path = c:\windows;c:\windows\system or path = c:\windows;c:\windows\system The only advantage to the latter is that it uses four fewer keystrokes. If both c:\windows and c:\windows\system are in the path, then they will be checked when a command that is typed is not in the current directory. Windows 2000 computers provide an additional location for setting the path environment variable. To change the path on a Windows 2000 computer, open the System Control Panel, click the Advanced tab, and click the Environment Variables button. You can use the Environment Variables dialog box to modify the path for the computer. 638 Getting an A+ Putting it together The following is a short batch file that has been documented with rem or remark statements throughout the file. It shows a completed file that uses many of the techniques discussed in this section. This batch file was designed to gather the TCP/IP configuration from a computer and place it in a text file on the C: drive; but it could place the information on a drive on a server so that it could be collected by an administrator. The text file that the batch file creates is named for the computer information from which the information was gathered. This data is collected only once. The networking troubleshooting commands used in this file can be found in Book IX, Chapter 3. rem Check for existing file, and if it exists, exit the batch file, rem and make the directory if it does not exist. if not exist C:\IPSettings\nul mkdir C:\IPSettings if exist C:\IPSettings\%computername%.txt goto end rem Check to see if the computer is running Windows 9x rem or Windows NT style OS. if not !%OS%==!Windows_NT goto Win9x :WinNT rem Create a new file containing the output of ipconfig.exe rem which is the current TCP/IP Configuration. ipconfig /all > C:\IPSettings\%computername%.txt rem Add to this file the current routing table using netstat.exe netstat.exe -R >> C:\IPSettings\%computername%.txt rem Skip the Windows 9x section and goto the end of the file. goto end :Win9x rem Use Windows 9x compatible versions of the Windows NT commands rem networking commands. winipcfg /all /batch C:\IPSettings\%computername%.txt netstat.exe -R >> C:\IPSettings\%computername%.txt :end If this file is saved to C:\Windows\GetIPSettings.bat, it can be executed by specifying the name of the file GetIPSettings in a command window or by typing it after using Start➪>Run. By specifying the name, the entire path on your computer will be searched for the file with either .com, .exe, .cmd, or .bat as the file extension. Getting an A+
more
There are two ways to navigate the Open dialog window. First, you can use the Alt key on the keyboard. You will notice white letters in several places in the dialog box. By pressing Alt and a white letter, you will be able to go to a section of the dialog box. For example, pressing Alt+D moves the cursor to the Directories pane, and pressing Alt+F moves it to the Files pane. You can use the arrow keys on your keyboard to scroll through either of these lists and use the Enter key to select choices. The first entry in the Directories pane is .. to navigate to the parent directory, and the last entries in that pane are all of your drive letters, to switch to different drives. The second way to navigate from pane to pane in this dialog box is to use the Tab key. If you press the Tab key in succession, you will move through the panes, fields, and buttons from left to right, top to bottom. The exact order for this dialog would be: File Name, Files, Directories, Open Read-only, Open Binary, OK, Cancel, Help. By holding the Shift key while tabbing, you move in reverse order. To select the check boxes, press the spacebar when the option is highlighted. When the correct file has been selected, you can press Enter or select the OK button to open the file. Saving files Saving files also requires that you first get access to the menu bar by pressing the Alt key. Alt+F opens the file menu, Alt+S saves, and Alt+A opens the Save As dialog box. If the file has already been saved, then saving updates the original; but if the file has never been saved, then either saving option opens the Save As dialog box, shown in Figure 5-2. This dialog box is similar to the Open dialog box with regard to navigation. After you select a directory and provide a name, select the OK button. Figure 5-2: When saving, choose a location and then a filename. 630 Working with the edit Command Searching and replacing One of the more powerful features of edit is its ability to search and replace text in your file. To perform a search and replace, press the Alt key to access the menu, and then press S to access the Search menu. The Replace dialog box (shown in Figure 5-3) can be opened by pressing R. You can then type the string that you are looking for, as well as the string that you would like to replace it with. To narrow down the search, you can also tell the editor to search only whole words and to match the case. Searching for whole words means that when you search for cat, for example, you will not find it as part of the words cats or categories. Matching case means that cat would not be found if you were searching for Cat. Closing the editor To close the editor, press the Alt key; then press F for File and X for Exit. If you have unsaved changes, you are prompted to save your changes, as shown in Figure 5-4. Figure 5-4: If there are unsaved changes, you are prompted to save them. Figure 5-3: Search and replace is a powerful feature. Book V Chapter 5 Command Prompt Procedures Batch File Basics 631 Batch File Basics You now know several basic commands that make the command prompt easier to use — as well as a powerful ally. In the following sections, you find out how to write a batch file, which makes the command prompt an even more powerful tool. A batch file is simply a string of commands, which could have been typed at a command prompt, chained together to automate a process. Starting your file To start things off, you need a place to put the commands that you want to execute, and, to do this, you need to make a new text file and save it with a .bat extension. Open the text editor of your choice and create a new file; then save your file with a .bat extension. If you're using a Windows-based editor, such as Notepad and the operating system option of Hide File Extensions for Known File Types is still enabled, you will have to enclose your filename in quotation marks when saving it. If you want to show or hide your file extensions, use the following steps: 1. Open My Computer. 2. Choose Tools➪Folder Options. 3. Click the View tab. 4. Clear (to show) or check (to hide) the box next to Hide File Extensions for Known File Types. 5. Click OK. With your batch file open in the text editor, you can now type any commands you want, but remember to put only one command per line in your file. You can use this file to create, copy, or delete files, or anything else that you could do from the command prompt. Once you have created a batch file, you can execute or run it by typing the path to file and the filename at the Start➪Run command or at a command prompt. It is best to do some testing with the batch file on a test computer — I have seen people create batch files with improperly formatted rmdir commands, which then deleted many more files and directories than expected. If you use commands that format partitions, remove files, or delete disk partitions, note that poorly structured commands may result in you being required to reinstall the operating system on your computer. The commands suggested in this section are not dangerous. 632 Batch File Basics Getting your directions Many people want to be able save the output of their commands, or more rarely, answer questions or provide input for a command. There are a few ways to do this, and Table 5-4 summarizes the differences among the options. All of these options require that your program is generating output going to stdout (standard output) or accepting input from stdin (standard input). stdout and stdin are interfaces or objects that C programmers use almost exclusively when requiring data input and output for command-line programs. As a programmer, I can write an application that sends its output to an interface called stdout, and then I let the operating system deal with where that actually is, as it might be a teletype terminal, a printer, a monitor, or a text file. For Windows XP, data that is sent to stdout will be displayed in a command prompt window. Table 5-4 Redirection Symbols Symbol Function < Sends the contents of a file listed on the right into the command on the left. This is useful when you want to provide an answer to a question that a command will prompt for (for example, when the format command prompts for confirmation). By creating a one-character text file with just Y and a return, you will be able to pass a yes into the format command. > By specifying a command on the left and a text file or nul on the right, you can prevent output of a command from going to the screen. Instead, the output will be passed to the file that is listed on the right side. If the file exists, it will be overwritten. This is extremely useful if you want to log the results of certain statements. >> Similar to the > symbol except that the output is appended to the destination file if it already exists. If the file does not exist, it will be created. | Referred to as a pipe. It pipes or directs the output of the file that is listed on the right side into (as input) the command that is listed on the left. This may allow you to bypass the creation of a text file. Working with parameters or starting arguments You can get a lot more mileage from your batch files if you pass and use arguments with them. An argument is a piece of data that is passed to the batch file or command when typing the command, such as copy C:\this. txt C:\that.txt, which has two arguments: C:\this.txt and C:\that. txt. There are ten arguments that you can use with a batch file. This really drops off to nine because the first argument is %0, and that represents the name of the running batch file. %1 through to %9 can be used as arguments for your batch file. If you have created a batch file that copies files from one directory to another, you can make your batch file more reusable by working with arguments. Here is an example of this concept: Book V Chapter 5 Command Prompt Procedures Batch File Basics 633 Old batch file — StaticCopy.bat: xcopy c:\dos\*.* c:\dosback This file could be made more generic with these modifications: New batch file — DynamicCopy.bat: xcopy %1 %2 This new batch file would be run by typing: dynamiccopy c:\dos\*.* c:\dosback It's true that you are typing more to achieve the same result. But you have to consider that this line could be in a much larger batch file, which could use the two parameters (%1 and %2) in many different ways. This could actually save you a lot of typing when creating and editing your batch file because the parameters can be used rather than hard coding the paths or parameters. This system works fine until you find yourself in a position in which you need more than nine parameters passed to your batch file. However, if you plan the order in which you use your parameters, you can actually support many more than nine. This is done with the shift command. Each time you use shift in your batch file, all of the parameters that are passed to your batch file are shifted over one position. For example, %2 becomes %1, %3 becomes %2, and so on. Making batch files make decisions So far, you have seen some ways to make your batch file more generic. Now, I'll show you how to make it think for itself, or at least think for you. There are two ways to get your batch file to make some decisions, although after you've read this section, you may argue that there is only one way, since both ways make use of batch file labels. First, the if and :label statements introduce simple program flow logic. For example, if you know that you need two parameters passed to your batch file for it to work properly, then you can use something like this in your batch file: if not !%2==! goto correct :Instructions echo. echo Please provided two parameters. The first is the echo source directory, and the second is the destination. echo. 634 Batch File Basics goto end :correct xcopy %1 %2 goto end :end When working with the if statement, you evaluate whether two options are the same or whether a condition is true. In this case, you are testing for two items being equal, and, in order to do this, you need two items — you cannot test equality with only one item. In this example, you want to see if the second parameter is blank, so you use %2, which represents the second parameter; but you aren't able to use if not %2==, as this would evaluate %2 to nothing, and you need something on the other side of the equation. This gets worse if the second parameter was not passed to the batch file, as %2 will not exist, and you are then asking if nothing equates to nothing. The if statement cannot handle evaluating nothing in an equation. In order to make sure there is something to evaluate on both sides of the equation, and not change the results, you need to add a character to both sides of the equation. In this example, I chose to use the exclamation mark. You should also take note of the use of the word not to reverse the results of the test. Some other items that the if statement can test for includes OS environment variables and whether files and directories exist. To test an environment variable for a specific value, you use a command like this one that checks the name of the computer that is running the batch file: if !%COMPUTERNAME%==EDSPC goto instructions To test if a file exits, you use something like: if exist c:\autoexec.bat goto Instructions If you want to know if a directory exists, you can test for nul, which only exists for your test if a directory is there. if exist c:\windows\nul goto Instructions The full example also shows you how to work with labels and the goto statement. The goto statement uses only the first eight characters of the label, so try to keep label names unique. The goto statement requires a destination in the batch file to be sent to, and that is where the labels come in. Although end is a label that is meaningful to you, to the batch file it is just another label. Remember, if you use a goto in your batch, you must have a matching label or you will get errors and your batch file will not work. Book V Chapter 5 Command Prompt Procedures Batch File Basics 635 The last method of controlling the flow of your batch file is using the choice or set statement. The choice statement allows you to pause your MS-DOS or Windows 9x batch file to wait for input. Input to the choice statement is a single character. Here is an example of how to use the choice statement: @echo off choice /c:ynm You choose if errorlevel == 3 goto m if errorlevel == 2 goto n if errorlevel == 1 goto y goto end :y echo You chose Yes. goto end :n echo You chose No. goto end :m echo You chose Maybe. goto end :end The choice statement uses the list of parameters after the /c: to listen to input. One of those choices must be provided. The choice statement will actually ignore any other input and wait for one of those choices. Also, take note of how to handle the input afterward. Each choice is assigned a number, based on its order: Y = 1, N = 2, M = 3. The if statement should actually be read as, "If the error level is greater than or equal to x, go to label." Because of how the computer handles if statements, always test the errorlevel from the highest to the lowest. If you test the values in the wrong order, and start you evaluation with if errorlevel = 1 goto y, then everything will satisfy the this test because all of the possible values are greater than or equal to 1. If you are using Windows 2000 or Windows XP, then you can do the same type of thing in your batch file using the set command, but I have found that set is an inferior tool for this type of test. So I suggest getting choice.exe from either a Windows 98 computer, the Windows 2000 resource kit, or extracting it from Microsoft provided tools such as the Microsoft Platform Support Reporting Utility. The Platform Support Reporting Utility is available from the download page at http://support.microsoft.com/default. aspx?scid=kb;en-us;816819 and provides choice.exe in most packages, including the Base/Setup/Storage/Print/Performance package. 636 Batch File Basics Starting with Windows Server 2003, Microsoft has included choice.exe, and it supports slightly different options than the MS-DOS version. This version of choice.exe is also compatible with Windows XP. Here is a copy of the same batch file using the Widows Server 2003 choice command. Notice the /M and the quotes around the message text: @echo off choice /c:ynm /M "You choose" if errorlevel == 3 goto m if errorlevel == 2 goto n if errorlevel == 1 goto y goto end :y echo You chose Yes. goto end :n echo You chose No. goto end :m echo You chose Maybe. goto end :end The if, choice, and set statements add many options to the design of your batch files; they can help you make batch files that are flexible and comprehensive. Looping I hate having to repeat myself, and if you feel the same way, then loops are for you. Loops can be used inside or outside of batch files with only a small modification. The loop is a for loop and requires a list of values that are assigned to a variable and a statement that uses that variable. The variable is assigned with a % sign in front of it outside of a batch file, and two % signs when used within a batch file. Here is an example of a loop at the command prompt: echo off for %x in (hello world) do echo %x The output of the previous loop would be: hello world Book V Chapter 5 Command Prompt Procedures Batch File Basics 637 If this were done in a batch file, it would look like this: echo off for %%x in (hello world) do echo %%x Loops may cut down your work when you have several repetitive lines in your batch file.
more
del To delete or remove files or directories, you can use del or erase. Once again, these two commands are synonymous. If you want to delete multiple 622 Making Comparisons files, you have to use the * and ? wildcards. MS-DOS and Windows 9x let you delete only files with this command, while Windows 2000 and Windows XP will also delete directories. It is very easy to unintentionally delete files (or delete the wrong files) when working with relative paths. When possible, use full pathnames to avoid mistakes. ren The ren command is used to rename files and directories. Similar to many of the commands that you have looked at, you specify the source name and a new name for the file or directory. All of the command-line tools in this section have not changed substantially since MS-DOS. Making Comparisons There are a many special function commands, and this section will look at a couple commands that can be used to compare files. These commands are fc.exe and diskcomp.exe. diskcopy.com and diskcomp.com These two tools do not get very much use these days. Both of these tools were designed to be used with floppy disks and both take two parameters, first is the drive letter of the source disk and the second is the destination disk. Both of these can be the same drive letter, such as diskcopy a: a:, which will copy the contents of drive a: to a temporary location and then ask for the target disk to be inserted in the a: drive. diskcopy.com will copy the contents of the disk to a new disk, and diskcomp.com will compare the contents of the two disks to ensure that there are no errors during or after the copy. fc.exe fc.exe is still a valid and useful tool, it compares the contents of two files and indicates the differences between the two files. There are a variety of switches with this command that will allow you to modify how the output looks or the way that the comparisons are made. The basic format of the command only requires that you specify the two files that you want to compare using a format like fc.exe c:\boot.ini c:\old-boot.ini. Here is a sample of the fc.exe command in action. Book V Chapter 5 Command Prompt Procedures Performing Diagnostics and Tuning Performance 623 C:\>fc.exe boot.ini old-boot.ini Comparing files boot.ini and OLD-BOOT.INI ***** boot.ini [boot loader] timeout=30 default=multi(0)disk(0)rdisk(0)partition(1)\WINDOWS ***** OLD-BOOT.INI [boot loader] timeout=20 default=multi(0)disk(0)rdisk(0)partition(1)\WINDOWS ***** In this example, there was one difference between the two files, in the timeout= line. By default, fc.exe shows the line before and after the difference in the files, and shows you which lines came from which file. This command is very useful when attempting to compare two very long configuration files for differences. All of the command-line tools in this section have not changed substantially since MS-DOS. The exam objectives call for testing on command-line tools and they may not be limited to just the common tools that are listed in this book. To review new command-line tools, choose Start➪Help and Support and search for New Command-line Tools. To review all possible command line tools, Choose Start➪Help and Support, and search for Command-line reference A-Z. Performing Diagnostics and Tuning Performance At the command prompt, a few commands can be used to optimize and diagnose your computer. defrag.exe can be used to optimize your hard drive, while chkdsk.exe can be used to check your disk for errors. You would have used mem.exe when creating an MS-DOS boot disk, to view memory used when trying to optimize your memory usage. The MS-DOS or command prompt versions of the defrag.exe and chkdsk .exe utilities have now been replaced by Windows XP and Windows 2000 versions. defrag.exe The purpose of the defrag utility is to fix speed and performance problems with hard drives. As files are written to and then deleted from a disk, they leave holes or blank areas scattered around your drive. When you write files 624 Performing Diagnostics and Tuning Performance to a disk, they always write to the largest open spaces that are available to them. There will be times when the largest area is not large enough for the entire file, and the file will have to be split into pieces. These fragmented files are slower to access because the disk head has to keep moving to a new location on the drive. If you want to defragment the files on your hard drive, you can use Computer Management in Windows 2000 or Windows XP, or defrag in Windows XP. In an effort to provide command-line access to all Windows-based utilities, Microsoft provides command-line access to the graphical defragmenter utility. In either case, you are using the defragmentation utility from Executive Software, and you have the option to analyze only or to force defragmentation when disk space is low. For more information about using Computer Management in Windows 2000 and Windows XP, see Book VI, Chapter 4. Defrag.exe does not exist for Windows 2000. It is only available on Windows XP and newer Windows operating systems. chkdsk.exe chkdsk.exe serves an important purpose within the Windows operating system. Its job is to check the directory structure and directory entries for corruption, and the disk for worn-out areas. Its purpose is to reduce the chance of data loss by catching corruption early and by fixing small problems before they become larger. For more information about chkdsk.exe, refer to Book VI, Chapter 4. mem.exe The mem command displays usage information about your computer's memory. This is often useful when trying to optimize the boot process or when trying to maximize the amount of memory available to MS-DOS-based applications. mem runs from within MS-DOS. Running the command by itself displays basic information about how much memory is available to the MS-DOS environment. Two main switches are available to the mem command: ✦ /c (classify) tells you how much space applications are using in upper memory and conventional memory. ✦ /d (debug) gives you a detailed breakdown of what is stored in the first 1MB of RAM. Book V Chapter 5 Command Prompt Procedures Working with the Rest 625 Working with the Rest The rest of the utilities in this chapter defy easy classification and are presented in the following sections. Although they serve a wide range of functions, they are all important in your computer's usage. attrib.exe All files have four basic attributes: read-only (r), hidden (h), system (s), and archive (a). The attrib command lets you change these attributes. The attributes are added or removed from files by specifying the attribute with a + or - in front of the filename, as in the following statement: attrib -s -h +a +r c:\*.sys The previous statement removes the system and hidden attributes while adding the archive and read-only attributes. If /s were added to the end of the line, then it would have been done to all of the files in the subdirectories as well. As the name suggests, read-only files cannot normally be deleted, nor can they be modified. Hidden files are not usually visible. System files have special file protection so that you may not delete or modify them. Archive files are files that have been modified. The archive attribute is used by some backup utilities to identify changed files for incremental backups. diskpart.exe To manage disk partitioning, if the need ever arises, Windows 2000 and Windows XP use a graphical disk partitioning tool called Disk Management; Windows XP also uses another command-line tool called diskpart.exe. Although this tool is capable of all disk partitioning tasks, you use this tool only if you need to perform rare disk partition changes that Disk Management cannot perform, such as expanding a partition on a basic disk. The reason for not using diskpart.exe is that it's user interface is awkward. To illustrate the interface, the following is the set of steps required to create a partition on a disk and format the drive (extra blank lines have been removed): C:\>diskpart.exe DISKPART>list disk Disk ### Status Size Free Dyn Gpt -------- ---------- ------- ------- --- --- Disk 0 Online 6142 MB 0 B Disk 1 Online 510 MB 0 B Disk 2 Online 6142 MB 6142 MB DISKPART> select disk 2 626 Working with the Rest Disk 2 is now the selected disk. DISKPART> create partition primary size=1000 DiskPart succeeded in creating the specified partition. DISKPART> list partition Partition ### Type Size Offset ------------- ---------------- ------- ------- Partition 1 Primary 1004 MB 32 KB DISKPART> select partition 1 Partition 1 is now the selected partition. DISKPART> assign letter=f DiskPart successfully assigned the drive letter or mount point. DISKPART> exit Leaving DiskPart... C:\>format f: /fs:ntfs The type of the file system is RAW. The new file system is NTFS. WARNING, ALL DATA ON NON-REMOVABLE DISK DRIVE F: WILL BE LOST! Proceed with Format (Y/N)? y Verifying 1004M Volume label (ENTER for none)? More Data Creating file system structures. Format complete. 1028128 KB total disk space. 1020600 KB are available. This process could have been completed through a single wizard in Disk Management, with less effort. format.com The format.com command prepares a disk to be used by your computer. The purpose of this command is to check to see if all of the clusters on the partition are in working order and to create the directory table. On FAT partitions, the directory table is referred to as the File Allocation Table. The directory table maintains a list of where each file starts on the disk. The format command requires a drive letter and supports additional switches. The proper syntax to format your A: drive is format a: You could modify the command with /q to perform a quick format of the drive. The quick format doesn't check the integrity of the sectors on the drive but only deletes and re-creates the directory table. If you are using MS-DOS or Windows 9x, you can also use the /s (system files) switch. This copies over the system files that are required to boot. Book V Chapter 5 Command Prompt Procedures Working with the Rest 627 If you are using Windows 2000 or Windows XP, you will be able to use /FS:filesystem to specify the format of the partition as either FAT, FAT32, or NTFS. sys.com The MS-DOS sys, or system command, enables you to put the files that are required for booting your computer on a disk that has already been formatted. By default, the system files are copied from your current drive to the drive specified in the command. You can copy the files from an alternate location, but you cannot copy them to your current drive. Here are two examples: sys a: sys d:\sysfiles a: Because the files have to be placed in a specific location on the disk, there is a chance that you will be told that there is no room on the disk if that area is already occupied. ver The ver command indicates what version of the command prompt you are running. This varies between copies of Windows 9x and Windows 2000 or XP, as shown in Table 5-3. ver with Windows 9x operating systems lets you see that they are all sub-versions of Windows 4.0, while all copies of Windows 2000 and XP are sub-versions of Windows NT 5.0. Major and minor version numbers from software manufacturers let you know how much they think the software has changed, so architecturally each of these operating systems has not changed significantly since their initial releases. Table 5-3 Windows ver Output Version Output of ver Command Windows 95 Retail Windows 95. [Version 4.00.0095] Windows 95 OSR2 Windows 95. [Version 4.00.1111] Windows 98 Windows 98. [Version 4.10.1998] Windows 98 SE Windows 98. [Version 4.10.2154] Windows 2000 Professional Microsoft Windows 2000 [Version 5.00.2195] Windows XP Professional Microsoft Windows XP [Version 5.1.2600] Windows Server 2003 Microsoft Windows [Version 5.2.3790] help If you need to know how to do something with the command line, you have two main options. All commands support /? as a switch to get additional 628 Working with the edit Command information on how to use the command. In addition to this feature, Windows XP also has a help command. To use help, type help followed by the command that you would like to get help on — for example: help help If you type help by itself, you are given a list of commands that you can request help for. Working with the edit Command Most of the configuration files on your computer can be edited with any text editor. If you have the Windows interface loaded, you will probably prefer to use a graphical program like Notepad or Wordpad. In the event that you don't have a computer that is currently running Windows, you can always use the edit command. Opening files To open files, you first have to launch the editor. This can be done by typing edit in any command window. And if you know the name of the file that you want to edit, you can specify it after the edit command, like this: edit a:\config.sys If you have the editor open and you want to open a file, you have to press Alt to get access to the menu, press F to access the File menu, and then press O to open. This will bring you to the Open dialog box, shown in Figure 5-1. By default, you will be in the File Name position, with the current name of *.* selected. If you type in the full path and filename of a file, you will be able to open the file. If you choose to browse for your file, it gets a little more complicated. Figure 5-1: At first glance,