In this tutorial you will:
• Learn how to make a batch file
• Learn how to do basic commands
• Learn how to use the IF command properly
• Learn how to use variables and ask questions
• Understand how batch files work
If you are looking for “viruses” then look elsewhere.
My goal for this instructable is to make it one of the biggest, most comprehensive and most reliable batch instructables out there.
Step 1: Contents Page
Step 2: Introduction
Let's look at some basic principles of making a batch file.
- Batch files have the extension of ".bat". That isn't the only extension that can be used however, you won't learn them here (probably).
- You can create a batch file with most text editors (such as notepad). I use Notepad++, but you can use anything you like.
- The commands that a batch file uses are read top to bottom, left to right.
- Commands can be written in UPPERCASE or lowercase. It doesn't really matter. PAuSe will be interpreted the same way as PAUSE or pause.
Some things you should know about this tutorial:
- Any code that I use (including command names) will be in italics.
- Any code that you will need to replace (such as a file path) will be in bold-italics.
- Any output from code that I've written will be in italic-subscript.
- The script snippets that I write (that I say to test out) are probably best if you type them into the command prompt (cmd.exe).
Some background information...
- When naming a script, save it as name.bat.
- The command prompt can be found at "C:\Windows\System32\cmd.exe" while notepad can be found at "C:\Windows\System32\notepad.exe".
- It's not necessary, but you could make a folder in your C drive named "Batch" for all your scripts (so they are easily accessible).
So, let's begin out batch journey!
Step 3: The Basics
So, let's start with the echo command.
The echo command is used to output text onto the console. Let's have a look at its syntax (how to use it).
The usual syntax is echo Text to be displayed. It's a pretty straight forward, simple command. If you use echo by itself, it will output the echo status (this will be explained a little further on). To output a blank line, put in echo.
So, you have output on the screen, but how do you get rid of it? That's where the cls command comes in. There's not really a varying syntax to this command, it's just plain old cls. As you might have guessed, cls stands for "clear screen".
I've made a script, but it just opens and closes. What gives?
Well, assuming you've used the two commands we've discussed (and there's no errors), it's because the commands are executing so fast that the screen only flickers open and closed. You can combat this with the pause command (among others).
The syntax is pretty simple, it's just plain ole (<- not a spelling mistake) pause. The command will suspend the processing of the script and displays the message "Press any key to continue . . .". Although useful, it's somewhat limited. New techniques will be discussed later.
Next thing on the list is comments. Comments are used in long pieces of code to help not only others who are reading them, but also you. There are loads of ways to make a comment, but the official way is by using the rem command. Comments will not be displayed on the console (there are some exceptions which will be visited on later). Another way to make a comment is to have two invalid characters, such as :: or :;. I will be using a double colon (::) to make my comments, but it's good to have an original style.
So, when I was learning Python, I came across a really good website that teaches you how to do something and then gives you a script snippet for you to complete.
Me, thinking it was a great idea, have decided to implement this into my instructable. So, without further ado, here is your task...
Using the code below, you need to
- Output the sentence I quite enjoy writing code..
- Pause the script and then clear the screen.
- Output the current status of echo, then pause again. Once you press a button, the screen should close.
Here is the snippet...
::Change the code below.
::The rest is up to you.
If you get stuck, answers will be on the last page of this instructable (generally speaking).
Step 4: Variables, Arithmetic and the Set Command
Hopefully you've all reached a degree of math where you begin to use pro-numerals (they might be called something different in your curriculum). Basically, these are variables. Variables are called so because their values are always changing. Let's have an example.
Here's an equation that you might have gotten at school (assuming you still go to school). 5x-6=19. Hopefully most of you already know that x has the value of 5. This is not a math lesson, so I won't be teaching you anything complicated today. Moving on, variables basically just store information to be recalled at a later date.
Within this step you'll be getting familiar with both variables, and the set command. Take note that this step will not delve into everything to do with the set command, nor everything to do with variables.
So, let's learn about the set command. The set command is a command that just so happens is most often used to set the value of a variable. Because its syntax varies, I'll be showing you just the basics. So, if you like, you can run the below code and see what happens.
::Setting the variable's value with the set command.
::To recall a variable's value, surround it in percent signs.
What you should see is the word "value" on your screen (with the default pause message). As I didn't mention, the variable's name was surrounded in percent signs. This tells the interpreter to recall the variable's value that is enclosed in the signs.
Unlike other languages you may learn (or have already learnt), you do not need to declare the type of variable (yes, there's more than one type). So, the following snippet will not work.
set string My_String=My_Value
Although no error message (we'll learn more about error messages and handling later) will be produced, the variable "My_String" will not be set.
Now, because I might have confused you a little, you don't need to remember anything about variable's types, I was just throwing that in there.
So, what can you do with variables?
Well, there's a lot you can do with variables, but we're going to look at good old arithmetic to get you started (there will be a step on string manipulation at some point).
So, unlike on paper, you can't write the division sign, nor the multiply sign (an x doesn't count). So, instead, there are symbols that are used to replace them.
The ones you'll be learning today are addition, subtraction, division and multiplication.
So, here are their symbols.
Subtraction - (hyphen)
Multiplication * (asterisk)
Division / (slash)
Now that you've learnt the basics, try out this snippet.
echo %var1% %var2% %var3%
What you should see may surprise you. What you would expect is 5 8 8. Instead you get 5 10-2 5+3.
What is this devilry?
Well, the answer is simple. The set command, without parameters (these will be explained later), is used to set the value of a variable, not do math. To make it do your math for you, you need to add the /a switch (also known as a parameter, which will be explained later).
So, try this modified version of the code.
set /a var2=10-2
set /a var3=%var1%+3
echo %var1% %var2% %var3%
The output should be 5 8 8, just like you expected. The a in /a stands for (at least I think it stands for) arithmetic.
The /a variable tells cmd to actually do some math, not just put the symbols into the variable. It's very useful for keeping count of how many times something has happened or doing some basic math to ensure everything is running smoothly.
Also, as you've just found out, you can put variables in your equations and it will still work. In fact, the interpreter is so smart that it recognizes when variables are being used, and you don't need to surround them in percent signs. So, the following code will work just as well.
set /a var2=var1-3
set /a var3=var1+var2
echo %var1% %var2% %var3%
Pretty cool, eh?
There will be a more advanced (but not too advanced) section on arithmetic and the set command very shortly.
So, now that you've learnt some stuff about variables and the set command, let's put your knowledge to the test.
I'm going to stop holding your hand through stuff now, and give you the code snippet, some comments and an expected outcome. Remember, an answer will be found on the last step.
::Once again, you'll learn about the above code later.
::These are the variables you will be using.
set /a var4=%var2%*5
::You'll need two more set commands about here.
::You should return the values here, each on a separate line.
echo Var1: %var1%
::Continue on here.
Here is what the output should look like when you're done. I've decided to make the output of commands smaller than normal text (and in italics), for clarification.
Press any key to continue . . .
Onto the next step!
Step 5: Some More Advanced Principles and Modifiers
So, let's kick this step off with some stuff we already learnt.
While setting the value of a variable, you don't need to use percent signs with your variable names.
set /a var2=var1 /5
Will get the same result as
set /a var2=%var1%/5
There are these weird things called parameters that affect how a command is executed (the "/a" in "set /a var1=50" is a parameter).
Parameters go by many names, including but not limited to
Now, onto the explanation to why I used @echo off in my code.
As I mentioned earlier, the echo command (without any words to be displayed) will output the current echo setting. The output will either be ECHO is on. or ECHO is off.
If ECHO is on, then the commands that are used will be displayed (as will the current prompt, which you will learn about later).
If ECHO is off, only the output of the command will be displayed (including error messaging).
Here's an example of some code...
echo Only the output of commands are displayed.
echo The command, output and prompt are displayed.
So, I've explained why I used echo off, but why did I put an @ sign in front of it?
Well, before you set echo to be off, the commands will still output all this random stuff. The @ modifier suppresses, not the output, but the weird stuff you see before the output (something like C:\Users\User_Name>echo Text.).
You can try this out if you want...
echo Echo will now be turned on
@echo All of the commands have an @ sign on them, which means it keeps the normal output.
As you can see, everything looks normal. There's no random text there.
Unlike most steps, there will not be a task here (lucky you), but feel free to reflect on what you've learnt.
Step 6: Parameters/Ribbons/Arguments/Flags/Switches
So, what do switches do and what makes them so great?
Well, switches alter the way commands react to certain things. An example that you've already seen is the /a switch in the set command. When it isn't used, it treats operators (things like plus and take signs) literally (meaning it's not a plus sign, it's just another character). Because of that, you can't do any math and there would be loads of constraints in what batch files can and can't do.
What makes them so great is the fact that without them, there'd have to be a separate command for each thing you want to do. For example, instead of the /a switch in the set command (I'm pretty sure this will be the last time I reference that) might be a different command altogether (perhaps setA). This saves you from remembering millions of different commands (now you just need to remember complicated syntaxes instead, hooray!).
Here's an activity for you to try...
Put this into a batch file called params.bat.
echo The first parameter is "%1".
echo The second parameter is "%2".
::Exit is another command that you'll learn about soon.
Now, I'm about to show you a neat trick that elite programmers use (slight fabrication). press SHIFT and right click the folder that your script is in (mine would be C:\Batch\Excercise1) and click Open Command Window Here (or press W on your keyboard).
Assuming you've done it correctly, a command window just opened up in your face. This saves you so much time navigating to the directory all your stuff is saved in, so feel free to use it as often as possible.
Now, onto our activity. Type params Y N.
What you should have gotten is
The first parameter is "Y".
The second parameter is "N".
Now clear the screen (btw, feel free to put in echo off to stop all that unwanted jargon on the command prompt) and type in params "Farts are..." smelly. What you should get out of it is
The first parameter is ""Farts are..."".
The second parameter is "smelly".
As you can see, if you surround parameters in double quotes then it'll be interpreted as one parameter. Neat, huh?
You might have figured this out already, but parameters are basically used to 'feed' information to other batch scripts (and some others too).
Some fun facts and limitations about parameters:
- Parameters are like variables except for the fact that you recall them by using a single percent sign at the front (parameters are always the numbers 0-9, you'll learn about %0 below). E.g %5 is the fifth parameter.
- There can only be 10 parameters at a time (0-9) (not entirely true, but you'll learn about that later). Parameters 1-9 and defined by whatever is executing it, whereas the %0 in the file path to the file (well, there's more to that, but you won't learn about that 'til later).
- "Parameters" is a really annoying word to type over and over again.
Let's get onto your test. This one will incorporate almost all sections you've learnt so far.
Your task, if you choose to accept it, is to create a script to multiply two numbers and display the results.
So, if I put in multiply 5 4, I would get 5*4=20 as an output.
I'll start you off
::Put your code here
If you get stuck, look at the back for answers.
Step 7: If Command
These are what the commands stand for
NEQ stands for NOT EQUAL
EQU stands for EQUAL
GTR stands for GREATER
LSS stands for LESS or LESSER
The IF command however is still used to survey something but it is used as the basis for the other commands and many more. These commands can be used to activate other effects and commands such as: “IF %feeling% EQU Happy echo That’s Great!
This command means that if the value of feeling is Happy then display the text "That’s Great!"
Now, there is also the ELSE command. This command is only available if delayedexpansion is on. To do this in a batch file, put in the code "setlocal enabledelayedexpansion". In CMD, type "CMD /V:ON" into the interpreter.
What can this do? It can delay the processing of certain if commands and variables so that it can read further ahead and make a judgement of what to do.
It works like this:
echo what do you rather, the colour blue or red?
set /p col=Please type either "blue" or "red":
if %col% equ blue color 10 (
echo YAY! IT'S NOW BLUE
if %col% equ red color 40 (
echo YAY! IT'S NOW RED
) ELSE (
Next we will create a batch file.
Step 8: My Batch File
Open notepad.exe (or wordpad) and either type or copy and paste the following command (you can also just download it from the bottom):
Title Website Starter (by Prof. Pickle)
echo This is the Website starter
echo Select the number of the website you wish to select
echo Or press E to exit.
echo 1. facebook
echo 2. youtube
echo 3. google
echo 4. redtube
echo 5. other
set /p web=
If %web% EQU 1 start www.facebook.com
If %web% EQU 1 goto Menu
If %web% EQU 2 start www.youtube.com
If %web% EQU 2 goto Menu
If %web% EQU 3 start www.google.com
If %web% EQU 3 goto Menu
If %web% EQU 4 start www.redtube.com
If %web% EQU 4 goto Menu
If %web% EQU 5 goto other
If %ERRORLEVEL% NEQ 0 goto ERROR
If %web% EQU E goto exit
If %web% EQU e goto exit
echo You have chosen other
echo Type the web address of the website (www.website.com)
set /p otherweb=
If %ERRORLEVEL% NEQ 0 goto ERROR
pause > nul
echo Sorry, an error has occurred.
echo If you were using the "other website" function you may have
echo typed it incorrectly.
echo Press any key to go back to menu
pause > nul
echo Please press a number from 1-5
If I have offended you by putting Redtube as an option forgive me because I couldn’t think of any other website you might want to go to… you can always change it.
The only commands that you have not yet been taught are the “exit”, “start”, "color" and "title" commands.
The start command starts files, websites, processes, etc.
The exit command exits the file.
The color command changes the color of the window.
The title command sets the title of the file.
If you like what you see here and want another batch "Program" like this one, I have made another instructable here. It includes the code for a Mega-Menu with batch (it can do heaps of things but not as much as TATcreator).
Step 9: Creating Directories and Files
md or MD This command creates a new, empty directory (a folder) with the last specified name.
E.g md folder_name (this would make a folder in the current directory named folder_name)
If you want to change the current directory type cd "folder path".
E.g cd "C:\Windows\System32" This would change the current directory to the windows system32 folder.
To check if a directory exists type If EXIST "folder_name" echo folder_name exists! (This would check to see if a directory exists and if it does it displays a message saying the folder_name exists)
You can also create files and edit them too!
There are three ways that I know how to do this.
echo This file name is text1.txt > "text1.txt" (This would create a .txt (text) file in the current directory named text1. This text can be viewed with notepad.exe)
Note: One ">" is used to create the file, two ">>" are used to add to the already existing file.
The "copy con" command.
This command works like so "copy con file.extension". This would create a file named "file.extension" in your current directory. Anything you type from now on will be added to the end of the file. To stop this, press CTRL+Z.
The edit command. The edit command, when used, brings you to cmd's first "gui". From here you cna create files, modify and save files. Self explanatory, right?
P.S When saving, you can choose any extension you want (E.g .bat, .py, .exe, .cmd, .doc,etc).