How to iterate on the parameters of a subroutine

Discussion forum for all Windows batch related topics.

Moderator: DosItHelp

Post Reply
Message
Author
jwoegerbauer
Posts: 33
Joined: 01 Jan 2013 12:09

How to iterate on the parameters of a subroutine

#1 Post by jwoegerbauer » 24 Feb 2015 04:31

Hi there,

simply spoken the task I want to accomplish is: Process something in accordance to unknown amount of parameters passed to a subroutine and their value, without the need of hundred IFs

Code: Select all

:subroutine
if "%1"=="foo1" do process something
...

if "%n"=="fooN" do process something
goto :eof


My actual intention is to have a subroutine that deletes in given string which is located in a text file and therein in the one and only line which contains drives, eg. C:\ D:\ ... Z:\ the drives passed, eg E:\ ... Z:\

Code snippet:

Code: Select all

SETLOCAL ENABLEDELAYEDEXPANSION
...

SET tmp_file=%TEMP%\FoundDrives.txt
fsutil fsinfo drives > %tmp_file%

FOR /l %%x IN (1,1,28) DO (
   SET param_index=%%x
   IF NOT "%!param_index!"=="" (
      SET search=%!param_index!
      FOR /f "tokens=*" %%y IN (%tmp_file%) DO (
         SET drives=%%y
         SET drives=!drives:%search%=%replace%!
         ECHO !drives! > %tmp_file%
      )
   )
)

...

DEL %tmp_file% > NUL 2>&1

...

ENDLOCAL
GOTO :EOF


The problem I have is I don't know to correctly code the 3 lines

Code: Select all

        SET param_index=%%x
   IF NOT "%!param_index!"=="" (
      SET search=%!param_index!


Any hints welcome.

aGerman
Expert
Posts: 4654
Joined: 22 Jan 2010 18:01
Location: Germany

Re: How to iterate on the parameters of a subroutine

#2 Post by aGerman » 24 Feb 2015 17:46

The supported parameters are %0 - %9. Even if your idea of a %!param_index! would work you were not able to access a number of 26 parameters this way. One possibility is to use SHIFT. This command removes the lowest parameter and shifts the remaining parameters one number down.
Nevermind. There is a better way. %* contains all parameters and you can use a simple for loop to separate them.

Code: Select all

for %%i in (%*) do echo %%i


Regards
aGerman

jwoegerbauer
Posts: 33
Joined: 01 Jan 2013 12:09

Re: How to iterate on the parameters of a subroutine

#3 Post by jwoegerbauer » 25 Feb 2015 01:47

@aGerman,

THX for your input

Post Reply