You are on page 1of 7

Beginners Guides: Understanding and Creating Batch Files Batch files can save time by automating specific actions

taken on the computer down to one simple click. They can also potentially hide damaging code so a good understanding of what they are how they work and how to create your own is crucial to today!s "T force. # $ersion %.&.& Bookmark this PCstats guide for future reference. In this Beginners Guide, PCSTATS is going to walk you through one of the simplest ut potentially most powerful ways to customi!e and simplify the management of your computer" atch files. These te#t files are easy to create, and only as comple# as you want them to e, ut they can perform many useful operations from file ackups to system configuration $uickly and automatically. At their simplest, atch files are te#t files which e#ecute one or more command prompt commands in a specific order. The power of a atch file lies in the way that it allows you to com ine multiple commands into one atch file %program% and customi!e the way that each command operates. In this article PCSTATS will illustrate what atch files are good for and how to create them. By creating a useful series of atch files designed to allow you to selecti&ely ack up files from one location to another, we%ll demonstrate the ways that atch files can make your computing life easier while you learn the &arious option in&ol&ed in creating them. 'hat can batch files do for you( If you read PCSTATS Guide to the 'indows (P Command Prompt, you%ll ha&e a passing familiarity with se&eral &ery useful command prompt commands. Batch files can incorporate any command prompt command )including the switches for that command*, e#ecute multiple commands in se$uence and choose which commands to use ased on user input or the results of pre&ious commands. +ssentially, anything you can do in the command prompt you can do etter and faster with atch files once you ha&e prepared them. This article deals e#clusi&ely with using the ,icrosoft 'indows (P-./ command prompt to create atch files, so commands here may not e 0112 compati le with earlier &ersions of 'indows which used a true 34S prompt )and the same holds true in re&erse5 true 34S atch files may not work under 'indows (P*. The range of commands a&aila le to produce atch files actually decreased with the 'indows (P-./ command prompt implementation, ut the essential functions are still present. )ow are batch files created( As we%&e said, atch files are simply te#t files, so all you need to create one is the 'indows notepad application. 3on%t use 'ordPad or a word processor like ,icrosoft 'ord5 these do not produce %pure% te#t files y default, since they add their own te#t formatting. To create a simple atch file, all you need is a single command you want to run, typed into a te#t file and sa&ed with the .BAT e#tension, like %my atchfile. at%. 3ou le click this file and it will run your command. 6et%s test it out... Creating a B*TC) File 7irst open an e#plorer window to your c" dri&e, using 'indows +#plorer or %my computer.% Arrange the window so you can see oth your desktop and your c" dri&e contents.

4pen the notepad application y going to %start8all programs8accessories8notepad% or %start8run% and type %notepad%. In the lank notepad window, type" md c:\testsource md c:\testbackup

9ow go to %file% and %sa&e as%. )in case you did not read our guide to the command prompt, the %md% command instructs the system to create a directory

using a name and location following the command.*

Sa&e your first atch file on the desktop as %myfirst atch. at%. Close notepad and you%ll see that %myfirst atch. at% has appeared on the desktop. 3ou le click the file to run it. Check your c" window. The %testsource% and %test ackup% directories ha&e appeared. :our first simple atch file is a success; 3elete the %myfirst atch. at% file from your desktop. +reparing for your second batch file 9ow we are going to create a useful atch file that will copy all the files in your %c"8testsource% directory into your %c"8test ackup% directory each time you run it. 'e%ll also make it so that the ne#t time you run that atch file, it will only copy the files that ha&e changed and new files, not e&ery single one in the %c"8testsource% directory. Ideally you%d use this atch file to copy your files onto a second hard dri&e or remo&a le media like a <SB key, ut we%ll lea&e it as it is for now. 7eel free to change the target directory to something more useful later. 7irst we need to create a couple of dummy files in our c"8testsource directory to gi&e us something to work with" 9a&igate to your c"8testsource directory in +#plorer and right click on the empty space inside. Select %new8te#t document.% Call your new te#t file %testdoc0%. 9ow right click again and create a new itmap image. Call your image %test it0%. :our c"8testsource directory should now ha&e the following contents"

Creating your second batch file 9ow to create a atch file to ackup these files into your c"8test ackup directory automatically. 4pen up notepad and type the following" @echo off xcopy c:\testsource c:\testbackup /m /e /y The %=echo off% line tells the computer not to display anything onscreen when it runs this atch file. The second line uses the #copy command to copy all contents of the c"8testsource% directory to c"8test ackup the first time the atch file is run. The second time and all remaining times, it will only copy new files and files which ha&e changed since it was last run. It will not copy unchanged files which it pre&iously copied, e&en if you delete the copies it made from the c"8test ackup% directory. 9ow sa&e your atch file as %test ackup. at% on your desktop and dou le click it to run the script. Check the contents of your c"8test ackup directory. It should now ha&e copies of the two files you created in c"8testsource. Good stuff. 9ow open %testdoc0% in your c"8testsource directory and add some te#t then sa&e it. >un your test ackup. at atch file again, and go to the %testdoc0% file in the c"8test ackup folder. It should ha&e een updated with the changes you made in the other folder. :ou%&e now created a useful ackup utility with a simple two?line atch file that @ust takes a dou le click to run. Starting to see the potential usefulness of knowing your atch files yetA *natomy of a batch file As you%&e seen, atch files are essentially simple programs, using the uilt in command prompt commands as a programming %li rary%. +ach line in a atch file is e#ecuted se$uentially, and they do not ha&e to e num ered or otherwise identified. The computer simply reads the whole file from top to ottom and performs any commands the atch file contains. In addition to the standard command prompt commands that can e used in atch files, there are a few additional e#tras like the %=+CB4 off% command we used in the last atch file we created. These can e used to modify how a atch file works. 6et%s run through some of them with e#amples of how they work" *dditional Batch file commands

