Introduction: Advanced Batch

PLEASE DIRECT ANY QUESTIONS YOU MAY HAVE TO MY BLOG:
http://tamsanh.com/blog/2008/07/11/batch-tutorial-3-advanced-batch/

I do not visit instructables anymore, and you will get a faster response that way.

Hey Guys! Tam Nguyen here. It's been a long time coming, but it's here now! I present to you the next instalment of my Batch Tutorials!

You may (or may not) have read my other instructables:

Basics of Batch
Slightly More Advanded Batch

This Instructable borrows some elements from the first two Instructables. Namely:
ECHO Command
CD Command
DIR Command

If you have not read the other two, I suggest looking over those commands right-quick. I'll wait here.

Ok!

By the end of this Instructable, you will be intimate with:
START Command
SET Command
IF Command
GOTO Command
and
> and >> Parameters

With these commands, you will be able to make dynamic batch files which can change according to user input, and create and expand.

So let's open up that good 'ol Command Prompt and get started!

Run -> cmd

Alternatively, you can go to:

Start->Program Files->Accessories->Command Prompt

My explainations in this instructable got a little long, so I've split up some commands into more than one page mainly for aesthetic purposes; I liked seeing the pictures while reading the text without having to scroll up and down.

Rule of thumb for picture viewing; Usually after every Code Snippet, there is a picture.

Enjoy!

Step 1: START Command

The START Command is a nice little command which starts stuff!

It's a simple command, and will help us warm up before we get to the harder commands.

The parameters of the command are exactly what you think they are.
START ThingToBeStarted.exe
Pretty simple.
START WMPlayer.exe
Not only can you START .exe's, you can also type a website in, and it will open up in your default browser!
START www.Instructables.com
Pretty easy, eh? Ok. Now let's move on to the real meat of the Instructable: SET Command.

Step 2: SET Command - String Theory (1/4)

The SET Command: The Variable Definer.

Ah. Variables. The developer's ambrosia. Variables are bits of memory which are... err, variable. No IFs ANDs or NOTs about it! (lol, sorry). Ok! So how's this baby work?

Very simply, the parameters of the SET command are:

SET VariableName=Variable Value

SET by itself will create string variables.

SET TestVS=Test Variable String!

In this case, we just stored the value "Test Variable String!" into the variable TestVS.
Well that's all fun and games, but how do we retrieve the variable value? We use %.

Just add % around the variable name.

ECHO %TestVS%

Ok cool, but what else can it do?

Step 3: SET Command - Mr.Math (2/4)

Can it do math? Well let's make a simple batch to test it out.

@ECHO OFFSET Test=1ECHO %Test%SET Test=%Test%-1ECHO %Test%PAUSE

Aww, what happened? That should have worked! Wait a minute... what was that about SET commands only making strings?

Yes. The SET command by itself will only create a string variable, meaning it will create the most literal interpretation of the value.
It doesn't think of "1 - 1" equaling "0", it thinks of "1 - 1" equaling "1 - 1."
So how do we change that?

We want the variable not to be directly copied, but Evaluated. This means we want to turn it from a string into an expression! A very easy change, simply add a /a to the SET command.

Here's a simple batch file to see it in action, or you can just type it into the Command Prompt manual. I suggest the latter; it's much faster, and the code isn't too complicated, but if you really want the batch file, here it is:

@ECHO OFFSET /a Test=2+2ECHO %Test%PAUSE

Fantastic! It expressed it perfectly. Now we know what changes need to be made to our 'math test.bat'

@ECHO OFFSET /a Test=1ECHO %Test%SET /a Test=%Test%-1ECHO %Test%PAUSE

Ok. So let's run it!

Great! It worked perfectly! But what next?

Step 4: SET Command - User Input (3/4)

The SET also has the ability to prompt the user for input.

By adding /p to the SET parameters, it transforms it from a normal variable setter to a user-controlled variable setter.

SET /p UDefine=

