Question


I'm having an issue with a Batch File. Basically, I would like to seek ahead by 1 in a for loop and use that value to reference the parameter at that position and then assign it to a variable which I can then use later, see code sample below.

Example: set myVar=%1+1
Where %1 is param name, and %2 would be param value.

::Batch file sample
@echo off

SETLOCAL ENABLEDELAYEDEXPANSION
set count=0
set HasParam=0
set ParamValue="null"
set paramValPos=0

for %%i in (%*) do (
    set /a count=!count!+1
    if /i "%%i"=="MyParam" (        
        set /a HasParam=1           
        set /a paramValPos=!count!+1
        ::The next line is where I Need Help, it's currently incorrect!
        set ParamValue=%!paramValPos!
    )   
)

if %HasParam%==1 (
    echo "Parameter Value: %ParamValue%"
)
pause

Example call from command line: prog.bat MyParam=5
Now I know that I can access it at pos 2, like:

::Sample batch file
@echo off
echo "Param Name: %1"
echo "Param Value: %2"
pause

However, this is not what I want, as there are more parameters and some are optional and they can also be passed in, in any order.

Thanks for your assistance.

Was it helpful?

Solution

call set "ParamValue=%%!paramValPos!"

OTHER TIPS

If I understood your request correctly, you want the next parameter after a given one. The Batch code below do that:

@echo off

set "HasParam="
set "ParamValue="

for %%i in (%*) do (
   if defined HasParam (
      if not defined ParamValue (
         set ParamValue=%%i
      )
   ) else if /i "%%i"=="MyParam" (
      set HasParam=yes
   )
)

if defined HasParam (
   echo "Parameter Value: %ParamValue%"
)
pause
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top