tags:

views:

35

answers:

1

I need my bat file to accept multiple optional named arguments.

mycmd.bat man1 man2 -username alice -otheroption

For example my command has 2 mandatory parameters, and two optional parameters (-username) that has an argument value of alice, and -otheroption:

I'd like to be able to pluck these values into variables.

Just putting out a call to anyone that has already solved this. Man these bat files are a pain.

+3  A: 

Though I tend to agree with @AlekDavis, there are nonetheless several ways to do this in the NT shell.

The approach I would take would take advantage of the SHIFT command and IF conditional branching, something like this...

@ECHO OFF

SET man1=%1
SET man2=%2
SHIFT /2

:loop
IF NOT "%1"=="" (
    IF "%1"=="-username" (
        SET user=%2
        SHIFT
    )
    IF "%1"=="-otheroption" (
        SET other=%2
        SHIFT
    )
    SHIFT
    GOTO :loop
)

ECHO Man1 = %man1%
ECHO Man2 = %man2%
ECHO Username = %user%
ECHO Other option = %other%

REM ...do stuff here...

:theend
ewall
Thanks ewall - one small error at line 4 - SET man2=%1
Ash Kim
Ah, right... fixing it now.
ewall