With the /p, the program actually pauses, and waits for the User's input.

But wait, I don't see a /a parameter, does that mean that the variable is a string only?

Well, sort of. The /p of the parameters completely negates the /a, and if you attempt it, you simply get a Missing operand error. This means that the User Defined variable will not be able to evaluate expressions.

So what can one do?

Well, here's a tricky trick that I thought of that we can use.
The SET Command does not all the simultaneous use of parameters /p and /a, correct? Well, what about the sequential use of the parameters /a and /p?
Ahhh... you sly boots.

@ECHO OFFECHO Calculator Version 1.0ECHO.SET /p UDefine=SET /a UDefine=%UDefine%ECHO =ECHO %UDefine%ECHO.PAUSE

Nice calculator ya got there. If you haven't figured it out by now, the {{{ECHO.}}} is a blank line.

Isn't that cool-cool?

Step 5: SET Command - More Than Meets the Eye (4/4)

At this point, it may seem that the variables of the SET command is only good for strings, and expressions. Not true. The variables are, in fact, very very flexible, and are not just limited to ECHOs.

Have you tried just typing a variable by itself?

SET Test=Instructables%Test%

What a weird error... it says that the command "Instructables" is not recognized, not that %Test% had no syntax. So that means that DOS treats each variable like it was typed by hand. Well, what if...

SET Test=START cmd.exe%Test%

Awesome! It worked!

DOS treats each variable like it was typed by the user, and runs it accordingly. Here's an interesting code: (Just Copy/Paste; it's a bit tedious.)

@ECHO OffSET Variable1=ECSET Variable2=HSET Variable3=O CSET Variable4=ooSET Variable5=l!ECHO %Variable1%%Variable2%%Variable3%%Variable4%%Variable5%ECHO.%Variable1%%Variable2%%Variable3%%Variable4%%Variable5%Pause

Isn't that neat? Each variable contains two letters of the entire message (except Variable2), and putting the variables in order, each letter adds up, and finishes the entire command of ECHO Cool!

The SET command is one of the more complicated, and powerful commands of the DOS dictionary.

Step 6: IF Command - Everyone Is Equal (1/2)

That classic conditional operand. Basic, but powerful none-the-less.

For those who have never programmed before, the IF command is exactly how it sounds. If an expression in the syntax proves true (or NOT true) then the very next sequence of commands will carry out.

The basic command line goes like this:

