Thursday, November 13, 2008

How to send parameter to a batch file?

When we run batch files (.BAT), there might be instants where the batch file should perform operation based upon some input parameters.
In such case we should write those batch files reading input parameters while calling them.
Say suppose I want to run a batch file to which I will give my name and it should say “Hai “ (My Name).
Let the batch file name be “MyName.BAT” saved at C: drive.
I go to run, and type c:\MyName.BAT srinivas. Then the batch file existing at the location specified is executed and gives required output.

Logic that has to be built or to be written inside “MyName.BAT” file that displays my name.
It is very simple and 1 line command :).

Echo Hai %1

Save this content inside a batch file whose name is MyName.BAT in C drive.

Go to Command Prompt Type
C:\MyName.BAT Srinivas and press enter


Specific parameter can be considered or read based upon the parameter index in input list.
If I say % 2 then the batch file considers the second parameter from the input list


What sowmya said is very true, that batch file cannot accept more than 10 parameters.
To resolve this , i mean to send parameters for a batch file more than 10 s possible by using shift key word.
Example :-
I want to send 11 characters to a batch files which has to display all those 11 input parameters.
Output :

Batch file content

@echo off
echo 1) %1
echo 2) %2
echo 3) %3
echo 4) %4
echo 5)%5
echo 6) %6
echo 7) %7
echo 8) %8
echo 9) %9
shift /1
echo 10) %9
shift /1
echo 11) %9

Shift key word helps in shifting the parameters towards left.
Syntax :-
shift /5
this shits the input parameters towards left starting from 5th parameter at 5 th position becomes now as 4th and 6th as 5 th etc...
so in the above file content when i say shift /1 then the 10th parameter will be the 9 th parameter and once again shift /1 makes 11th parameter as the 9 th parameter.
So i can make use of those 2 parameters as well.


No comments:

Post a Comment