Sunday, February 22, 2015

How To Create A Windows Batch File

Batch files are used to store DOS commands. Once you run the batch file by double clicking on the file or via any other method such as using command prompt, all the DOS commands are executed sequentially. Normally batch files are mostly used to automate repetitive tasks.  You can save your time by automating repetitive tasks. This method is very useful for developers more than normal computer users.

Creating a batch file is not a complex task.  You need to know only the DOS commands that you are going to put into the batch file and the order of the commands.

Here you can see few of commonly used DOS commands.

  • TITLE      Window name when bat file executes.
  • PAUSE    :  Pause the execution of the bat file and wait until user press any key  to continue
  • CLS        :  Clear the DOS window
  • MKDIR    Create a directory
  • DIR         :  Move into a directory ( “DIR directory_path”) or view current directory (“DIR”)
  • START    :  Execute a file using default application
  • ECHO      :  Print something on the command prompt window
  • ECHO OFF    :    Prevent showing the batch file commands on the command prompt
You can find a list of DOS commands by typing HELP in command prompt 

Let’s create few batch files.

After understood basics you can create complex batch files by adding various commands. First you need to create a file with .bat extension or .cmd extension.

Open notepad --> click save --> select all files --> name it as test.bat or test.cmd --> save

Now you can insert below DOS commands into your file and test them.

1.  A program to create a directory
       MKDIR  Hello_World
       MKDIR “Hello World”

Insert above commands into your test.cmd/test.bat file and save. Then execute these commands by double clicking the on the file. Keep in mind to put double quotation marks if you use spaces in a name.
Above commands will create two folders called Hello_world and Hello World in the same directory where your batch file exists.

2.       Create a text file with a text string
MKDIR “text folder”
CD "text folder"
ECHO "This is the text string" > textFile.txt

This DOS command will create a folder named text folder and create a file named textFile.txt and write a text string into the file.

You can understand the basics of creating a batch file using above examples. Once you got the basics you can create very complex files to automate a process.
Click here to read more on this topic.

No comments:

Post a Comment