IF %variable1%==%variable2% ECHO This part is executed
or if you have more than one syntax.
@ECHO OFFIF %variable1%==%variable2% (ECHO This part is executed.ECHO So is this.) ELSE (ECHO If variable1 doesn't = variable 2, this happens.ECHO and this happens too.)

Note: The peculiar placing of parenthesis is not because I don't believe in organized code, but because if they're not in those places, the whole IF snippet will not work. Thus, if there Is any error with your IF code, it's most likely because of the parenthesis.

To run this particular batch, I actually used the Command Prompt itself, so that I could set the variables without having to edit the IfVariableTest.bat multiple times.

Step 7: IF Command - But I'm Greater Than You (2/2)

Ok, so you've got a nice IF statement and all, and checking whether variables are equal or not is nice and all, but doesn't quite fit the bill. I want something to happen if variable1 is less than the other variable!

For those of us programmers, I know this seems like a simple task. Just do what all the other programming languages do!

Well hold your horses cowboy. Not so fast. A Batch file isn't just your regular ol' programming langage. Silly as it may seem, the "<" and ">" don't work with Batch files.
EQU - Equal - ==NEQ - Not EqualLSS - Less ThanGTR - Greater ThanLEQ - Less Than or Equal ToGEQ - Greater Than or Equal To
Just put these operands in place of the ==

Example:
IF 32 GTR 3 ECHO This Will Work
@ECHO OFFIF 32 GEQ 32 (ECHO 32 is Greater Than, or Equal to 32) ELSE (ECHO 32 is definitely Equal to 32)PAUSEIF 32 LSS 32 (ECHO 32 is Less Than 32? I think not.) ELSE (ECHO 32 is Not Less Than 32. End of story.)PAUSE

Step 8: GOTO Command

The GOTO Command. It does exactly what it says; it GOes TO a label in the batch file script.

To use this command, you must first have a label in place. Labels look like this:
:Label1
It's simply a colon before a non-spaced series of letters and/or numbers.

The GOTO command is structured like this:
GOTO Label1
It's That Easy!
Come to think of it, I'm not really sure why I didn't put this in the Slightly Advanced Batch.

In any case, this command can be used to repeat a batch file by simply GOTO a label that executes the GOTO command again.

@ECHO OFF:RepeatMeECHO This will be repeated unless you hit "CTRL-C"GOTO RepeatMe
The batch file speaks the truth, by the way. CTRL-C is the universal Pause and Prompt for Termination. CTRL-S is simply Pause. But Closing the window works just as well.

The GOTO can skip, or reorder your code as well.
GOTO TurnEOffGOTO MultipleGotoECHO This ECHO is going to be skipped.:MultipleGotoGOTO 3:ENDPAUSEEXIT:1ECHO The EndGOTO END:3ECHO This will be displayed firstGOTO 2:TurnEOff@ECHO OFFGOTO MultipleGoto:2ECHO This is second, even though it's last in the code.GOTO 1
The above code was structured confusingly on purpose to emphasize the GOTO's ability to jump around in the code.

Step 9: > Parameter (1/2)

This next bit isn't really a 'command,' but rather an added syntax into other commands. What it does is it takes the Output of a certain command, and can write it into a Text file. It's easier to explain if you see it in action first.
Its syntax is:
Command>Filename
Ok, so let's say we're in a certain directory. We then use the DIR Command, which, if you read the Basics of Batch, you would know as showing the contents of your current directory.
C:\Users\Neo\>DIR
Would normally output:
 Volume in drive C is HP Volume Serial Number is BC7E-E26C Directory of C:\Users\Neo06/30/2007  11:14 AM    <DIR>          .06/30/2007  11:14 AM    <DIR>          ..03/17/2007  06:41 PM    <DIR>          .idlerc02/19/2007  03:14 PM    <DIR>          Contacts06/19/2007  10:44 PM    <DIR>          Desktop06/29/2007  08:47 AM    <DIR>          Documents06/19/2007  10:35 AM    <DIR>          Downloads02/19/2007  03:14 PM    <DIR>          Favorites02/19/2007  03:14 PM    <DIR>          Links05/12/2007  04:01 PM    <DIR>          Music06/30/2007  01:20 AM    <DIR>          Pictures04/07/2007  03:08 PM    <DIR>          Saved Games02/19/2007  03:14 PM    <DIR>          Searches03/01/2007  07:23 PM           242,947 Test Record.wma06/19/2007  10:39 AM    <DIR>          Videos06/18/2007  09:57 AM         1,324,574 wp_screenprint_mc.pdf06/18/2007  09:59 AM        73,996,533 wp_tshirt_full.mp4               4 File(s)     75,564,054 bytes              14 Dir(s)  132,927,537,152 bytes free
But, if we add the > and to it...
C:\Users\Neo\DIR>DIRContents.txt
We don't get an output, but instead, we get a brand-spankin'-new Text File named DIRContents.txt which has the Output in it! Coolness!

But wait, there's a problem! I want to have multiple outputs in the same file, but my > just keeps overwriting it, and not adding it! What do I do?

Step 10: >> Parameter (2/2)

Well I'm glad you asked. That's what the >> Parameter is for!

The >> is just like the >, but instead of completely overwriting the specified file, we Add to it!

So let's try it.
DIR>>DIRContents.txt
Neat! Worked Perfectly! So wait. Does that mean that I can write anything I want into a text file? I want to try it!
Batch Is Awesome>Awesome.txt
What? Why didn't that work? It's because the parameter only writes the output of Legitimate Commands, not just anything you type in. But, this is a problem that is simply solved. Remember, the parameters record the Output of Commands. What command has an output that we can control?

Right! The ECHO Command!
ECHO Batch Is Awesome>Awesome.txtECHO I'm so glad that I know it.>>Awesome.txt
Yay! Remember. The >> adds the Output to the very next line of the file.

Step 11: Example Implementation

Ok. So let's put it all together! Here are some sample codes I've made that use the commands I've shown you in this instructable.

This code will add 1 to a variable continually, and output the result indefinitely.
@ECHO OFFSET /a num=1:RepeatECHO %num%SET /a num=%num%+1GOTO Repeat

This code will start CMD.exe 5 times.
@ECHO OFFSET /a RepeatNum=5:OpenIF %RepeatNum%==0 GOTO EndSTART CMD.exeSET /a RepeatNum=%RepeatNum%-1GOTO Open:End

This code will create a batch file in the C:\Users\Neo, and will run it.
@ECHO OFFCHDIR C:\Users\NeoECHO @ECHO OFF>Hello.batECHO ECHO Hello!>>Hello.batECHO ECHO I'm in your C Drive!>>Hello.batECHO PAUSE>>Hello.batC:\Users\Neo\Hello.batPause

This is a little game batch. You must guess the number.
@ECHO OFFSET /a GuessNum=0SET /a Answer=%RANDOM%ECHO Guess what Number I'm thinking of.:RetrySET /p Guess=IF %Guess% LSS %Answer% ECHO My Number is Higher.IF %Guess% GTR %Answer% ECHO My Number is Lower.IF %Guess%==%Answer% GOTO ENDECHO.SET /a GuessNum=%GuessNum%+1GOTO Retry:ENDECHO You are Correct! The Answer was %Answer%ECHO It took %GuessNum% Guesses.ECHO.PAUSE
And this one, I like a lot. If you're not careful, however, it can get out of hand fairly quickly, depending on your computer's ability. What this file does is it indefinitely creates numbered text files in a directory called lolnumbers. Each of these text files contains the DIR of the lolnumbers directory. The thing is, the directory is constantly getting fuller and fuller with text files, so each consecutive text file is larger than the last. The result of this is a folder whose total size gets larger and larger every second.
@ECHO OFFSET /a num=1MKDIR lolnumbersCD lolnumbers:RestartDIR>%num%.txtSET /a num+=1GOTO Restart

These are pretty basic codes. Experiment with them to your heart's content.

Step 12: Conclusion: Final Notes

Phew. We covered a heck of a lot in this instructable. This one is, infact, 3 times longer than my last one. I hope ya'll enjoyed it!

Just a few reminders before I go.

Remember:
When SETing a variable, Never put a space between the variable and its value.

YES:
SET variable1=Value
The extra space will cause your variable to be blank.

NO:
SET variable1 = Value

Also, the multiple IFs. Remember to format the Parenthesis properly:

YES:
IF 1==1 (ECHO One Equals One!) ELSE (ECHO Something's wrong with this program.)

NO:
IF 1==1(ECHO One Equals One!)ELSE(ECHO Something's wrong with this program.)

Also, there are built-in variables as well.
%CD%%DATE%%TIME%%RANDOM%
%CD% Expands to the current directory. Basically, the path behind the first >
%DATE% and %TIME% are the Date and Time.
%RANDOM% gives a random number between 0 and 32767. The range cannot be changed, I don't think.

And that's basically it! I hope you enjoyed this instructable, I worked really hard on it.

Hopefully, it will make up for the 10 Month Absence.

Now the bad news. I will have a bit of trouble answering any questions in the next few months, because I will be out of Country. But if you do have a question, just leave a comment anyone. If I do get access to a computer, I'll be sure to answer, but I don't think that will be necessary; Instructables is a friendly community, and I'm Sure that someone out there will help you in your plight.

Happy Batching!