我有一个批处理文件,应该输入“-input1”,“ - input2”和“-input3”。在这里我需要验证参数,如果用户将输入参数指定为“-test”或“-blah”或任何其他参数,那么我应该将错误抛出为“未注册的参数”。我怎样才能实现这一目标?我尝试通过%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
任何帮助..
答案 0 :(得分: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
答案 1 :(得分: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!"