Batch Scripting

Basics

Batch scripts are nothing but the sequence of commands which are executes one by one using command interpreter [cmd.exe]. The command line interpreter or cmd.exe is available in almost all versions of windows OS and located at c:\windows\system32\cmd.exe

First of all you need to know the commands which are interpreted by cmd.exe, but before let’s see how command are executes with command interpreter. The cmd.exe executes command in two modes :

1. Interactive Mode :  

In Interactive Mode we type commands in “command prompt”. To start the command prompt just go to start Menu and type cmd on search box then hit enter. In this box type “echo hello world” and hit enter, after that command prompt will be return “hello world”. “echo” command prints all the arguments.

 2. Non Interactive Mode or Batch Mode :

In Non Interactive Mode or Batch Mode we put all commands in a file and save it as “cmd.bat”, where cmd is file name and “.bat” is the file extension of Batch files or Batch scripts. We simply creates Batch file using notepad, first open notepad and type these  

@echo off  
title My first Batch Script  
echo ..........................  
echo Hello Guys This is A batch Script  
echo ..........................  
pause    
exit /b  

Now to go file Menu and click on save as option, then change save as type to all files and change the file name to cmd.bat then click to save button. Remember you could give any name to batch file but file extension is always .bat. To executes batch file just click on it.

The commands which are used in above script are :

  • @echo off :    command ‘echo off’ will be turn off the prompt. Prompt means the execution path of batch file. In my case the path is “C:\User\Ajay\Desktop\”, your differ. After putting @ at the start of a command will prevents shown the execution of command in that line. (To test what @echo off command does just create another batch script similar to above and change @echo off to @echo on then see what happen.)
  • Title :    Title command is used to set the title of console window.
  • Pause :    Pause command is pause the command execution and wait for the user input, when user gives any input then next command will be executed.
  • Exit :    Exit command close the command processor or cmd.exe.

Some Batch Commands

  • md : (Make Directory) used to create a new directory.
md dir_name
  • cd : (Change Directory) used to change directory.
cd dir_name
  • copy : used to coping files.
copy source_file_name destination_file_name
  • move :  used to moving files.
move source_file_name destination_file_name
  • ren :  used to rename files.
ren old_file_name new_file_name
  • del : used del files.
 del file_name
  • dir : used to listing in current directory.
  • rem : used to write comments or description inside batch scripts.
rem this is comment

we also write comments using :: sign

:: This is comment

Now there is a simple script which demonstrate the above commands

These are some basic commands used in batch scripting. For more batch commands check these links :

@echo off  
title Script test  
md my_dir  
rem create a directory my_dir  
dir > dir_list.txt  
rem list all files in current directory with dir command and save the output in dir_list.txt  
copy dir_list.txt .\my_dir\  
rem copy dir_list.txt in my_dir '.' sign before my_dir specify the current working directory.  
del dir_list.txt  
rem delete dir_list.txt  
cd my_dir  
rem change directory to my_dir  
ren dir_list.txt renamed_list.txt  
rem rename dir_list.txt to renamed_list.txt  
pause  
exit /b 

windows commands List : http://ss64.com/nt/
windows command reference : http://www.microsoft.com/en-in/download/details.aspx?id=2632

Variables

To declare a variable use set command

set name="Ajay Kumar"

And to get the variable’s data use %variable_name%

echo %name%

To know more about set command just type set /? in command prompt or look at the windows command reference help file. Now here is an example program of set command.

@echo off  
title TEXT File Creater  
echo.   
echo.  
set /p data="Enter the File Content = "  
echo.  
echo.  
set /p name="Enter file Name = "  
echo %data% > %name%.txt  
echo.  
echo File created Successfully. !! Press Any key To Exit.  
pause > nul  
exit /b  

Loops

Goto Loop :

@echo off  
:loop  
msg * Hello world!!  
Pause  
goto loop  

For Loop :

Syntax of For loop is  

for %%{variable} in (set) do (command)

Example :

@echo off  
FOR %%i IN (Windows, Linux, Mac_OS) DO (echo %%i)  
Pause  
exit /b  

For loop on numeric mode

Syntax :    

for /L %%{variable} in (starting point, step, end point) do (command)
@echo off  
FOR /L %%i IN (1, 1, 20) DO (echo Hello world!!!)  
Pause  
exit /b  

The above script prints Hello world!!! 20 times, In For loop (1, 1, 20), where first 1 is starting point and second 1 is step means first 1 is increased by 1 at every loop and 20 is end point, when first 1’s value is 20 then for loop is end.

We also write this loop as :

for /L %%i in (20, -1, -1) do (echo hello world)

Conditional Statement

if-else :