Call Can e used to call another atch file from within the current one call c:\batchfile2.bat ,cho <sed to display information and commands on the screen or pre&ent them from eing displayed. ,cho on causes all commands in the atch file to e displayed onscreen. This is the default setting. -,cho off causes no commands to e displayed. The atch file will run silently unless you use the echo command specifically as elow. echo what you want on the screen Causes whate&er te#t comes after the echo command on the same line to e printed on the screen. For <sed to select a specific set of files and run a command on each of them. for (variable) in (set of files) do (command) In another e#ample, the atch file line5 for %% in (!.txt) do del "%% " Gi&es the &aria le %227% the &alue of e&ery file ending in .t#t in the current directory, then passes that &aria le to the 3+6 command. This means that e&ery file with the .t#t e#tension in the current directory will e deleted. Goto ,o&es to different points within a atch file. The destination point must e indicated with a colon. 7or e#ampleC #oto end :end echo this is the end$ beautiful friend% the end "f Performs a command depending on a condition. I7 must include an +6S+ statement which says what happens if the condition is not met. 7or e#ample" if exist c:\myfile.txt (copy c:\myfile.txt d:\myfiles) else echo myfile.txt does not exist In this e#ample, if the %myfile.t#t% file e#ists, it will e copied to d"8myfiles. If it does not, a message will e shown indicating this. 6ook here for more I7 command options. .,/ >em is used to create comments, or ignored sections in atch files. The computer will ignore any line that egins with >+,, so you can use this command to add notations e#plaining what your file does. 7or e#ample" @echo off rem this batch file is rem desi#ned to format rem floppy disks in the a: drive format a:

Third trial batch file: getting fancy 9ow that we%&e seen some of the e#tra commands that can e used in atch files, let%s play with one of the most powerful of them, the 74> command. In this case, we%re going to alter our simple ackup atch file and make it a it more sophisticated. It%s going to differentiate etween two different types of files )te#t-'ord documents and pictures* and ack each file type up to a different directory. To set up for this we need to create two more directories in c"8. Call them &:\'ext &:\(ics 3elete the e#isting te#t and . mp files in your c"8testsource directory and create a couple of new &ersions of each. 9ow open notepad and enter the following" @echo off cd c:\testsource for %%f in (!.doc !.txt) do xcopy c:\testsource\"%%f" c:\text /m /y for %%f in (!.)p# !.bmp !.#if) do xcopy c:\testsource\"%%f" c:\pics /m /y 9ow this is a it more complicated than the files we did efore, so let%s take a close look at what this atch file is going to do. cd c:\testsource Tells the computer that the directory we are going to e working in is c"8testsource for %% in (!.doc !.txt) do xcopy c:\testsource\"%% " c:\text /m /y This line tells the computer that 74> any file with the .doc or .t#t file e#tension )meaning any standard 'ord doc or te#t file*, 34 an #copy command to copy that file to the c"8te#t directory using the same options we used in the last atch file. The confusing looking %227% character represents the &aria le that the 74> command uses to carry out this operation. 7or e#ample, if your first te#t file in the c"8testsource directory is %te#ttest0.t#t%, the atch file would look at it, see that it had a .t#t e#tension and assign it as the &alue of %227%. The second part of the command do xcopy c:\testsource\"%% " c:\text /m /y takes whate&er 227 is )in this case your %te#ttest0.t#t% file* and copies it to the c"8te#t directory. The $uotation marks around 227 are to allow the command to deal with file names containing spaces. The command then loops until it has looked at e&ery file in the current directory efore mo&ing on to the ne#t part of the atch file. for %% in (!.)p# !.bmp !.#if) do xcopy c:\testsource\"%% " c:\pics /m /y The only thing that is different here is that we are looking for graphics file e#tensions instead and copying them to the %c"8pics% directory. Sa&e your third atch file on the desktop as %tricky ackup. at% and try it out. :ou%ll see that your newest creation neatly differentiates etween te#t documents and pictures and splits them up accordingly. Batch file error levels and the goto command 'hen a command is e#ecuted in a atch file, in addition to any information it may display on the screen, it also returns an error le&el to the atch file itself. This error le&el is either errorle&el 1 )meaning no error occurred and the program worked correctly* or errorle&el 0 )an error occurred and that section of the atch file did not work correctly*. 7or e#ample, if you created a simple atch file to format a disk in your floppy )a"* dri&e like so"

@echo off format a: The format command in the atch file would return errorle&el 1 if there was a disk in the dri&e and it was formatted correctly, while if there was not, or the disk could not e formatted, it would return errorle&el0. By using these errorle&els and the G4T4 command, you can set up your atch files to do different things depending on whether the commands in them succeed or fail. 7or e#ample, you can use the I7 command along with the errorle&el returned y the format command to let the user know whether the operation was successful or not" @echo off format a: if errorlevel * #oto error !#o to the :error headin# if there+s an error in format echo your disk formatted successfully !if format returned no error$ sho, this messa#e #oto end !#o to the :end headin# to finish the pro#ram :error echo an error occurred durin# formattin# :end echo formattin# finished There%s no way we could co&er all the angles of atch files in a single guide, so we%&e got to stop here. If you%&e een following along, you should ha&e picked up enough of the fundamentals and possi ilities of atch file creation to start designing your own. Start with modifying the ones we made here to suit your own ackup needs, then progress from there.

You might also like