将开关添加到命令行参数

Sub*_*thi 2 command-line cmd batch-file

我想按以下方式创建自己的命令,我希望从批处理和 cmd.exe 运行该命令:

fake-command -name <some value> -age <some Value>
Run Code Online (Sandbox Code Playgroud)

目前我知道创建一个命令如下:

fake-command  <some value> <another Value>
Run Code Online (Sandbox Code Playgroud)

之后我可以将输入收集为%1%2。但这不是有效的方法,因为如果我期望输入的顺序发生变化并且有人在姓名之前输入年龄,会发生什么。

所以我有两个问题:

  1. 如何在Windows命令行上创建类似Linux的开关?
  2. 我的做法正确吗?有一个更好的方法吗?

Mag*_*goo 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
Run Code Online (Sandbox Code Playgroud)

这是一个演示。

假设您有 3 个开关,将接受一个参数和两个 true 开关、选项另一个不带参数的选项命名为 age ,然后运行上述过程:

q27497516 -age 92 /选项 goosefeathers /name fred

(q27497516.bat 是我的批处理名称)将产生

name=fred
age=92
whatever NOT defined
option=Y
anotheroption NOT defined
otherparameters= goosefeathers
Run Code Online (Sandbox Code Playgroud)

约定是用作切换指示符 -文件名的/前导是合法的。-实现取决于程序员的想法。上面的结构将允许任何字符 - 在cmd的语法规则内,自然[即。$_# 好的,%!^ 不,! 也许()尴尬]