通过类似开关的参数循环批处理文件? [英] Batch file for loop through switch-like arguments?
问题描述
我通过我传递给一个批处理文件的参数试图循环。根据的说法,我想设置一个变量的标志真或假供以后使用脚本
I'm trying to loop through the arguments that I am passing to a batch file. Based on the argument, I want to set a variable flag true or false for use later in the script
所以我的命令是myscript.bat / U / P / S
So my command is "myscript.bat /u /p /s"
和我的code是:
FOR /f %%a IN ("%*") DO (
IF /I "%%a"=="/u" SET UPDATE=Y
IF /I "%%a"=="/p" SET PRIMARY=Y
IF /I "%%a"=="/s" SET SECONDARY=Y
)
它只是如果我有一个参数,它告诉我,这是越来越参数的整个列表作为一个参数工作。我已经试过delims =,但无济于事。在得到每个间隔参数有什么想法?
It only works if i have a single argument, which tells me that it is getting the entire list of arguments as a single argument. I've tried "delims= " but to no avail. Any thoughts on getting each spaced argument?
怎么样增加一个值PARAMS之一?
What about adding a value to one of the params?
myscript.bat / U / P / D测试/ S
myscript.bat /u /p /d TEST /s
:loop
IF "%~1"=="" GOTO cont
IF /I "%~1"=="/u" SET UPDATE=Y
IF /I "%~1"=="/p" SET PRIMARY=Y
IF /I "%~1"=="/s" SET SECONDARY=Y
IF /I "%~1"=="/d" SHIFT & SET DISTRO="%~1"
SHIFT & GOTO loop
:cont
不过,与过去的IF内联来了SHIFT实际上并没有任何转变。 DISTRO最终被/ D代替TEST
But the SHIFT that comes inline with the last IF doesn't actually shift anything. DISTRO ends up being "/d" instead of "TEST"
推荐答案
您可以遍历使用SHIFT,GOTO和一个额外的IF参数,以检查是否有没有更多的参数解析:
You could loop over the arguments using SHIFT, GOTO and an extra IF to check if there are no more parameters to parse:
:loop
IF "%~1"=="" GOTO cont
IF /I "%~1"=="/u" SET UPDATE=Y
IF /I "%~1"=="/p" SET PRIMARY=Y
IF /I "%~1"=="/s" SET SECONDARY=Y
SHIFT & GOTO loop
:cont
...
更新(解决的情况下,当一个参数都有自己的一个参数)
UPDATE (addressing the case when a parameter has an argument of its own)
在IF语句的转变,检查 /天
确实工作。问题是,整条生产线是在一次评估和两个实例%〜1
被替换为同一个值,这是 /天
在这一点上。
The SHIFT in the IF statement that checks for /d
does work. The issue is that the entire line is evaluated at once and both instances of %~1
get replaced with the same value, which is /d
at that point.
所以,基本上在这种情况下,解决办法是分别从导致跨preTER评估 SET DISTRO =%〜1
部分 IF / I%〜1==/ D
。可以有各种方法来此。例如,你可以简单地移动 SHIFT&安培; SET DISTRO =%〜1
到下一行,并跳过它,如果%〜1
是的不的 /天
:
So, basically the solution in this case would be to cause the interpreter to evaluate the SET DISTRO="%~1"
part separately from the IF /I "%~1"=="/d"
. There can be various approaches to this. For instance, you could simply move SHIFT & SET DISTRO="%~1"
to the next line and skip it if %~1
is not /d
:
...
IF /I NOT "%~1"=="/d" GOTO skip_d
SHIFT & SET "DISTRO=%~1"
:skip_d
...
另一种方法可以指定特定值(如?
)以 DISTRO
当 DISTRO
有特殊的价值,并将其设置为%〜1
:
Another method could be to assign a special value (e.g. a ?
) to DISTRO
and shift when /d
is encountered. Then, on the next line, check if DISTRO
has that special value and set it to %~1
:
...
IF /I "%~1"=="/d" SHIFT & SET DISTRO=?
IF "%DISTRO%"=="?" SET "DISTRO=%~1"
...
这篇关于通过类似开关的参数循环批处理文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!