使用“&”
正如您注意到的那样,直接执行 bat 而不使用 CALL、START、CMD /C 会导致进入并执行第一个文件,然后在第一个文件完成时进程停止。虽然您仍然可以使用&,这与直接在控制台中使用command1 & command2 相同:
(
first.bat
)&(
second.bat
)& (
third.bat
)&(
echo other commands
)
就机器资源而言,这将是最有效的方式,但在最后一个区块中,您将无法使用命令行GOTO,SHIFT,SETLOCAL.. 它的功能几乎是与在命令提示符下执行命令相同。并且在最后一个右括号之后您将无法执行其他命令
call first.bat
call second.bat
call third.bat
在大多数情况下,这将是最好的方法 - 它不会创建单独的进程,但具有与调用 :label 作为子例程几乎相同的行为。在MS术语中,它创建一个新的“批处理文件上下文并将控制权传递给指定标签之后的语句。第一次遇到批处理文件的结尾(即跳转到标签后),控制权返回到后面的语句调用语句。”
您可以使用在被调用文件中设置的变量(如果它们没有设置在SETLOCAL 块中),您可以使用access directly labels in the called file。
CMD /C, 管道,FOR /F
其他native 选项是使用CMD /C(/C 开关将强制被调用的控制台退出并返回控制)
cmd.exe 以非透明方式对 bat 文件使用 FOR /F 或使用管道时所做的事情。
这将产生一个子进程,该进程将拥有调用 bat 的所有环境。
在资源方面效率较低,但由于进程是独立的,解析崩溃或调用EXIT 命令不会停止调用.bat
@echo off
CMD /c first.bat
CMD /C second.bat
::not so different than the above lines.
:: MORE,FINDSTR,FIND command will be able to read the piped data
:: passed from the left side
break|third.bat
允许您更灵活地在单独的窗口中启动脚本、不等待它们完成、设置标题等。默认情况下,它以CMD /K 启动.bat 和.cmd 脚本,这意味着生成的脚本不会自动关闭。再次将所有环境传递给启动的脚本并消耗比cmd /c 更多的资源:
:: will be executed in the same console window and will wait to finish
start "" /b /w cmd /c first.bat
::will start in a separate console window and WONT wait to be finished
:: the second console window wont close automatically so second.bat might need explicit exit command
start "" second.bat
::Will start it in a separate window ,but will wait to finish
:: closing the second window will cause Y/N prompt
:: in the original window
start "" /w third.cmd
::will start it in the same console window
:: but wont wait to finish. May lead to a little bit confusing output
start "" /b cmd /c fourth.bat
与从现在开始的其他方法不同,示例将使用 CMD.exe 实用程序的外部(默认情况下仍可在 Windows 上使用)。
WMIC 实用程序将创建完全独立的进程,因此您将无法直接等待完成。虽然 WMIC 的最佳特性是它返回生成进程的 id:
:: will create a separate process with cmd.exe /c
WMIC process call create "%cd%\first.bat","%cd%"
::you can get the PID and monitoring it with other tools
for /f "tokens=2 delims=;= " %%# in ('WMIC process call create "%cd%\second.bat"^,"%cd%" ^|find "ProcessId"') do (
set "PID=%%#"
)
echo %PID%
你也可以用它在远程机器上启动一个进程,使用不同的用户等等。
使用 SCHTASKS 提供了一些功能,例如(明显的)调度、作为另一个用户(甚至是系统用户)运行、远程机器启动等。再次在完全独立的环境(即它自己的变量)甚至隐藏进程、带有命令参数的 xml 文件等中启动它:
SCHTASKS /create /tn BatRunner /tr "%cd%\first.bat" /sc ONCE /sd 01/01/1910 /st 00:00
SCHTASKS /Run /TN BatRunner
SCHTASKS /Delete /TN BatRunner /F
这里的PID也可以从事件日志中获取。
在启动的脚本之间提供一些超时。基本事务功能(即错误回滚)和参数可以放在单独的 XML 文件中。
::if the script is not finished after 15 seconds (i.e. ends with pause) it will be killed
ScriptRunner.exe -appvscript %cd%\first.bat -appvscriptrunnerparameters -wait -timeout=15
::will wait or the first called script before to start the second
:: if any of the scripts exit with errorcode different than 0 will try
:: try to restore the system in the original state
ScriptRunner.exe -appvscript second.cmd arg1 arg2 -appvscriptrunnerparameters -wait -rollbackonerror -appvscript third.bat -appvscriptrunnerparameters -wait -timeout=30 -rollbackonerror