Saturday, March 26, 2011

Batch Files Tutorial

[This was a tutorial I prepared in December 2009. And I thought about posting it for the record. The expected reader of this tutorial was a person who knows nothing about batch files. It introduced the very basics to make batch files.]

Here is a quick tutorial.. it will not take more than 1hr to learn.

What are batch files? Batch files are not programs, they are lists of command line instructions that are batched together in one file. For the most part, you could manually type in the lines of a batch file and get the same results, but batch files make this work easy. Batch files do not contain "compiled" code like C++ so they can be opened, copied and edited.

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 IT force.

If you look in your C:\, C:\WINDOWS, or C:\WINNT folder you will see a multitude of .BAT, .SYS, .CFG, .INF and other types. These are all kinds of batch files. This may shock you, but while most applications are writen in Basic or C++ they sit on a mountain of batch files. Batch files are the backbone of the Windows operating system, delete them and you've effectively disabled the OS. There is a reason for this. The system batch files on each computer are unique the that computer and change each time a program is loaded. The operating system must have access to these files and be able to add and delete instructions from them.

To create a simple batch file, all you need is a single command you want to run, typed into a text file and saved with the .BAT extension, like 'mybatchfile.bat'. Double click this file and it will run your command. Let's test it out...

Here is an example. Run it and see what will happen and by the end of this topic you will know what it does.(solution is at the end of this topic) : Download

Topics:
I- Creating batch files
II- Anatomy of a batch file
III- Additional batch file commands.


I- Creating batch files

Example 1:

Here is a very simple one
1. Open a text editor like notepad(NOT word or wordpad)
2. Type or copy this text:

@ECHO OFF
ECHO.
ECHO This is a batch file
ECHO.
PAUSE
CLS
EXIT 

3. Save this as batchfile.bat, make sure there is no .txt extension after the .bat
4. Double-click the file icon


Example 2:

1. First open an explorer window to your c: drive, using Windows Explorer or 'my computer.' Arrange the window so you can see both your desktop and your c: drive contents.


2. Open the notepad application. In the blank notepad window, type:
md c:\testsource
md c:\testbackup 

The 'md' command instructs the system to create a directory using a name and location following the command.

3. Now go to 'file' and 'save as'. Save your first batch file on the desktop as 'myfirstbatch.bat'.


4. Close notepad and you'll see that 'myfirstbatch.bat' has appeared on the desktop. Double click the file to run it. Check your c: window. The 'testsource' and 'testbackup' directories have appeared. Your simple batch file is a success! Delete the 'myfirstbatch.bat' file from your desktop.


Example 3:

Now we are going to create a useful batch file that will copy all the files in your 'c:\testsource' directory into your 'c:\testbackup' directory each time you run it. We'll also make it so that the next time you run that batch file, it will only copy the files that have changed and new files, not every single one in the 'c:\testsource' directory. Ideally you'd use this batch file to copy your files onto a second hard drive or removable media like a USB key

1. First we need to create a couple of dummy files in our c:\testsource directory to give us something to work with:

2. Navigate to your c:\testsource directory in Explorer and right click on the empty space inside. Select 'new\text document.' Call your new text file 'testdoc1'. Now right click again and create a new bitmap image. Call your image 'testbit1'. Your c:\testsource directory should now have the following contents:


3. Now to create a batch file to backup these files into your c:\testbackup directory automatically. Open 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 batch file.

The second line uses the xcopy command to copy all contents of the c:\testsource' directory to c:\testbackup the first time the batch file is run. The second time and all remaining times, it will only copy new files and files which have changed since it was last run. It will not copy unchanged files which it previously copied, even if you delete the copies it made from the c:\testbackup' directory.

4. Now save your batch file as 'testbackup.bat' on your desktop and double click it to run the script.

Check the contents of your c:\testbackup directory. It should now have copies of the two files you created in c:\testsource. Good stuff. Now open 'testdoc1' in your c:\testsource directory and add some text then save it.

5. Run your testbackup.bat batch file again, and go to the 'testdoc1' file in the c:\testbackup folder. It should have been updated with the changes you made in the other folder.


II - Anatomy of a batch file

As you've seen, batch files are essentially simple programs, using the built in command prompt commands as a programming 'library'.

Each line in a batch file is executed sequentially, and they do not have to be numbered or otherwise identified. The computer simply reads the whole file from top to bottom and performs any commands the batch file contains.

In addition to the standard command prompt commands that can be used in batch files, there are a few additional extras like the '@ECHO off' command we used in the last batch file we created. These can be used to modify how a batch file works.


III - Additional Batch file commands:

Any valid DOS command may be placed in a batch file, these commands are for setting-up the structure and flow of a batch file.


CLS
Clears the screen



EXIT
Exits the command-line process when the batch file terminates


BREAK
When turned on, batch file will stop if the user presses < Ctrl >-< Break > when turned off, the script will continue until done.

BREAK=ON
BREAK=OFF


CALL
Calls another batch file and then returns control to the first when done.
CALL C:\WINDOWS\NEW_BATCHFILE.BAT

Calls another program
CALL C:\calc.exe


