One solution is:
@echo off
setlocal EnableExtensions DisableDelayedExpansion
SET "JVM_ARGS=-server"
for %%I in (%*) do (
set "Argument=%%~I"
setlocal EnableDelayedExpansion
if /I "!Argument:~0,2!" == "-D" (
rem echo Argument starting with -D is: !Argument!
endlocal
set "JVM_ARGS=%JVM_ARGS% %%I"
) else endlocal
)
rem set JVM_ARGS
endlocal
It works for:
-d
-D
"-d"
"-D"
-dhello
-DHello
-d"Hello world!"
-D"!That's my function()!"
"-dHello world!"
"-DYes, argument processing is not trivial!"
The above code is written for just one -D
option. For multiple -D
options it would be necessary to replace the line
set "JVM_ARGS=%JVM_ARGS% %%I"
by
set "Argument=%%I"
call set "JVM_ARGS=%%JVM_ARGS%% %%Argument%%"
The command CALL results in parsing the command line being already
call set "JVM_ARGS=%JVM_ARGS% %Argument%"
after parsing the entire command block before executing FOR a second time with replacing %JVM_ARGS%
by current string value of this environment variable and %Argument%
by the string value assigned to environment variable Argument
above. The additional Argument
environment variable is needed to avoid that a string after -D
containing %
is malformed as it would occur with using %%I
instead of %%Argument%%
.
To understand the commands used and how they work, open a command prompt window, execute there the following commands, and read the displayed help pages for each command, entirely and carefully.
call /?
echo /?
endlocal /?
for /?
if /?
rem /?
setlocal /?
Please read this answer for details about the commands SETLOCAL and ENDLOCAL.