Sie sind auf Seite 1von 9

Creating a Batch File:

Batch files are easy to create and can be done using notepad quite easily. When you save a
batch file, specify the .bat extension, and check to make sure that the save-as-type is set to all
files. Or, you can rename .txt files, though its better practice to initially save them as batch
files. That was easy. If only I had a staples button...
Editing Batch Files:
Obviously, you can't just double-click on the batch file and edit it. Since batch is run through
DOS (the command prompt), it doesn't require compiling, so double-clicking on it will run
the program. Instead, right-click and go to edit. This will open up notepad for you with the
file.
Running Batch Files:
Treat just like an exe file, double-click.
And Now For the Fun Part-Coding, Commands, Etc.:
First off, REM is the comment command. Actually, REM is a command which does nothing,
technically speaking, and takes arguments that do nothing. Yes, even the comment is a
command that is interpreted by the computer. Thats why there are no block comments in
batch file programming. I use it throughout.
The first command you should know is the @ECHO OFF command. Note that no DOS
commands are case sensitive, and batch files do not require semicolons. By default, the
console will display all of the lines of code as they execute and then the result. Most of the
time, the source code is unnecessary to the user, creates clutter, and in other cases gives away
security and such. So, make this the first line of code in most of your programs. Next, we can
learn the ECHO command. This prints out anything we want it, and there are no string literals
in batch, so we just type what we want outputted, like ECHO Hello World. Echo with a
period after it is a blank line. So, a "hello world" program would look like:
1 @ECHO OFF
2 ECHO Hello World!

Next, we should learn the pause command. Any veteran programmer will know that in the
above code, the window will open, execute, and then close abruptly before the user can
absorb the information. So we use the pause command to hold the window open. Simply
typing "pause" will output "Press any key to continue... ", which is good, though if you don't
wish to display that message, and use your own, you can echo your message and then type
pause>null to wait for the user to press a key. So we could use either:
1 @ECHO OFF
2 ECHO Hello World!
3 ECHO.
4 pause

or
1 @ECHO OFF

2 ECHO Hello World!


3 ECHO.
4 ECHO Press any key to exit.
REM Notice the space in the echo above.
important for other uses later on
6 pause>null
5

It looks better, and will become

Though I would choose the second one, more specific to the situation, continuing isn't the
same as exiting (may cause confusion), etcetera.
The next command we will be using is the START command. This is used to run an external
executable. So if i wanted to run helloworld.bat, and it was in the same folder as the bat file
we're working with, we can use this:
1 START helloworld.bat

START can also be used to start explore, you know, to look at files. So if I didn't want to go
through my network places to find a file, you could use:
1 START \\networkedcomputername\sharedfolder

or if you wanted to start www.google.com:


1 START www.google.com

This will open google in your default html browser.


