如何在 BATCH 文件中使用 SWITCH 解析命令行参数 [英] How to parse command line arguments with SWITCH in BATCH file
问题描述
我们正在尝试创建一个 switch 语句来解析批处理文件中的命令行参数.
We are trying to make a switch statement which is parsing command line argument in a batch file.
mybatch.bat -a 10 -b name -c India --zipcode 20
只有-a
、-b
、-c
是解析参数(以-
开头).
Only -a
, -b
, -c
are parsing parameter (which is starts with -
).
我们的代码如下:
for %%x in (%*) do (
switch(%%x) (
case a:
SET first_number=%arg%
break
case b:
SET name=%arg%
case c:
for %%x in (%*) do (
SET place =%place% %arg%
)
default:
echo wrong parameter
)
推荐答案
通常你会尽量保持简单,并为参数设置一个顺序.要以任何方式处理参数,随机顺序比仅仅知道 %1 = 数字、%2 = 名称和 %3 以上 = 位置要费力得多.
Normally you try to keep things simple and have a set order for the parameters. To handle parameters in any, random order is a lot more effort than just knowing that %1 = number, %2 = name and %3 onwards = place.
也就是说,这是一个解决方案的尝试.我忽略了 place 部分中的 --params,只是将这些值连接在一起.
That said, here's an attempt at a solution. I'm ignoring --params in the place section, just joining the values together.
@echo off
setlocal
:loop
if x%1 equ x goto done
set param=%1
if %param:~0,1% equ - goto checkParam
:paramError
echo Parameter error: %1
:next
shift /1
goto loop
:checkParam
if "%1" equ "-a" goto A
if "%1" equ "-b" goto B
if "%1" equ "-c" goto C
goto paramError
:A
shift /1
set first_number=%1
goto next
:B
shift /1
set name=%1
goto next
:C
set place=
:GetPlaces
shift /1
set param=%1
if not defined param goto donePlaces
if %param:~0,2% equ -- (
shift /1
goto processPlace
)
if %param:~0,1% equ - goto donePlaces
:processPlace
echo.%place%
if x%1 neq x (
set place=%place% %1
goto GetPlaces
)
:donePlaces
rem remove leading space
if defined place set place=%place:~1%
goto loop
:done
echo num=%first_number% name=%name% place=%place%
这篇关于如何在 BATCH 文件中使用 SWITCH 解析命令行参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!