1

I want to create my own command in following manner which I wish to run from both batch and cmd.exe:

fake-command -name <some value> -age <some Value>

Currently I know to create a command as following:

fake-command  <some value> <another Value>

After that I can collect the input as %1 and %2. But that is no efficient way to do this because what happens if the order in which I am expecting the input gets changed and someone enters age before name.

So I have two questions:

  1. How to create Linux like switches on Windows command line?
  2. Is my approach correct? Is there a better way to do this?
Mofi
  • 46,139
  • 17
  • 80
  • 143
Subham Tripathi
  • 2,683
  • 6
  • 41
  • 70
  • 3
    Are you talking about a batch file, a powershell script, or an executable? – James Dec 16 '14 at 04:30
  • batch file and cmd.exe @James – Subham Tripathi Dec 16 '14 at 04:31
  • 1
    Have a look at [my answer to "Windows Bat file optional argument parsing"](http://stackoverflow.com/a/8162578/1012053). It supports default values and is really convenient. I've used the technique on batch scripts with 20 named options. – dbenham Dec 17 '14 at 02:21

1 Answers1

4
@ECHO OFF
SETLOCAL
SET "switches=name age whatever"
SET "noargs=option anotheroption"
SET "swindicators=/ -"
SET "otherparameters="
:: clear switches
FOR %%a IN (%switches% %noargs%) DO SET "%%a="

:swloop
IF "%~1"=="" GOTO process

FOR %%a IN (%swindicators%) DO (
 FOR %%b IN (%noargs%) DO (
  IF /i "%%a%%b"=="%~1" SET "%%b=Y"&shift&GOTO swloop
 )
 FOR %%b IN (%switches%) DO (
  IF /i "%%a%%b"=="%~1" SET "%%b=%~2"&shift&shift&GOTO swloop
 )
)
SET "otherparameters=%otherparameters% %1"
SHIFT
GOTO swloop

:process

FOR %%a IN (%switches% %noargs% otherparameters) DO IF DEFINED %%a (CALL ECHO %%a=%%%%a%%) ELSE (ECHO %%a NOT defined)

GOTO :EOF

Here's a demonstration.

Given you have 3 switches, name age whatever which accept one argument and two true switches, option and anotheroption which take no arguments, then running the above procedure as

q27497516 -age 92 /option goosefeathers /name fred

(q27497516.bat is my batchname here) will yield

name=fred
age=92
whatever NOT defined
option=Y
anotheroption NOT defined
otherparameters= goosefeathers

Convention is to use / as a switch indicator - a leading - is legitimate for a filename. Implementation depends on the programmer's whim. The above structure will allow any character - within cmd's syntax rules, naturally [ie. $_# OK, %!^ No, ! maybe () awkward]

Magoo
  • 77,302
  • 8
  • 62
  • 84