Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Batch script loop to check for multiple parameters

Ok, I keep playing with this but can't get it to run the command for each parameters.

Batch file run as

test.bat /r /a /c

Full Batch Code

@echo on
SETLOCAL ENABLEEXTENSIONS
SETLOCAL ENABLEDELAYEDEXPANSION

:checkloop
set argtoken=1
FOR /F "Tokens=* delims=" %%G IN ("%*") DO (call :argcheck %%G)
pause
GOTO:END


:argcheck
if /i "%1"=="/r" set windows=1
if /i "%1"=="/a" set active=1
goto:eof

:end

"%*" Displays all of the arguments such as

/r /a /c

But for some reason no matter what I try, I can't get the for loop to break up different parameters and run :argcheck for each parameter.

UPDATE: For anyone interested here is what I ended up wtih. I am implementing it in a few different scripts and its working amazing. Just place it somewhere in the script with the call function and the "%*" and you should be good. :) Post if you have any problems with it.

@echo off
SETLOCAL ENABLEEXTENSIONS
SETLOCAL ENABLEDELAYEDEXPANSION

call:ArgumentCheck %*
echo %DebugMode%
echo %RestartAfterInstall%
pause
goto:eof

:ArgumentCheck
if "%~1" NEQ "" (
    if /i "%1"=="/r" SET DebugMode=Yes & GOTO:ArgumentCheck_Shift
    if /i "%1"=="/a" SET RestartAfterInstall=Yes & GOTO:ArgumentCheck_Shift
    SET ArgumentCheck_Help=Yes
    :ArgumentCheck_Shift
        SHIFT
        goto :ArgumentCheck
)
If "%ArgumentCheck_Help%"=="Yes" (
    Echo An invalid argument has been passed, currently this script only supports
    ECHO /r /a arguments. The script will continue with the arguments 
    ECHO you passed that is supported.
)
GOTO:EOF
:end
like image 475
Nick W. Avatar asked Aug 01 '26 02:08

Nick W.


1 Answers

The cause is that FOR/F will split one line into a fixed count of tokens named %%A,%%B,%%... (%%A is here the first named token).
But as you use empty delims= even this will not work.

FOR /F "tokens=1-5 delims= " %%A in ("%*") do (
  echo %%A, %%B, %%C, %%D, %%E
)

This would split your line into tokens, but it would even split tokens like

One "two and three"

Output:

One, "two, and, three",

It's easier to use SHIFT and a loop.

:loop
if "%~1" NEQ "" (
  call :argcheck
  SHIFT
  goto :loop
)
like image 109
jeb Avatar answered Aug 03 '26 09:08

jeb



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!