如何将逗号分隔参数传递给批处理文件并在批处理文件中使用if else?

时间:2015-11-27 10:50:22

标签: windows batch-file cmd

我有一个批处理文件MyTest.bat

MyTest.bat

call "first.bat" 

call "second.bat" 

call "third.bat"

现在,在执行MyTest.bat时,我将传递逗号分隔的参数,如

调用MyTest.bat first.bat,second.bat

现在在MyTest.bat里面我想检查传递的参数以及使用if else条件的参数

我想执行内部声明。

例如类似的东西

MyTest.bat first.bat,second.bat

now inside 

I will check 

get all parameters list param[] = {first.bat,second.bat}

if param[i] ==  "first.bat" 

{

call "first.bat" 

}

else if param[i] ==  "second.bat" 


{

call "second.bat" 

}

else if param[i] ==  "third.bat" 


{

call "third.bat" 

}

//这确保了我只传递那些语句的参数而不是其他参数。

上面的代码只是一个伪代码,怎么写实际的MyTest.bat?

1 个答案:

答案 0 :(得分:1)

下一个脚本需要另一个参数顺序(批处理名称列表以结束所有其他参数):

@ECHO OFF
SETLOCAL EnableExtensions
rem usage: 33955749.bat name address "first script", second, third
:loop
  if "%~3" == "" goto :next
  if exist "%~n3.bat" (
    call "%~n3.bat" %1 %2
  ) else (
    echo can't found file; failed call "%~n3.bat" %1 %2 
  )
  shift /3
  goto :loop
:next

出于调试目的,准备样本文件"first script.bat"second.bat;确保third.bat不存在:

==> >"first script.bat" echo @echo %~nx0 parameters: %%*=%*

==> >second.bat echo @echo %~nx0 parameters: %%*=%*

==> 2>NUL del third.bat

输出(显示对使用过的delimiters的独立性):

==> 33955749 name address "first script", second, third
first script.bat parameters: %*=name address
second.bat parameters: %*=name address
can't found file; failed call "third.bat" name address

==> 33955749 name address "first script"  second; third
first script.bat parameters: %*=name address
second.bat parameters: %*=name address
can't found file; failed call "third.bat" name address

另一种方法:拳头参数=用一对双引号括起来的逗号分隔批名称列表:

@ECHO OFF
SETLOCAL EnableExtensions
rem usage: 33955749b "first script,second,third" name address
rem no spaces surrounding commas or names
rem wrong: 33955749b " first script , second, third" would fail
set "_names=%~1"
set "_names=%_names:,=","%"
rem debug echo _names="%_names%"
for  %%G in ("%_names%") do (
  if exist "%%~dpnG.bat" (
    call "%%~dpnG.bat" %2 %3
  ) else (
    echo can't found script; failed call "%%~dpnG.bat" %2 %3 
  )
)

输出(显示对已使用分隔符的响应度):

==> 33955749b "first script,second,third" name address
first script.bat parameters: %*=name address
second.bat parameters: %*=name address
can't found script; failed call "D:\bat\SO\third.bat" name address

==> 33955749b "first script, second,third" name address
first script.bat parameters: %*=name address
can't found script; failed call "D:\bat\SO\ second.bat" name address
can't found script; failed call "D:\bat\SO\third.bat" name address

请注意,33955749.bat33955749b.bat脚本

  • 接受(部分或完全限定的)被调用脚本的路径,即使是空格也是如此;
  • 另一方面,
  • 即使提供了文件扩展名,也会忽略文件扩展名并强制.bat

例如,33955749 name address first.cmd second.cmd会尝试拨打first.batsecond.bat

资源(必读,不完整):