【问题标题】:Adding switches to command line arguments将开关添加到命令行参数
【发布时间】:2015-02-14 08:15:39
【问题描述】:

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

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

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

fake-command  <some value> <another Value>

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

所以我有两个问题:

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

【问题讨论】:

  • 您说的是批处理文件、powershell 脚本还是可执行文件?
  • 批处理文件和 cmd.exe @James
  • 看看my answer to "Windows Bat file optional argument parsing"。它支持默认值,非常方便。我已经在具有 20 个命名选项的批处理脚本上使用了该技术。

标签: batch-file command-line cmd


【解决方案1】:
@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

这是一个演示。

假设您有 3 个开关,name age whatever 接受一个参数和两个 true 开关,optionanotheroption 不带参数,然后将上述过程作为

运行

q27497516 -age 92 /option goosefeathers /name fred

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

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

约定是使用/ 作为开关指示符——前导- 对文件名来说是合法的。实现取决于程序员的心血来潮。上述结构将允许任何字符 - 在cmd 的语法规则内,自然 [ie. $_# 好的,%!^ 不,!也许()尴尬]

【讨论】:

  • 太棒了!我已将其保存在我的 golden BAT sn-ps 文件夹
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-12-31
  • 1970-01-01
  • 2020-10-22
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多