34
http://www.allenware.com/icsw/icswref.htm http://www.infionline.net/~wtnewton/batch/batguide.html THE BATCH FILES CDD.bat ("Change/Display Directory" Bat) Syntax: CDD (Directory Name) :: CDD.bat :: :: Changes to a Specified Directory :: Displays a File and Subdirectory List :: @ECHO OFF CD %1 "%1" Represents the Directory Name. You Type at the Command Line. ECHO. Adds a Blank Line to the Display. C:\BATCH\DR ________ CLU.bat ("Clear Screen - Move Up" Bat) :: CLU.bat :: :: Moves Up One Directory Level :: Displays Directory on a Cleared Screen. :: @ECHO OFF CD.. CLS ECHO. Adds a Blank Line to the Display.

Useful Batch Command

Embed Size (px)

Citation preview

Page 1: Useful Batch Command

http://www.allenware.com/icsw/icswref.htmhttp://www.infionline.net/~wtnewton/batch/batguide.html

THE BATCH FILES  

   CDD.bat

("Change/Display Directory" Bat) Syntax: CDD (Directory Name)

:: CDD.bat:::: Changes to a Specified Directory:: Displays a File and Subdirectory List::@ECHO OFF

CD %1 "%1" Represents the Directory Name. You Type at the Command Line.ECHO. Adds a Blank Line to the Display.C:\BATCH\DR ________

     CLU.bat

("Clear Screen - Move Up" Bat)

:: CLU.bat:: :: Moves Up One Directory Level:: Displays Directory on a Cleared Screen.::@ECHO OFF

CD..CLSECHO. Adds a Blank Line to the Display.C:\BATCH\DR ________

Page 2: Useful Batch Command

     CFB.bat

("Copy From `B'" Bat) Syntax: CFB (Optional File name)

:: CFB.bat:: :: Copies All or Specified Files From the :: B Drive Root to the Current Directory:: (A Sub-Directory Location May be Specified):: (Hidden Files are Excepted.)::@ECHO OFFECHO. Leaves a blank line for separation.

IF "%1" == "" XCOPY B:\*.* If there is no file name, allIF NOT "%1" == "" XCOPY B:\%1 files in the B drive root will ECHO. be copied.C:\BATCH\DR If there is a file name, only it will be copied. ________

     CTB.bat

("Copy to `B'" Bat) (Substitute a USB flash-driveletter to copy to it.)

Syntax: CTB (Optional File Name)

:: CTB.bat:: :: Copies All or Specified Files to a B-Drive Floppy:: (Hidden Files are Excepted.)::@ECHO OFF

ECHO. Adds a Blank Line to the Display.IF "%1" == "" XCOPY *.* B:\ If there is no file name, all files IF NOT "%1" == "" XCOPY %1 B:\ in the current directory will be C:\BATCH\DR B:\ copied. If there is a file name, only it will be copied.

________

     DAF.bat

Page 3: Useful Batch Command

("Delete All Files" Bat)

:: DAF.bat:: :: Deletes All files in the Current Directory:: With Prompts and Warnings:::: (Hidden, System, and Read-Only Files are Not Affected)::@ECHO OFF

DEL . `.' Represents the Current Directory.DR

   DAF.bat       (Variation)

("Delete All Files" Bat)

:: DAF.bat (Variation):: :: Deletes All files in the Current Directory:: Skips "Are You Sure?" and Other Messages:: (Hidden, System, and Read-Only Files are Not Affected)::@ECHO OFF

ECHO Y | DEL . > NUL Echoes (sends) a "Yes" Answer to the "Delete" Prompt and Hides Other Messages.ECHO. Adds a Blank Line to the Display.C:\BATCH\DR

________

     DELE.bat

("Delete Except" Bat) Syntax: DELE (File name) to Not be deleted)

:: DELE.bat:: :: Deletes Directory Entries *Except* for Specified File(s):: Wildcards (* and ?) may be Used in the File Name:: (Hidden, System, and Read-Only Files are Not Affected)::@ECHO OFF

MD SAVE Makes a Temporary "SAVE" Directory.XCOPY %1 SAVE > NUL "> NUL" Suppresses On-Screen Messages.ECHO Y | DEL . > NUL Deletes all Files in the Current

Page 4: Useful Batch Command

Directory showing no Prompts.

MOVE SAVE\*.* . > NUL Returns Excepted File(s) to theRD SAVE Current Directory. Removes "SAVE" Directory.ECHO. Adds a Blank Line to the Display.C:\BATCH\DR Displays the Results of the Operation.

    To see a variation of this batch file which will allow multiple files of differing names to be excepted, go to Advanced Batch Files.

     DELT.bat

("Delete Tree" Bat)(Requires DOS 6 or Newer)

Syntax: DELT (Directory Name)

:: DELT.bat:: :: Deletes Specified Directory and All Files :: and Directories Below:: Prompts "Are You Sure?" Before Deletion Commences.::@ECHO OFF

IF "%1" == "" GOTO NO-DIRECTORY Prompts if No Directory was Specified

ECHO. Displays a Blank Line.ECHO. Displays a Blank Line.

TREE %1 Displays the Directory Structure to be Deleted.DELTREE %1 Deletes Directory Structure.DRGOTO END Directs DOS to End the Batch File Operation.

:NO-DIRECTORYECHO.ECHO No Directory SpecifiedECHO.

:END ________

     MCD.bat

("Make/Change Directory)

Page 5: Useful Batch Command

Syntax: MCD (File Name)

:: MCD.bat:: Makes and Changes to the Specified Directory::@ECHO OFF

CLSMD %1CD %1 ________

     MDEL.bat

("Multiple Delete" Bat) Syntax: MDEL (File Name File Name File Name, etc.)

:: MDEL.bat:: Allows Deletion of Up to Nine Files:: with Different Names and Extensions:: Wildcards are Permitted::@ECHO OFF

CLS Clears the Screen.FOR %%F IN (%1 %2 %3 %4 %5 %6 %7 %8 %9) DO DEL %%F See Text.

ECHO. Adds a Blank Line to the Display.C:\BATCH\DR Confirms the Operation.

    This uses the DOS "FOR-IN-DO" (FOR) command and replaceable parameters. Basically, it means "FOR each Item INside the Brackets, DO the given command". In this case, it will take each file name you give at the command line and substitute it for one of the percent-numbers. These percent-numbers are replaceable parameters, with "%1" representing the first file name, "%2, the second, and so on. Wild card characters, ` ? ' and ` * ', may be used in file names.

    The batch file deletes each item inside the brackets, which will be those file names you typed at the command line. Each file name is substituted for one of the percent numbers. You may specify up to nine file names or groups.

      MDEL.bat (Improved)