@echo off  
:Again  
set /p num="Enter A Number{0 to continue}: "  
if %num%==0 (goto Again) else (  
echo.  
echo You have entered %num%)  
pause > nul  
exit /b 

if not-else :

@echo off  
echo.  
set password=12345  
:pass  
set /p user_input="Enter The Password : "  
if not %password% == %user_input% (  
echo Wrong Password ?  
echo.  
goto pass ) else (  
echo.  
echo Congratulations..!! You have SuccessFully Log in  
pause > nul  
exit /b)  

if exist :

@echo off  
echo.  
if exist "C:\Windows\SysWOW64" (echo Your Operating System is 64 bit) else (  
echo Your Operating System is 32 bit)  
echo.  
Pause  
exit /b  

Command line Arguments

We also use arguments in batch scripts, to access arguments use %1, %2… where %1 denotes first argument and %2 denotes second. Here is an example script which shows how to use Arguments :

@echo off  
set /a ans=%1+%2+%3  
echo.  
echo The Sum of %1, %2, %3 is %ans%.  
pause > nul  
exit /b  

Above program takes three arguments, then print their sum. Make sure run this script via command line.

Functions

We can also create functions in Batch programming. Functions are simply a reusable piece of code, in Batch programming a function is creates using a Label and goto :EOF command. Here is an Example of a simple function

:print  
Echo Hello this is my first function.  
Echo Which Prints this Message.  
Goto :EOF  

A function can be called by call command which followed by function’s label.

call :print

So the above script look like this

@echo off   
call :print  
pause > nul  
exit/b  
:print  
Echo Hello this is my first function.  
Echo Which Prints this Message.  
Goto :EOF  

for more information and detailed tutorial about functions check out below link

http://commandline.co.uk/lib/treeview/index.php
http://www.dostips.com/DtTutoFunctions.php

Now here is function written by me which returns the IP address of given website url

@echo off & setlocal ENABLEEXTENSIONS  
echo.  
set /p url="Enter The WEBSITE URL : "  
call :SiteIp %url% ip  
echo.  
echo The IP Address of %url% is : %ip%   
pause > nul  
goto :EOF  
:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::  
:SiteIp %address% ip  
::  
:: Func: Return the IP address of given Website URl.   
::    If function fails, it shows "Problem in Connection.??"  
::  
:: Args: %1 var for WebSite URl & %2 to receive IP Address.   
:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::  
setlocal ENABLEEXTENSIONS & set "ans=Problem in Connection.??"  
for /f "tokens=3" %%a in ('ping -n 1 %1^|findstr /B Pinging') do ( set d=%%a)  
if exist %d%=nul ( endlocal & set "%2=%ans%" & goto :EOF)  
for /f "delims=[]" %%b in ('echo %d%') do ( set data=%%b )  
endlocal & set "%2=%data%"  
goto :EOF  
:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::  

In this below link has a huge collection of ready made functions

http://www.dostips.com/DtCodeCmdLib.php

Colored Batch Script

To create a color-full Batch script use color command, with this command we can change the text color as well as background color. The color code of Batch script is 

CodeColor
0Black
1Blue
2Green
3Aqua
4Red
5Purple
6Yellow
7White
8Gray
9Light blue
ALight green
BLight aqua
CLight red
DLight purple
ELight yellow
FBright white

For more info about color command type color /? in command prompt. To change the text color only type 

color [color code]

Example :

color a

For changing text and background color use :

color [background color][text color]

Example :

color 1a

Try out this command with different combinations of colors.

Multicolored Batch Script :

Example of a Batch Script which shows multiple colors in a single script :

@echo off  
setlocal EnableDelayedExpansion  
for /F "tokens=1,2 delims=#" %%a in ('"prompt #$H#$E# & echo on & for %%b in (1) do rem"') do (  
    set "DEL=%%a"  
)  
rem Prepare a file "X" with only one dot  
<nul > X set /p ".=."  
echo.  
call :color 0a "  Hello Guys This IS Test....    "  
echo.  
call :color 0b " This IS The Second Colour........  "  
echo.  
call :color 0c " This IS The Third Colour........  "  
echo.  
echo.  
pause >nul  
del X  
exit /b  
:color  
set "param=^%~2" !  
set "param=!param:"=\"!"  
findstr /p /A:%1 "." "!param!\..\X" nul  
<nul set /p ".=%DEL%%DEL%%DEL%%DEL%%DEL%%DEL%%DEL%"  
exit /b  

Script source page :

http://stackoverflow.com/questions/4339649/how-to-have-multiple-colors-in-a-batch-file/5344911%235344911

References

Here is the list of links for Batch Scripting References :