The interesting thing about the first example, to start helloworld.bat, the syntax of DOS
allows us to leave out start when running batch files. As a matter of fact, many pre-existing
DOS commands are .exe or .bat files in the system32 folder(which is in the PATH variable,
so we don't need to include the full path when starting it.). So, for out purposes, START
command.exe and command are all equivalent in cmd.exe/cmd.com's eyes (Most of the
commands in this tutorial are internal commands, meaning that they do not have a .exe
equivilant, but i'll tell you when there is an external command, which does have a .exe form).
Any modifier is an argument. Even something as basic as the echo command is really a
precompiled exe file ready for your use. This easily allows you to create your own
commands. Instead of START helloworld.bat we could simply type helloworld as if it was
our own command to work with! If you're feeling really ambitious, you can even dump your
commands into the system folders and add commands that can be used in any batch file
(though changing system files can really mess with your computer if you do not know what
you are doing, I do not advise this for novices).
A very handy command (especially when on a LAN) is the shutdown command (Also our
first external command, this one actually works for shutdown.exe). This allows you to
shutdown the computer (wow, didn't see that one coming). NOTE: The switches for this one
can be used with '/' in all windows operating systems, but XP says you have to use '-', which
is false. Use '/' because it works in XP, Vista, and Win9?. If you want to shutdown your
computer, you just type shutdown /s. There are a bunch of other useful switches, but this is
just the basics. One more switch, the /m switch. With this switch you can shutdown any
computer over the network. Now, here is where this comes to be useful. Imagine you are the
IT person of a humogous firm, and many lazy workers tend to leave their computers on after

they leave. In addition, durring potential power surges, you have hundreds of thousands of
dollars of sensitive electronic equipment on the line! You need to shutdown all of the
computers in the building at the end of the day, without walking through every floor and
clicking the off button. All you need to do is make a .bat file with the code:
1 @ECHO OFF
2 ECHO Shutting down all networked computers.

Please wait...

3 SHUTDOWN /s /m \\*
REM The above line actually shuts down all the computers on the network,
4
using the * wildcard
5 SHUTDOWN /a
REM That line keeps the shutdown from affecting your computer, /a is the
6
abort switch
7 ECHO Shutdown Finished.
8 pause>nul

Press any key to exit.

Here we start to see where batch files actually start to work to accomplish tasks. A side note
on SHUTDOWN: I have actually never shut down a computer over my network, I'm too lazy
to give myself permission to do that

Another command that actually gets a lot of work done is the copy duo: COPY and XCOPY.
Copy has a few switches, mostly just for basic ctrl-c, ctrl-v modification. Not much other
than: COPY source destination Except for the -Y switch (which goes before the source) and
overrides the "Do you wish to replace this file of the same name?" dialog. A neat trick with
copy is that it can append files of the same encoding (ANSII/ASCII, UTF, BIN, HEX, etc). If
file1.txt contained "hello", file2.txt " ", file3.txt "world", and file4.txt was blank, we could
enter:
1 COPY file1.txt + file2.txt + file3.txt file4.txt

Now, what if you need more functionality, like copying entire directories over, instead of one
or two files (copy can only have filenames as the source and either filenames or directories as
the destination). Enter XCOPY, the magic do-it-all copy command on steroids, HGH, and
several illegal narcotics (Speed, PCP for example). XCOPY is incredibly functional, but that
comes at a high price for syntax. Whenever you use XCOPY, I would suggest consulting the
syntax reference for the myriad switches, modifiers, and arguments (There are almost 30
possible args for this function, and they should be in the correct order.). This command
allows for greater use without user input. It can automatically override dialogs, copy or delete
readonly and archived files, copy (or not copy) subdirectories, copy the directory structure
without copying any files, copy encrypted files, choose whether or not to display filenames
when they are copied, copy system and hidden files, discriminate against and/or copy file
attributes, exclude files, copy authorship, and the ability to only copy files which do(n't)
already exist in the target directory. Whew. Don't make me go over the syntax, just do
XCOPY /?. Since there's no way DOS would already have this installed inside, Microsoft
made it an external command (unlike copy, which is internal). Just thinking of all the code
that would be required for all of that makes me sick. To make a batch file that does the same
thing would take multiple pages worth of code... bleh...
A little code snippet using XCOPY to make a game installer for Axis and Allies (the
computer game, I made this a long time ago and found it as I was digging through archived
files to delete, thought it would make a good example) will be provided near the end (you

need to know three or so more commands first). The file includes a directory containing all of
the DirectX data and Program Files needed to run the game, called setup files. It also has
what I call a TUI, or textual user interface (GUIs are for squares who have no life except
sitting there programming really long programs in confusing APIs that have nothing to do
with the base language, but then, squares are the people who get a lot of $
every once and a while, but don't find it an enjoyable experience).

I make GUIs

The above commands are great for making little utilities to do commonly used tasks for you,
but don't have much in the form of user input. In that they are limited. Batch Files are
EXTREMELY Weakly-Typed, meaning that there are no data types, and that you only get an
error when you try to multiply an integer by a string! Variables in Batch are just like
variables in Algebra, but with one key difference: Batch Files use variables as strings which
replace themselves by their value. For example, variables in Batch are created using the SET
command, which has two optional switches:
1 REM Some code...
2 SET a=2
3 REM That sets A to the string of two.
REM Alternatively, you can use the /A switch to indicate an
4
exp<b></b>ression.
5 REM And if you want the user to imput the value in XP or later:
6 REM Notice I've put a space at the end
7 SET /P a=Please input a number to store to a:
REM Otherwise, you'd be typing right next to the colon.
8
string ("Please...a:") can be empty

The prompt

This basically sets some values to the command. To reference the value we put it in
%variable%. Or, if you want your program run from the command line (like if your creating
your own command, such as helloworld.bat), the first argument would be %1, the second %2,
and so on. Note, number variables cannot be set once they have been set as arguments. Also,
notice how environment variables you create have the variable names enclosed by %s, while
arguments only have a leading % and then the argument number. The nice thing about batch
variables is how they work. Whenever the command prompt sees a variable, it simply
replaces it with the variable. This lets us easily output and concatenate strings and numbers
together without any type casting. An example of variable use and user input in a batch file
test.bat called from commandline with one arg:
1 @ECHO OFF
2 ECHO To call this program you typed test.bat %1
3 ECHO Your argument was %1.
4 SET /P userin=Please type a value:
5 ECHO The value you typed was: %userin%
6 ECHO Press any key to exit...
7 PAUSE>nul

OUTPUT:

C:\>test.bat helloworld

To call this program you typed test.bat helloworld


Your argument was helloworld
Please type a value: hi
The value you typed was: hi
Press any key to exit...
x
C:\>

You can see where we run into problems, though, with the weak typing:
CODE:
01 @ECHO OFF
02 REM Call this with two args, and it will add them.
03 REM File Name:demonstrate.bat
04 SET a=%1+%2
05 ECHO %a%
06 [code]
07
What if I typed [inline]demonstrate.bat 1 hi[/inline]? The program
would try to add hi and 1. See, when it simply replaces the strings,
it will replace %1 with the arg i typed, 1. So, a will actually be
1+%2. But no calculator can add 1 and hi. It would work fine if i had
the args 1 and 2. It would echo 3, if you followed along. So you must
be careful. However, you can prevent problems like this using the IF
command and the errorlevel variable. IF is another internal command
whose syntax goes like this (if it is in [] it is optional): [inline]IF
[/I] [NOT] [EXIST] CONDITION Exp<b></b>ression [ELSE
Exp<b></b>ression2][/inline]. We can use () to set it off, too, which
is especially important when you consider that the ECHO command must be
terminated by a newline. The /I switch is for evaluating a variable to
a string, and you want it to be non-case-sensetive. The NOT argument
is obvious, it reverses the truth/false of the condition. EXIST means
that CONDITION is actually the name of a file. Then, if the file
actually exists it will return true, and if there is no file of that
name, it will return false. CONDITION is what is to be
08
evaluated. Exp<b></b>ression is the exp<b></b>ression to be evaluated
if CONDITION is true (or false, if using the argument NOT). ELSE
Exp<b></b>ression2 is executed if CONDITION is false (or true, if using
NOT). IF can be used to check for errors. For example, 0 generally
means that the command was successful. Before I show you an example, I
have one more command to tell you. This is the goto %label%
command. You can set a label anywhere in the program, and then you can
jump to it using the goto command. To create a label named 1 you would
type [inline]:1[/inline] on its own line anywhere in the program. Then,
to cause the program to go to that line, you would type [inline]goto
1[/inline]. You can also use a variable, like [inline]goto
%userin%[/inline]. Since we know that it would just replace userin
with the variable's value, regardless of its surroundings, it could
goto any label it wants, from :exit to :hdlshfa;lkdhsglkxchsdlk to :3
. Hope I haven't given you too much to think about. Here's a example
of some of what we've learned so far. This is good ol' demonstrate.bat
again:
09
10 CODE:

11 [code]
12 @ECHO OFF
13 REM Call this with two args, and it will add them.
14 SET a=%1+%2
15 goto errors-%errorlevel%
16 :errors-0
17 REM This is if it was successful
18 ECHO %a%
19 goto exit
20 :errors-1
21 REM this is if it had an error:
22 ECHO Errors occured.
23 goto exit
REM GUESS WHAT, THIS REM WILL NEVER EVER BE READ!
24
OVER BY THE GOTOS

IT WILL BE SKIPPED

25 :exit
26 ECHO.
27 ECHO press any key to exit.
28 PAUSE>nul

Alternatively:
01 @ECHO OFF
02 REM Call this with two args, and it will add them.
03 SET a=%1+%2
04 IF %ERRORLEVEL%==0 (goto errors-0) ELSE (goto errors-1)
REM Instead of using goto with the variable, this uses an IF-ELSE
structure
06 :errors-0
05

07 REM This is if it was successful


08 ECHO %a%
09 goto exit
10 :errors-1
11 REM this is if it had an error:
12 ECHO Errors occurred.
13 goto exit
REM GUESS WHAT, THIS REM WILL NEVER EVER BE READ!
14
OVER BY THE GOTOS

IT WILL BE SKIPPED

15 :exit
16 ECHO.
17 ECHO press any key to exit.
18 PAUSE>nul

Both will do pretty much the same thing. Note, that you can break up if-else among multiple
lines if you're using echo or sommat:
1 IF CONDITION (

2 ECHO X
3 ) ELSE (
4 ECHO Y
5)

This will work, since the IF and the ELSE are on the same "line" (the command prompt
automatically puts all of the commands on one line for the above, however, it won't echo the
else if you have it move the result up into the parenthases. That code will work, but if it was
on one line, it would echo: X) ELSE (ECHO Y), clearly not what was intended. ECHO needs
to be on its own line. This won't work:
1 IF CONDITION (
2 ECHO X
3)
4 ELSE
5(
6 ECHO Y
7)

More readable, but this time the IF and ELSE are interpreted as seperate commands, and
since ELSE is not a command, but an argument, it generates an error. As a side note, a
common use of labels in batch is to section off areas of code to create pseudo-functions, and
jump to the function, and then back into the line after it was called. More on that in the final
snippet.
Lastly, but not least, loops:
These are relatively simple. They evaluate while a certian condition is true. This is a trick
question, however. FOR is an incredibly complex command I will not go over in this tutorial,
simply because it is out of its scope. (for you java folks its more like the FOR EACH/IN
command, but not exactly) Maybe in a later one, huh? I can't cover every command.
WHILE, however, doesn't even exist. We can make a simple loop, however, using gotos:
1 IF NOT CONDITION (goto endloop)
REM The above will skip the loop if the condition isn't met in the first
2
place. Remove if you want do...while
3 :loop
4 REM Insert commands...
REM If, after all commands are executed, the condition is still true,
the loop will restart in the line below. Otherwise, it will continue on.
6 IF CONDITION (goto loop)
5

7 :endloop

This is the same as this code in C++:


1 while(CONDITION) {
2 //Insert Commands...
3}

The two if statements and the labels replace the loop structure.
Now, i promised you some challenge code, eh? Well, here you go. Its not documented (i
removed it all) so you could try to figure out what it was doing by yourselves. It uses only
commands you have learned in this tutorial. The purpose of this tutorial was to get you
started, so that with a couple of syntax lookups, and a few googles, you could figure out
either A> how a program was working and what it was doing (structure) or B> you could
design your own code. If you can figure this out, you're golden. Thanks for reading my
tutorial.
01 @ECHO OFF
02 ECHO Axis and Allies Installer and Player
03 ECHO.
04 ECHO Windows Version 1.0
05 ECHO.
06 :RunInstall
07 set /p run=Play Game or Install (play/install):
IF /I %run%==play (START "\Autorun.exe") ELSE (IF /I %run%==install
08
(GOTO INSTALLER) ELSE (GOTO INVLD))
09 :INSTALLER
10 :USERIN
11 set /p userin=Do you wish to install Axis and Allies? (y/n):
12 ECHO.
IF /I %userin%==y (GOTO INSTALL) ELSE (IF /I %userin%==n (ECHO You
chose no) ELSE (GOTO INVALID))
14 ECHO.
13

15 :EXIT
16 ECHO Press any key to exit
17 pause>nul
18 Exit
19 :INVLD
20 ECHO Invalid Response.

Please type only "play" or "install".

21 ECHO.
22 GOTO RunInstall
23 :INVALID
24 ECHO Invalid response.

Please try again.

25 ECHO.
26 GOTO USERIN
27 :INSTALL
28 ECHO You chose yes
29 ECHO.
30 ECHO Deleting existing files (if applicable)...
31 ECHO.
IF EXIST "C:\Program Files\Axis and Allies\AA.exe" DELTREE /Y
32
"C:\Program Files\Axis and Allies"
33 ECHO Installing new files...
34 XCOPY \setup_files "C:\Program Files" /E /I /Q /R /Y

35 ECHO.
36 ECHO Finished with setup.
37 ECHO.
38 GOTO EXIT

A closing note: comments as a line with :: in front of it. This creates a label that is invalid,
and thus, is not interpreted. It is invalid and non-standards-compliant to comment your code
in this way. Though it may run slightly faster because it is skipping the line of code instead of
executing an empty function with REM, it is much safer to use traditional comments. In the
end, its personal preference. Though I think speed (and really, not that much, one line of code
is all that's skipped) is outweighed by being standards-compliant, and having a lower chance
of bugs in my program (occasionally, a double colon will fail and wreck the program). That is
all. Just be wary, Batch programmers and DOS Hackers (who of course use a lot of .bat
files)like to break the rules

Das könnte Ihnen auch gefallen