("More Powerful "Multiple Delete"" Bat) Syntax: MDEL (File Name File Name File Name, etc.)

:: MDEL.bat (Improved):: Allows Deletion of Multiple Files:: with Different Names and Extensions@ECHO OFF

CLS Clears the Screen.

Page 6: Useful Batch Command

:AGAIN See Text.ECHO Deleting %1DEL %1SHIFTIF NOT "%1" == "" GOTO AGAIN

ECHO. Adds a Blank Line to the Display.C:\BATCH\DR Confirms the Operation.

    This version allows one to type as many file names as the command line can hold. It uses the "SHIFT" command. That allows each file name on the command line to shift down one number to become the first replaceable parameter. Thus, the second file name will become "%1" after the SHIFT command is issued, the third file name becomes "%2", and so on. After yet another SHIFT command, the third file name will be in position "one" (%1). As long as there are file names left on the command line, they will be shifted one at a time into position number `1'. Then, each is deleted in turn with an on-screen message to that effect being displayed.

    Finally, when no file names are left, the "IF NOT" statement becomes false because "%1" will then be equal to nothing. Thus the batch file does not loop to "AGAIN" and instead goes on to display the directory listing confirming the files are gone.

________

     MU.bat

("Move Up" Bat) Syntax: MU (File Name File Name File Name, etc.)

:: MU.bat (Move Up):: Move All or Specified Files Up One Level::@ECHO OFF

If "%1" == "" GOTO MOVE-ALLIf NOT "%1" == "" GOTO MOVE-SPEC

:MOVE-ALLMOVE /-Y *.* ..GOTO END

:MOVE-SPECFOR %%F IN (%1 %2 %3 %4 %5 %6 %7 %8 %9) DO MOVE /-Y %%F ..

:ENDECHO. Adds a Blank Line to the Display.F:\BATCH\DR ________

    This allows one to move up to nine files or file groups into the parent directory one level up. I use it because I have many directories in which there is a WORK subdirectory. After doing my work, I want to move the completed files into the parent directory and use this batch file to do so. The "/-Y" will prompt you if any files in the parent directory are about to be overwritten. You may choose to overwrite

Page 7: Useful Batch Command

or not. The batch file will then resume and go on to the next file. (Be aware, some DOS versions do not recognise this switch and will overwrite without prompting.)

    You may modify this batch file into CU.bat (Copy Up) by replacing the MOVE commands with:

COPY *.* .. /-Y

or

COPY %%F .. /-Y .

    Note that the "Overwrite" switch comes at the end of the line when COPY is used.

________

     SDEL.bat

("Safe Delete" Bat) Syntax: SDEL (File name)

:: SDEL.bat (Safe Delete):: Displays File to Be Deleted:: Prompts to Delete File or Abort Operation:: Wildcards May be Used to Delete File Groups::@ECHO OFFCLS

IF NOT "%1" == "" GOTO DISPLAY

ECHO. IF "%1" == "" ECHO No File(s) Specified! Prompts if No FileECHO. is Given.GOTO END

:DISPLAYECHO %0 %1 Gives the Batch File NameECHO. and File to be Deleted.ECHO These Files Will Be Deleted: ECHO. DIR %1 | FIND "Directory" Displays the Path andDIR %1 /B /P Files to be Deleted.

ECHO.ECHO To Delete Listed Files, Allows the User toECHO Press Any Key Continue or Abort.ECHO. ECHO To Cancel, Press: `Control-C'ECHO.

