2

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?
3
  • 3
    Are you talking about a batch file, a powershell script, or an executable? Commented Dec 16, 2014 at 4:30
  • batch file and cmd.exe @James Commented Dec 16, 2014 at 4:31
  • 1
    Have a look at my answer to "Windows Bat file optional argument parsing". It supports default values and is really convenient. I've used the technique on batch scripts with 20 named options. Commented Dec 17, 2014 at 2:21

1 Answer 1

5
@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]

Sign up to request clarification or add additional context in comments.

1 Comment

excellent! I have saved it on my golden BAT snippets folder

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.