向命令行参数添加开关 [英] Adding switches to command line arguments

查看:26
本文介绍了向命令行参数添加开关的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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>

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

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.

所以我有两个问题:

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

推荐答案

@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 个开关,名称 年龄 随便接受一个参数和两个真正的开关,选项anotheroption 不带任何参数,然后将上述过程作为

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 是我这里的批次名称)将产生

(q27497516.bat is my batchname here) will yield

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

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

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]

这篇关于向命令行参数添加开关的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