I'd like to check if an argument to a batch file is valid based on a list of strings.
For example:
IF %1 IN validArgument1, validArgument2, validArgument3 SET ARG=%1
This would set ARG to one of the valid arguments only if it matched. Ideally case insensitively.
A robust method is to use delayed expansion
setlocal enableDelayedExpansion
set "validArgs=;arg1;arg2;arg3;"
if "!validArgs:;%~1;=!" neq "!validArgs!" set ARG=%1
It can also be done using CALL along with normal expansion, but it is more likely to fail, depending on the value of the parameter.
set "validArgs=;arg1;arg2;arg3;"
call set "test=%%validArgs:;%~1;=%%"
if "%test%" neq "%validArgs%" set ARG=%1
Both techniques above have a limitation that no valid arg can contain =
and args must not start with *
.
You could also use the following brute force method as long as none of the valid args contain *
?
,
;
=
or <space>
set "validArgs=arg1;arg2;arg3"
for %%A in (%validArgs%) if /i "%~1"=="%%A" set ARG=%1
You might want to have a look at this argument parser. You could adapt that code, or it might spark some ideas for your own unique strategy.