My blog has moved!

You should be automatically redirected. If not, visit
http://benohead.com
and update your bookmarks.

Tuesday, April 3, 2012

Batch: Get parameters from command line or user input

When you write a batch file where you either want the caller to provide a parameter or ask the user to type it in if not provided, you can use the following piece of code:

set MyParameter=%1
if "%MyParameter%"=="" (
:input
set INPUT=
set /P INPUT=Enter a value for the parameter: %=%
)
if "%MyParameter%"=="" (
if "%INPUT%"=="" goto input
)
if "%MyParameter%"=="" (
set MyParameter=%INPUT%
)

It first gets the first command line argument. If it's not empty you can just skip every (so either do it the way I did it or just use a goto.

As long as the user hasn't entered anything, the script will keep asking. Instead of just checking for an empty string, you could also have a more elaborate validation of the input.

The multiple if blocks are required because if you put it all in one block the %INPUT% variable will only be evaluated when the script is started and not again after user input.

No comments:

Post a Comment