We are trying to make a switch statement which is parsing command line argument in a batch file.
mybatch.bat -a 10 -b name -c India --zipcode 20
Only -a
, -b
, -c
are parsing parameter (which is starts with -
).
Our code will be like:
for %%x in (%*) do (
switch(%%x) (
case a:
SET first_number=%arg%
break
case b:
SET name=%arg%
case c:
for %%x in (%*) do (
SET place =%place% %arg%
)
default:
echo wrong parameter
)
The Batch file below parses all arguments that start with -
and creates a series of variables that start with "option" and the names and values of all options given:
@echo off
setlocal EnableDelayedExpansion
set "option="
for %%a in (%*) do (
if not defined option (
set arg=%%a
if "!arg:~0,1!" equ "-" set "option=!arg!"
) else (
set "option!option!=%%a"
set "option="
)
)
SET option
For example:
>test -a 10 -b name -c India --zipcode 20
option--zipcode=20
option-a=10
option-b=name
option-c=India
This way, you need to make no changes in the parsing code if you want to add/change/delete any option, just use the value of the option you want. For example:
if defined option-x (
echo Option -x given: "%option-x%"
) else (
echo Option -x not given
)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With