16 January 2014

Command Line Argument to Batch file (Parameter)

Hi All,

Lets see how can we pass the parameter to batch file.  If you have worked with C, C++ and anyother programming language then I hope you must be familir with "Command Line Args" and whats the use of it.

lets see the basic batch file code to print the value.
@echo off
set n=Hello World..!!!
echo Hello Friends the value stored in variable n is = %n%
pause

when i will run the above batch code it will show the output as below -

Hello Friends the value stored in variable n is = Hello World..!!!
Press any key to continue . . .

but I want to pass the value to the batch code, to run the file I have to use the file name followed by the value we want to pass.

batch_file.bat value1 value2

now our job is to take these value from the command line and use it in our batch code. %1 will refer to the first parameter value and %2 will point to the second value.

@echo off

if %1.==. goto novar1
if %2.==. goto novar2

set first_var= %1
set second_var=%2

echo first variable pass as command line is = %first_var%
echo second variable pass as command line is = %second_var%
goto end

:novar1
echo no command line argument passed in.
goto end

:novar2
echo only one command line argument passed in.
goto end

:end
pause
so in this way you can pass the command line argument to batch file,  and can check either command line argument is passed or not.

Happy Coding & Sharing..

No comments:

Post a Comment