2

我有一个批处理文件,它应该接受输入“-input1”、“-input2”和“-input3”。在这里,我需要验证参数,例如用户是否将输入参数作为“-test”或“-blah”或任何其他参数,那么我应该将错误作为“unregonized parameter”抛出。我怎样才能做到这一点?我尝试通过将参数迭代为 %1 %2 等,但我无法实现所需的行为。

IF "%1"=="" (
 GOTO :ERROR3
)
IF "%1"=="-input1"  (
 SET value1=%2
)
@IF "%3"=="-input1"  (
 SET value1=%4
)
@IF "%5"=="-input1"  (
 SET value1=%6
)
@IF "%7"=="-input1"  (
 SET value1=%8
)
IF "%1"=="-input2" (
 SET value1=%2
)
@IF "%3"=="-input2" (
 SET value2=%4
)
@IF "%5"=="-input2" (
 SET value2=%6
)
@IF "%7"=="-input2" (
 SET value2=%8
)
IF "%1"=="-input3" (
 SET value3=%2
)
@IF "%3"=="-input3" (
 SET value3=%4
)
@IF "%5"=="-input3" (
 SET value3=%6
)
@IF "%7"=="-input3" (
 SET value3=%8
)

    // some codes here

:ERROR1
ECHO "ERROR1"
GOTO :END
:ERROR2
ECHO "ERROR1"
GOTO :END
:ERROR3
ECHO Usage SAMPLE.bat -input1 "value1" -input2 "value2" -input3 "value3"
:END

任何帮助..

4

2 回答 2

3

这是一个简单的参数转换示例

@echo off
setlocal
set "value1="
set "value2="
set "value3="

:Parse
set "Param=%~1"
if not defined Param goto Validate
if "%Param%"=="-input1" set "value1=%2" & goto Next
if "%Param%"=="-input2" set "value2=%2" & goto Next
if "%Param%"=="-input3" set "value3=%2" & goto Next
goto Error1

:Next
shift & shift
goto Parse

:Validate
if defined value1 if defined value2 if defined value3 goto Main
goto Error2

:Main
echo %value1% %value2% %value3%
goto End

:Error1
echo Invalid Parameter: %1 %2
goto End

:Error2
echo Usage %~nx0 -input1 "value1" -input2 "value2" -input3 "value3"
goto End

:End
endlocal
于 2013-10-24T15:56:37.600 回答
0

下面的批处理文件允许您修改参数的数量和名称,只需更改一行。

@echo off
setlocal EnableDelayedExpansion

rem Define the list of parameters
set params=-input1 -input2 -input3

rem Initialize the array of parameters and their values
set n=0
for %%a in (%params%) do (
   set /A n+=1
   set param[%%a]=!n!
   set "value!n!="
)

:nextParam
set "param=%~1"
shift
if not defined param goto start
if defined param[%param%] (
   set "value!param[%param%]!=%~1"
   shift
   goto nextParam
)
echo ERROR - Bad parameter: %param%
goto :EOF

:start
echo Values of given parameters:
echo/
for /L %%i in (1,1,%n%) do echo Value%%i = "!value%%i!"
于 2013-10-24T18:27:37.063 回答