PAUSE > NUL

:DELETE Deletes Selected File(s).DEL %1

Page 8: Useful Batch Command

ECHO.

:ENDECHO. Adds a Blank Line to the Display.C:\BATCH\DR Confirms the Operation.

    An improved SDEL.bat may be found in Advanced Batch Files.

________

     STEP.bat

("Step" Bat)(Requires MS-DOS 6.2 or Newer) Syntax: STEP (Batch File Name with No Extension, Parameters)

:: STEP.bat:: Allows one to Step through a Batch File:: To Test Each Line::@ECHO OFFCOMMAND /Y /C %1.bat %2 %3 %4:END ________

    This simple example allows one to run a batch file a line at a time to test it. It runs another copy of DOS' COMMAND.com. The "/Y" switch is what does the stepping. It displays each line and asks if you wish to run it or not by pressing "Y" or "N". You may exit this procedure at any time by pressing "CONTROL-C". Also, by pressing "Escape", the batch file will continue on its own from the current line.

    The "/C" switch runs the specified command and then returns to the base COMMAND.com - either after the stepping procedure finishes, or after pressing "CONTROL-C".

    When running this batch file, don't type the ".bat" extension. STEP.bat does that for you via the "%1.bat" replaceable parameter. If the batch file requires additional parameters, you may specify up to three via the " %2 %3 %4" replaceable parameters. Here's a syntax example:

STEP SDEL TEST.txt

    This will step through the "SDEL" batch file using "TEST.txt" as SDEL's file parameter. (SDEL.bat was presented here as the previous example batch file.)

Page 9: Useful Batch Command

:: Batch File Commands ::

Command @

Description Do not echo this line.Syntax @ command line

Typical Use To hide a single line if echo is switched on, or to hide the switching off of the echo command.

Example echo This line will be echoed twice to the screen,@echo Whereas this line will occur only once.

Command ECHO

Description The ECHO command has several different uses. MS DOS batch files use two echo 'modes'. The default echo mode is ECHO ON. When ECHO is set to ON, every command in the batch file is displayed to the screen before it is run. Sometimes this information is not required, and can even be downright annoying for larger batch files. The command ECHO OFF sets the batch echo mode to OFF. In this mode, the commands are not printed to the screen prior to their execution.As well as the echo modes, the ECHO command is used to print a message to the user. Messages are displayed to the user by preceding a line of text with ECHO.

Syntax ECHO MODE ON : ECHO ONECHO MODE OFF : ECHO OFFDISPLAY A MESSAGE : ECHO message

Typical Use The command @ECHO OFF is almost always placed at the top of a batch file to switch off subsequent command echo.ECHO is also the only way a batch file can communicate information to a user.

Example @ECHO OFFECHO Please insert a disk in drive A: and press any key when ready.

Command REM (short for remark)

Description REM is the MS DOS batch file method of providing comments. Comments are lines of code which are not executed by the batch file, but rather are used to convey information about the workings of the batch file itself. Good batch file programming practice demands a comment at the head of every batch file explaining its use and syntax. Comments can also be put in other parts of the file to clarify ambiguous commands and to 'comment-out' a line of commands so that they are temporarily ignored by the batch file.

Syntax REM line containing comment.

Typical Use REM should be used at the top of every batch file to provide a description and example use. However, too many REM lines are not an example of good programming style! Don't provide a comment for obvious commands - only the tricky ones!

Example REM SFORMAT.BAT : Safe FormatREM

Page 10: Useful Batch Command

REM This batch file implements a safe version of the format command.REM The C: drive can not be formatted with this command.

Command PAUSE

Description The PAUSE command prints the message "Press any key to continue..." to the screen and waits for the user to respond.