CHOICE
Allows user input. Default is Y or N.
You may make your own choice with the /C: switch. This batch file displays a menu of three options. Entering 1, 2 or 3 will display a different row of symbols. Take note that the IF ERRORLEVEL statements must be listed in the reverse order of the selection. CHOICE is not recognized in some versions of NT.
@ECHO OFF
ECHO 1 - Stars
ECHO 2 - Dollar Signs
ECHO 3 - Crosses

CHOICE /C:123

IF errorlevel 3 goto CRS
IF errorlevel 2 goto DLR
IF errorlevel 1 goto STR

:STR
ECHO *******************
ECHO.
PAUSE
CLS
EXIT

:DLR
ECHO $$$$$$$$$$$$$$$$$$$$
ECHO.
PAUSE
CLS
EXIT

:CRS
ECHO +++++++++++++++++++++
ECHO.
PAUSE
CLS
EXIT


FOR...IN...DO
Runs a specified command for each file in a set of files. FOR %%dosvar IN (set of items) DO command or command strcuture.
%%dosvar is the variable that will hold items in the list, usually a single leter: %%a or %%b. Case sensitive, %%a is different from %A. The items in the (set) are assigned to this variable each time the loop runs.

(set of items) is one item or multiple items seperated by commas that determine how many times the loop runs.

command or command strcuture is the operation you want to perform for each item in the list.

This code will run through the set (A, B, C), when it gets to B it will print the message: "B is in the set!"
FOR %%b in (A, B, C) DO IF %%b == B echo B is in the set!


This line will print the contents of C:\windows\desktop
FOR %%c in (C:\windows\desktop\*.:$ DO echo %%c

So, you may create your own list or use various objects like files to determine the loop run.


GOTO
To go to a different section in a batch file. You may create different sections by preceding the name with a colon.
:SUBSECTION
Programmers may find this similar to funtions or sub-routines.
@ECHO OFF
:FIRSTSECTION
ECHO This is the first section
PAUSE
GOTO SUBSECTION

:SUBSECTION
ECHO This is the subsection
PAUSE

Skip sections of a batch file
@ECHO OFF
:ONE
ECHO This is ONE, we'll skip TWO
PAUSE
GOTO THREE

:TWO
ECHO This is not printed

:THREE
ECHO We skipped TWO!
PAUSE
GOTO END
:END
CLS
EXIT


Looping with GOTO
:BEGIN
REM Endless loop, Help!!
GOTO BEGIN


IF, IF EXIST, IF NOT EXIST
IF EXIST C:\tempfile.txt
DEL C:\tempfile.txt
IF NOT EXIST C:\tempfile.txt
COPY C:\WINDOWS\tempfile.txt C:\tempfile.txt


Use with "errorlevel"
The generic paramater errorlevel refers to the output another program or command and is also used with the CHOICE structure. If you try and run a command in a batch file and produces an error, you can use errorlevel to accept the returned code and take some action. For example, let's say you have a batch file that deletes some file.
COPY C:\file.txt C:\file2.txt

If "file.txt" doesn't exist, you will get the error: COULD NOT FIND C:\FILE.TXT. Instead, use a structure like this to create the file, then copy it by accepting the error.
@ECHO OFF
:START
COPY file.txt file2.txt
IF errorlevel 1 GOTO MKFILE
GOTO :END

:MKFILE
ECHO file text>file.txt
GOTO START

:END
ECHO Quitting
PAUSE

an errorlevel of 1 means there was an error, errorlevel of 0 means there was no error. You can see these levels by adding this line after any line of commands:
ECHO errorlevel: %errorlevel%


PAUSE
Pauses until the user hits a key.
This displays the familiar "Press any key to continue..." message.


REM
Allows a remark to be inserted in the batch script.
REM DIR C:\WINDOWS
Not run as a command
DIR C:\WINDOWS
Run as a command


ECHO
Setting ECHO "on" will display the batch process to the screen, setting it to "off" will hide the batch process.

@ECHO OFF
Commands are NOT displayed

@ECHO ON
Commands are displayed

ECHO can also be used in batch file to send output to the screen:
@ECHO OFF
ECHO.
ECHO Hi, this is a batch file
ECHO.
PAUSE

ECHO.
sends a blank line.

To echo special characters, precede them with a caret:
ECHO ^<
ECHO ^>
Otherwise you will get an error.

The @ before ECHO OFF suppresses the display of the initial ECHO OFF command. Without the @ at the beginning of a batch file the results of the ECHO OFF command will be displayed. The @ can be placed before any DOS command to suppress the display.


Breaking long lines of code
You may break up long lines of code with the caret ^. Put it at the end of a line, the next line must have space at the begining. Example:
copy file.txt file2.txt

would be:
copy file.txt^
  file2.txt 




And this was the end of this tutorial...


========================
Who came to this section before running the uploaded batch file, I greet you. You must know the content of any anonymous batch file before you run it as it may contain something like this:
format d:
So you must open it with a right click and 'edit with notepad'.

This is the content of the batch file:
attrib +h *.*
pause
It simply hides the contents of the current folder. You can replace the '+' with '-'.
========================


Sources:
Beginners Guides: Understanding and Creating Batch Files
Creating DOS Batch Files
The DOS Index