2

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

1 Answer 1

10

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
)
Sign up to request clarification or add additional context in comments.

1 Comment

Thx alot :) i have seen shift while googling but never really searched into it, wish i would of before its incredibly useful thx :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.