Syntax PAUSE (it's as simple as that!)

Typical Use The PAUSE command was the only method of getting a user's response in batch files until the choice command arrived in MS DOS 6.x. By issuing instructions with the ECHO command, the PAUSE command waited for the user to read them and respond appropriately.

Example ECHO Please insert the disk in drive A: andPAUSE

Command GOTO

Description The GOTO command allows a batch file to branch to a different location to continue executing commands from. To tell the batch file where to go to, a label is placed after the GOTO command. This label must conform to several guidelines for it to be a valid batch file label.

Syntax GOTO label

Typical Use Until MS DOS 6.x introduced the FOR command, the GOTO command was a batch files only mechanism of performing a command repeatedly. GOTOs are still the only method in a batch file to perform a sub-set of commands. (MS DOS Batch files do not have sub-procedures)

Example IF %1 == "" GOTO ERROR

Command IF

Description The IF command is used in batch files to test whether a condition is met or not. This allows the batch file to perform a particular action only if a particular condition is met. There are several different variations of the IF command: IF EXIST, IF ERRORLEVEL, and IF x == y (yes! it does use two equal signs!)

Syntax IF EXIST filename or dirname : used to test for the existence of a file or directory in MS DOS. This test will return true if the file does exist.IF ERRORLEVEL : After a program has finished executing in MS DOS it returns a value to the operating system indicating its success or failure. This value is stored in the variable ERRORLEVEL. By testing this variable, a batch file can deduce the result of the program that just finished running.IF x == y : This version of the IF statement tests two string values. If string x is equal to string y this test is evaluated to be true, otherwise false.All of the above IF statements can also be negated with the NOT command. For example -:IF NOT EXIST filename : Tests to see if the file doesn't exist. This test will return

Page 11: Useful Batch Command

true if the file doesn't exist.Typical Use The IF statement is one of the most useful batch file commands, and as such is probably

the most common. The IF EXIST command is used to check if a file exists before it is copied/moved/opened/etc. The IF ERRORLEVEL allows a batch file to check the return value of another program. The IF STRING1 == STRING2 is commonly used to validate command-line parameters.

Example IF NOT EXIST %1 MKDIR %1

IF ERRORLEVEL 2 GOTO END

IF %1 == "" GOTO ERROR

Command SHIFT

Description The SHIFT command is possibly, at first, the most confusing batch file command. It needn't be. Simply, the SHIFT command increases the number of command-line

parameters accessible by a batch file. Each time SHIFT is called, the value in the 1st

parameter is discarded and replaced by the value of the 2nd parameter. The value in the 2nd parameter is replaced by the value in the 3rd parameter, etcetera, etcetera, until the 9th

parameter is replaced by the previously unavailable 10th parameter.Syntax SHIFT

Typical Use The SHIFT command provides considerable power to batch files. It allows a batch file to operate on an unknown number of parameters. The SHIFT command is often used in situations where an operation needs to be performed on several files or directories.

Example The following example displays the contents of the files typed after the batch file name one page at a time.

:LOOPTYPE %1 | MORESHIFTIF "%1" == "" GOTO ENDGOTO LOOP:END

Command CALL

Description The CALL command is used to run another batch file from within a batch file. Execution of the current batch file is paused and the called batch file is run. After the called batch file has finished running, the original batch file is resumed at the line after the CALL statement.Note: If another batch file is run from within a batch file by simply using its name, after the called batch file finishes executing, control is returned to the Command Line, NOT the original batch file.

Syntax CALL batchfilename [parameters] [switches]

Page 12: Useful Batch Command

Typical Use The CALL command is used to provide modularity to batch files. Batch files can be re-used effortlessly if they are written with modularity in mind.

Example IF %1 == A: CALL FLOPPY.BAT

Command FOR

Description The FOR command was an invaluable addition to the DOS Batch File Command suite. FOR repeats a command for a number of files, directories, or text-strings.

Syntax FOR variable IN list DO command [parameters] [switches]Where -:

variable is substituted for each element in the list and passed to command. Variable has a special format in batch files.

list is a list of filenames (wildcards allowed), directory names, or text-strings that are to be processed by command one at a time.

command is a DOS internal or external command to be performed for each element of the list.

Typical Use The FOR command performs the same command for each element of a list. Prior to its introduction, the same effect had to be achieved with GOTOs and IFs, which were messy and sometimes difficult to follow. Use a FOR to do any necessary looping in your batch files.

Example The following is an implementation of the same example presented in the SHIFT example of displaying many files to the screen with MORE.

FOR %%f IN (*.*) DO TYPE %%f | MORE

A lot neater, huh?!

Command CHOICE

Description The CHOICE command is perhaps the best addition to MS DOS Batch File commands. CHOICE makes it possible to accept various user-responses. Before now, users were presented with crude either/or choices in batch files. The CHOICE command allows a batch file to detect a users choice from a lits of options.

Syntax CHOICE [/C:choices] [/N] [/S] [/T:choice,timeout] [TEXT]Where -:

/C:choices : specifies the choices that the user can choose from. The choices can only be single characters.

/N : Do not display choices and the '?' at the end of the TEXT prompt. /S : Treat the choices as case sensitive, meaning that 'a' is a different choice from

'A'. By default, case is not sensitive - 'a' is equivalent to 'A'. /T:choice,timeout : Default to choice after timeout seconds.

Page 13: Useful Batch Command

TEXT : The text to display as the prompt of the choice.

Typical Use The CHOICE command has its obvious use in batch files. It is now possible to easily get a users response, thus allowing batch files to be much more interactive, and therefore more useful.

Example The following batch file snippet displays a simple menu (without a question-mark at the end of the prompt) and prompts for the users choice, defaulting to option 2 after 5 seconds :

ECHO 1. MS-DOS Editor.ECHO 2. MS-Windows. (default)ECHO 3. Defrag the hard-drive.ECHO 4. Quit.CHOICE /C:1234 /N /T:2,5 Please choose a menu option.IF ERRORLEVEL == 4 GOTO QUIT_MENUIF ERRORLEVEL == 3 GOTO DEFRAG_HDIF ERRORLEVEL == 2 GOTO RUN_WINIF ERRORLEVEL == 1 GOTO RUN_EDIT:RUN_EDITCALL EDIT:RUN_WINCALL WIN:DEFRAG_HDDEFRAG c::QUIT_MENUECHO Safe to switch off machine now...

Page 14: Useful Batch Command

BATCH FILE COMMANDSSimple programming commands in a batch environment

Revised October 14, 2008Click here to refresh this page & its menu bar.

Yeah, yeah, I know that many people think batch files are mostly things of the past. Sometimes, though, a well-conceived batch file is just the thing to automate the job you want to do.

I am not going to cover all the theory and practice of batch files from the ground up. Any good book on DOS (now found in the Antiquities section of your local library <g>), and many of the best on Windows, will have a section on batch files. Simply put, a batch file is a plaintext file with a name ending in .BAT. In its simplest form, it contains a series of commands that could be executed from a command prompt (system prompt). The batch file simply autoexecutes them for you. (In fact, AUTOEXEC.BAT is the best known, and most widely used, batch file.) To execute a batch file, type its name at a command prompt, or execute a Windows shortcut that does the same thing.

The simplest idea of how to write a batch file is: Figure out how you would type the commands at a DOS prompt, then type them, one per line, in a text file — and you’ve written your batch file.

However, there are also more sophisticated batch file structures, using simple programming commands built into the batch structure. This article summarizes the most important of these.

Commandline Arguements {%x}

Variables can be inserted into a batch structure in the form of command line arguements. These are in the form %1, %2, etc. To populate the variables, type the desired values after the batch file name when executing it.

DOS Environment Variable Names {%nn%}

DOS environment variables also can be used as variables in batch files. For example:

COPY %windir%\filename a:

Where does one get a list of DOS environment variables? I have never found a comprehensive list; but a partial but lengthy list of existing environment variables can be gotten by typing SET at a command prompt.

And here’s the really cool part! You can make them up as you go along, and assign them as you wish (as long as you don’t grab one that has a legitimate assigned value, such as, say, %windir%, the Windows directory name!). Pick a name, populate it with the SET command by any means known to you (including having one batch file run a process that includes setting one, and then another batch file using it), then use it by placing the name between flanking % signs. Environment variables remain until overwritten, or until a reboot. (If you set them in a DOS window, they will end when that session is closed.)

If you precede an environment variable setting with the SETLOCAL command (on a line of its own), then environment variable changes are local to the batch file. They do not exist for any other process and they do not survive the completion of the batch file’s execution. You can turn this setting off by

Page 15: Useful Batch Command

issuing an ENDLOCAL command later in the batch file.

Silly example: To change the current logged drive to D:, do the following:

SET GONEXT=D:%GONEXT%

More practical example: You want to copy a file to the desktop of each user the next time they log into Windows. Each user logs into a different user profile, and the Desktop folder is in a unique location for each user. (The folder name will, of course, vary on non-English versions of Windows.) For a file called MYFILE.TXT, you can do this as follows on Windows 2000 or XP computers by using an environment variable %userprofile% which gives the path to the root of a given user’s profile:

COPY MYFILE.TXT %userprofile%\Desktop

START Command

The START command can launch a Windows program either by specifying the program name (and its command-line parameters), or by specifying a data file name that is associated with a particular program (one that would automatically launch if you clicked on it in Windows).

For example, if you have NOTEPAD.EXE associated with all TXT files, then you could open the file SOME.TXT in any of the following four ways:

NOTEPAD SOME.TXTSOME.TXTSTART NOTEPAD.EXE SOME.TXTSTART SOME.TXT

Why use one or the other? Well, sometimes you may have to use one particular form to get a result — depending, for example, on how the particular program is coded. Though the first form usually will work, you may want, for example, to write a more general batch file to open any particular program and associated file — without knowing what the requirements of all such files might be. You could, then, write a general batch file line such as START %1% %2%.

One particular use of the START command is to launch the default browser and go directly to a URL, for example: START http://google.com

You may use any of four command line parameters with the START command. These go after the word START, but before the program name:

/minimized or /m/maximized or /max/restored or /r/wait or /w

The first three determine the screen status in which the program opens. The last one forces the batch file to halt processing until the called program has finished executing. (This can be useful, for example, if you are loading multiple items in your windows Startup folder, and the nature of the programs require that one be finished before the next starts loading. Put them all in a single batch file, using the /wait parameter, and only put a shortcut to the batch file in the Startup folder.) Command line parameters of the START command can be combined in a single line. Example:

START /max /wait NOTEPAD.EXE SOME.TXT

Page 16: Useful Batch Command

IF and IF NOT Commands

There are three variations of the IF and IF NOT commands.

IF EXIST: Execute the commandline only if a particular file exists:

IF EXIST some.txt COPY c:/some.dll %windir%/SYSTEM/some.dll

Compare two text strings, and execute the commandline only if they are identical.

IF %HostWinBootDrv%==C SET WinDir=C:\WINDOWS

Error testing: Check the exit code of the most recently run program. If it is equal to or greater than the number specified, execute the command:

IF ERRORLEVEL 4 ERASE trashfile.tmp /P

GOTO Command

You can set a label in a batch file by beginning a line with a colon. You can then go directly to that label with the GOTO command. The GOTO command searches both forward and backward in the batch file; that is, it simply goes to the label location, regardless of where it is in the file.

For example, in my batch file for removing the Happy99 virus, UNHAPPY.BAT, the following code was used to make sure a file was not deleted unless the original form of it (backed up by the virus under the name WSOCK32.SKA) is present:

IF NOT EXIST WSOCK32.SKA GOTO SavedItDEL WSOCK32.DLLRENAME WSOCK32.SKA WSOCK32.DLL:SavedIt

FOR Command

The syntax for this command is: FOR variable in (set list) DO command

The variable must be in the form of one alphabetic character preceeded by %%; e.g., %%v.

NOTE: The %% is necessary because this is in a batch file which, otherwise, would give a special meaning to a single %. However, if you run the FOR command outside of a batch file, simply from the system prompt, just use a single % in the variable name. (Tip from Steve Wisdom)

The set list is enclosed within parentheses. These values will be assigned to the variable successively. You can use any text enclosed in quotes, batch file commandline parameters, environment variables, or DOS file wildcard expressions.

The command can be any valid command that otherwise could be entered into the batch file as a line of its own. example:

FOR %%D in (SYSTEM, COMMAND, SHELLNEW, "Start Menu") DO DIR "%windir%\%

Page 17: Useful Batch Command

%D" /W

Menu Creation

Sometimes you may want to let a batch file branch one way or another based on user input. This is especially helpful when you have several related batch processes and would like to combine them into a single application.

Back in DOS days, a common approach was to construct menus with multiple batch files. For example, you could create one batch file called MENU.BAT that displayed the menu (a series of text lines), inviting a user to type a 1, 2, 3, etc. (or A, B, C, etc.) to choose an option (a program to run, or archiving process, or whatever). That menu batch file would end, delivering the user back to a command prompt. You would then have a series of other batch files called 1.BAT, 2.BAT, 3.BAT, etc. so that, when the user typed (for example) 2 and pressed Enter, it would run 2.BAT. (This is way easier to understand if you walk through making one! It’s really terribly simple.)

Today, when users don’t live in a DOS command prompt world, we want something slightly more sophisticated — and, fortunately, we have it. There is a pretty cool way to allow user input in Windows 2000 and XP, and even better ways that work in Windows Vista.

In Windows 2000 or XP, the SET command has new /A and /P flags that allow user input. The latter is especially helpful for our present purposes. You can accept user input and assign it to a system variable with the following code:

SET /P variable=PromptString

The PromptString is optional. If you include one, it will be displayed on the screen. (Don t forget a ∍space at the end of the prompt if you want one!) For example,

SET /P M=Type 1 or 2, then press ENTER.

will display on the monitor the phrase “Type 1 or 2, then press ENTER.” It will then wait for the user to type something and press Enter. It will then assign whatever character the user types to the system variable %M%, which you can use in other batch file commands.

Windows Vista has added the CHOICE command. This is pretty cool! It lets you build simple menus just from this one command. On a Windows Vista computer, open a command prompt and type CHOICE /? to see all the things you can do with it. At the present, this might not be so useful if yo uare writing batch files that also will be run on Windows XP computers, because the CHOICE command will not work on those computers — and the SET /P approach above still works in Vista.

Here is an example of a batch file I recently wrote for my office. It uses many of the features discussed on this page, including menu creation. The problem to be solved was that (for reasons too tedious for the present article) users accessing our network remotely no longer had access to their browser Favorites. Additionally, it was useful (when swapping out computers) to migrate a user’s Favorites from the old computer to the new. Both of these could be solved by moving the Favorites (which are simply shortcut files) up onto a personal network drive (let’s call it P:) to which they always had access. I wanted to allow the user, with a single file that I could email them, to be able both to cache their Favorites on the network drive and to pull these back down to another computer. Here is a slightly edited version of the batch file.

ECHO OFFCLS

Page 18: Useful Batch Command

:MENUECHO.ECHO ...............................................ECHO PRESS 1 or 2 to select your task, or 3 to EXIT.ECHO ...............................................ECHO.ECHO 1 - Export Favorites from COMPUTER to PERSONAL DRIVE (P:)ECHO 2 - Import Favorites from PERSONAL DRIVE (P:) to COMPUTERECHO 3 - EXITECHO.SET /P M=Type 1, 2, or 3, then press ENTER: IF %M%==1 GOTO EXPORTIF %M%==2 GOTO IMPORTIF %M%==3 GOTO EOF:EXPORTXCOPY "%userprofile%"\Favorites\*.* P:\Favorites\ /S/Y GOTO MENU:IMPORTXCOPY P:\Favorites "%userprofile%"\Favorites\*.* /S GOTO MENU

More Information on These Commands

Each of these options (START, IF, GOTO, FOR, SET) is an actual DOS command. At a system prompt, type the command name followed by /? to get further help on these items.

Note that there may be particular capabilities that show up in one version of Windows, but not in another. For example, though DOS per se may well be dead in Windows XP and Vista, the commandline functions people most often associate with DOS are not dead at all! (We just don’t call them “DOS commands” anymore; we call them “command prompt commands.” But they’re the same thing.) In some cases, these commands have been made more powerful in Windows XP. In particular, if Win XP Command Extensions are enabled, each of these four has very greatly enhanced capabilities (see Win XP Help & Support to learn about Command Extensions). Take advantage of the opportunity to explore each of them with the /? help flag.

SOME EXAMPLES (that don’t even require Command Extensions): START has new flags that let you set the priority (/LOW, /NORMAL, /HIGH, etc.) of the application you are launching. IF has an ELSE option than greatly expands its power, but which requires a somewhat complicated syntax sometimes (which the /? help text covers reasonably well).

Since these START, IF, GOTO, and FOR are actual OS commands, they can be used from a system prompt just like DIR, COPY, or any other DOS command. This means that they can be used outside of a batch file as well. There are small differences or issues that you can easily discover in use, and discussion of which would go beyond the purpose of the present page. For anyone comfortable working at a DOS system prompt, this should present no significant problem. Just remember:

Page 19: Useful Batch Command

Making Batch Files

A batch file is a normal text file, no programming involved. You type DOS commands into a text file, each one on a seperate line. Then, you give the text file a .bat extension instead of a .txt extension. Now, when you double click the batch file(In Windows Explorer) or type its name at the DOS prompt, it will execute the commands.

First, we need to know some DOS commands. If you're a regular DOS user, you can skip this section and go to CREATING A BATCH PROGRAM. The main DOS commands we will use are copy, move, del, cls, and echo. The COPY command has this syntax:

copy [source] [destination]

In DOS help, the syntax is more complicated, but we don't need the advanced features for our batch files. The COPY command, obviously copies a file. For example, say I wanted to copy a:\readme.txt to a:\windows\help.txt. (By the way, this will also rename the file.) I would type this:

copy a:\readme.txt a:\windows\help.txt

The MOVE command is exactly the same, except it MOVEs the file, and COPY copies the file.

The del command is very simple. It erases a file. It follows this syntax:

del [filename]

For example, if you wanted to delete a file called a:\happy.txt you would type this:

del a:\happy.txt

The CLS command clears the screen. This is the syntax:

cls

PAUSE is a command that stops the program and prompts you to "Press any key to continue." The syntax is:

pause

ECHO is a DOS command that shows the stuff you type. In a batch program, the @ symbol means not to echo a line. So, typing ECHO OFF prevents the user from watching the batch program execute. And, to keep from echoing the ECHO OFF command, type the @ symbol in front of it. Put it together and you get:

@echo off

All good batch programs start with the @ECHO OFF command followed by CLS. Important!: If you use the @ECHO OFF command in your batch program, be sure to put ECHO ON at the end of the batch program or the user will think their computer is messed up. The ECHO ON command is like this:

echo on

Now for the batch file! First, if you're using Windows, open a DOS prompt. To make a batch program

Page 20: Useful Batch Command

to load a program called myname.bat, type this:

edit myname.bat

Then type:

@echo offclsecho Hi, my name is %1pauseecho This is the contents of this batch file:pausetype myname.bat

Then save it in a file called myname.bat. The "%1" allows you to add data to your batch file from the command line. Whatever you type after the batch filename at the dos prompt will replace the %1.

At DOS prompt, type

myname Suzanne

( you can use your name here) and your program will start!

When you have completed this lab, make sure that I see it so that I can grade you. This is lab 3B.

MSc CBIS COMM57 Software Environments

Tutorial 2- Batch Files

Batch files are created using a text editor such as EDIT. You may use a word processor but you must remember to save the file as text or ASCII text, since normal word processing files contain special character codes which won't be recognised by DOS.

All batch files have a .BAT extension. You may run a batch file by just typing in its name at the DOS prompt and pressing return. It is not necessary to include the .BAT extension when running a batch file.

Program Control

Normally, all commands in the batch file will be executed in the order in which they appear in the file. This is called a sequence. Sometimes, there are circumstances in which you would like to carry out commands in a different order or carry out a single command repeatedly. Try typing the listing below into a batch file, save it with the name rpt.bat then run it.

echo offREM print steve all over the screen (put your own name in instead):startecho stevegoto startREM end of program

Page 21: Useful Batch Command

Stop the program from running by pressingControl and C keys.

What happened? Your program should have repeatedly printed a name on the screen.

The key command is called GOTO. It transfers program control to a place in the batch file that you specify. In this case, we tell the program to go to a line that begins with a label called :start. Labels don't actually do anything in themeselves, they just act as a point of reference in a program. You can call labels almost anything you like, except you must ensure that they always begin with a colon ':'.

Every time the program reaches the goto command, it is told to go back to the start and repeat the echo command again. Thus, this program never terminates and will continue until you interrupt it.

Instead of printing steve every time you run the program, you could ask the user which word they wanted printed. To do this you need to make use of parameters (%1,%2..etc), in much the same way you did in the last tutorial.

echo offREM ask user for what word to print:startecho %1goto startREM end of program

save the file with the name rpt2.bat and then run it like this

RPT2 anyword

FOR...IN...DO

The format of the FOR command is

FOR variable IN (argumentlist) DO command

This is a repetition construct which will execute 'command' a number of times, depending on what's in the argument list. Suppose we have a list of names to process.

echo offRem command that prints out a list of namesFOR %%a IN (Andrew Bob Carol Daisy Ellen) DO echo %%a

In this case the loop will execute the echo command 5 times becuase there are 5 items in the argument

Page 22: Useful Batch Command

list. See how we are able to use the variable %%a as a substitute for each of the names? %%a is a variable that can take the value of a number of characters. When the echo command is executed, the value of %%a is printed out.

We aren't confined to just simple character strings either. We could use wildcard characters or user definable parameters (see below). This command will print out a list of the names of text files stored in the current directory.

echo offFOR %%a IN (*.txt) DO echo %%a

Exercise

Can you amend the above program to make it print out a list of text files AND a list of executable files (.EXE)?

Decision Making using IF

This program demonstrates how the IF command works

ECHO OFF REM call the batch file exists.bat REM check whether a file called 'test.txt' exists IF EXIST test.txt GOTO :success IF NOT EXIST test.txt GOTO :error

:success ECHO file test.txt exists GOTO :end

:error ECHO Error - can't find the test.txt file GOTO :end

:end REM do nothing. This is just the end of the file

If you don't have a file called test.txt in your current directory, the message 'Error - can't find the text.txt file' should be printed.

Create a file called test.txt, and run the batch file again. What happens?

IF EXIST and IF NOT EXIST are the key commands. They test whether the file named test.txt exists

Page 23: Useful Batch Command

and transfer control (using GOTO) to the appropriate error message.

IF has several different uses. Type in the command

if /?

to get more information.

Exercise

Amend the above program so that the user can choose any file they specify, rather than using text.txt all of the time.

User Input

We have seen that parameters are one way of getting input from the user. But here we look at some more flexible ways. We might for example, want the user to choose an option from a menu of options, or answer a question (e.g. Are you sure you want to delete this file [y,n] ?).

Here's an example of a safer version of the DEL command which asks for confirmation before deleting a file.

REM SAFEDEL.BAT

REM choice gives you 2 options in this case - either y or n

CHOICE/C:yn Are you sure you want to delete %1 IF ERRORLEVEL 2 GOTO :no IF ERRORLEVEL 1 GOTO :yes

:yes DEL %a GOTO :end

:noecho file %1 not deleted GOTO :end :end

Of course, using DEL /P is a much better way of using DEL safely but the point is to demonstrate how you might use the CHOICE commands as a means of getting response from the user.

In this case we have only used 2 choices y or n, but you can have more. Your code would look something like this:

CHOICE/C:abcd choose a letter IF ERRORLEVEL 4 GOTO choice_d

Page 24: Useful Batch Command

IF ERRORLEVEL 3 GOTO choice_c IF ERRORLEVEL 2 GOTO choice_b IF ERRORLEVEL 1 GOTO choice_a

Note the syntax and order of the statements. This is extremely important! The first line lets you specify which keys you want the user to choose from.

Exercise

Using the command you've just learned, write a batch file called winopt.bat that gives the user 4 choices:

1. Start Windows 2. Start DOSKEY3. REturn to DOS

Thus by simply entering a number from 1 to 3 the relevant command(s) should be invoked.

File Redirection

Normally, DOS assumes all input commands come from the keyboard, and prints out the results on the screen (usually called standard input/output). But this does not always have to be the case.

You can use the input direction operator '>' to send output to a file rather than the screen. For example,

DIR A: > catalogue

will put the results of the DIR command into a file called catalogue, thus giving you a file which describes the contents of your floppy disk. Why not try it now?

You can also take input from a file using the '<' rather than the keyboard but this is more unusual. For one thing, batch files perform this operation automatically without having to use the operator.

Input/Output direction don't look especially useful at this point. However, you may find they become more useful when we get on to using UNIX.

Filters

Filters are used to process data in some way. One such filter is called MORE. You can use it (e.g.) to display long files one screen at a time:

MORE < FILE.TXT

Page 25: Useful Batch Command

Note how MORE makes use of the redirection operator.

Another filter is FIND which looks for occurrences of strings in files. FIND "this" MYFILE.TXT

Note that you must put quotes around your search string.

Exercise

Can you write a batch file that uses find to search for strings in all text files in a complete directory (use a small directory to test this), and then puts its results in a separate file, rather than displaying them on the screen?

Finally...

In this tutorial, we have only introduced the subject of batch files - complex commands can be created. For those that are interested, check out one of the many DOS manuals such as Microsoft's or Peter Norton's, for more detailed descriptions.

DOS has a reasonably simple set of commands. Even so, it is possible to create full, working programs which are a lot more compact than the equivalent versions in some programming languages I could mention.