using «&«
As you have noticed executing the bat directly without CALL
,START
, CMD /C
causes to enter and execute the first file and then the process to stop as the first file is finished. Though you still can use &
which will be the same as using command1 & command2
directly in the console:
(
first.bat
)&(
second.bat
)& (
third.bat
)&(
echo other commands
)
In a term of machine resources this will be the most efficient way though in the last block you won’t be able to use command line GOTO
,SHIFT
,SETLOCAL
.. and its capabilities will almost the same as in executing commands in the command prompt. And you won’t be able to execute other command after the last closing bracket
Using CALL
call first.bat
call second.bat
call third.bat
In most of the cases it will be best approach — it does not create a separate process but has almost identical behaviour as calling a :label
as subroutine. In MS terminology it creates a new «batch file context and pass control to the statement after the specified label. The first time the end of the batch file is encountered (that is, after jumping to the label), control returns to the statement after the call statement.»
You can use variables set in the called files (if they are not set in a SETLOCAL
block), you can access directly labels in the called file.
CMD /C
, Pipes ,FOR /F
Other native
option is to use CMD /C
(the /C switch will force the called console to exit and return the control)
Something that cmd.exe is doing in non transparent way with using FOR /F
against bat file or when pipes are used.
This will spawn a child process that will have all the environment ot the calling bat.
Less efficient in terms of resources but as the process is separate ,parsing crashes or calling an EXIT
command will not stop the calling .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
START
Allows you more flexibility as the capability to start the scripts in separate window , to not wait them to finish, setting a title and so on. By default it starts the .bat
and .cmd
scripts with CMD /K
which means that the spawned scripts will not close automatically.Again passes all the environment to the started scripts and consumes more resources than 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
WMIC
Unlike the other methods from now on the examples will use external of the CMD.exe utilities (still available on Windows by default).
WMIC utility will create completely separate process so you wont be able directly to wait to finish. Though the best feature of WMIC is that it returns the id of the spawned process:
:: 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%
You can also use it to start a process on a remote machine , with different user and so on.
SCHTASKS
Using SCHTASKS provides some features as (obvious) scheduling , running as another user (even the system user) , remote machine start and so on. Again starts it in completely separate environment (i.e. its own variables) and even a hidden process, xml file with command parameters and so on :
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
Here the PID also can acquired from the event log.
ScriptRunner
Offers some timeout between started scripts. Basic transaction capabilities (i.e. rollback on error) and the parameters can be put in a separate XML file.
::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
using «&«
As you have noticed executing the bat directly without CALL
,START
, CMD /C
causes to enter and execute the first file and then the process to stop as the first file is finished. Though you still can use &
which will be the same as using command1 & command2
directly in the console:
(
first.bat
)&(
second.bat
)& (
third.bat
)&(
echo other commands
)
In a term of machine resources this will be the most efficient way though in the last block you won’t be able to use command line GOTO
,SHIFT
,SETLOCAL
.. and its capabilities will almost the same as in executing commands in the command prompt. And you won’t be able to execute other command after the last closing bracket
Using CALL
call first.bat
call second.bat
call third.bat
In most of the cases it will be best approach — it does not create a separate process but has almost identical behaviour as calling a :label
as subroutine. In MS terminology it creates a new «batch file context and pass control to the statement after the specified label. The first time the end of the batch file is encountered (that is, after jumping to the label), control returns to the statement after the call statement.»
You can use variables set in the called files (if they are not set in a SETLOCAL
block), you can access directly labels in the called file.
CMD /C
, Pipes ,FOR /F
Other native
option is to use CMD /C
(the /C switch will force the called console to exit and return the control)
Something that cmd.exe is doing in non transparent way with using FOR /F
against bat file or when pipes are used.
This will spawn a child process that will have all the environment ot the calling bat.
Less efficient in terms of resources but as the process is separate ,parsing crashes or calling an EXIT
command will not stop the calling .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
START
Allows you more flexibility as the capability to start the scripts in separate window , to not wait them to finish, setting a title and so on. By default it starts the .bat
and .cmd
scripts with CMD /K
which means that the spawned scripts will not close automatically.Again passes all the environment to the started scripts and consumes more resources than 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
WMIC
Unlike the other methods from now on the examples will use external of the CMD.exe utilities (still available on Windows by default).
WMIC utility will create completely separate process so you wont be able directly to wait to finish. Though the best feature of WMIC is that it returns the id of the spawned process:
:: 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%
You can also use it to start a process on a remote machine , with different user and so on.
SCHTASKS
Using SCHTASKS provides some features as (obvious) scheduling , running as another user (even the system user) , remote machine start and so on. Again starts it in completely separate environment (i.e. its own variables) and even a hidden process, xml file with command parameters and so on :
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
Here the PID also can acquired from the event log.
ScriptRunner
Offers some timeout between started scripts. Basic transaction capabilities (i.e. rollback on error) and the parameters can be put in a separate XML file.
::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
Windows, Windows 10, Windows 7, Windows 8, Windows Server, Windows Vista, Windows XP
- 28.05.2020
- 19 114
- 1
- 68
- 67
- 1
- Содержание статьи
- Способ 1: С ожиданием завершения запущенного bat-файла
- Способ 2: Без ожидания (параллельная работа) запущенного bat-файла
- Комментарии к статье ( 1 шт )
- Добавить комментарий
Иногда, при выполнении пакетного файла, возникает необходимость запустить другой пакетный файл. Причем, в некоторых случаях, выполнение основного пакетного файла должно быть приостановлено, пока выполняется вспомогательный файл, а в других вспомогательный файл должен работать параллельно с основным.
Способ 1: С ожиданием завершения запущенного bat-файла
Для примера создадим два bat файла. Один с именем 1.bat и содержащий всего одну команду
call 2.bat
Второй с именем 2.bat и также содержащий одну команду
pause
Теперь запустим файл 1.bat Откроется окно, в котором будет предложено нажать любую клавишу для продолжения, после нажатия которой окно закроется. Таким образом, вызов из одного пакетного файла другого при помощи команды call останавливает исполнение пакетного файла до тех пор, пока не завершится выполнение пакетного файла, вызванного командой call.
Способ 2: Без ожидания (параллельная работа) запущенного bat-файла
В другом случае, надо запустить из bat файла либо приложение, либо другой пакетный файл, не прерывая выполнения основного пакетного файла. Такое нередко бывает нужно сделать, например, принудительно открыв лог работы пакетного файла, запланированного на ночь, чтобы с утра, пользователь мог проконтролировать правильность его выполнения. Для этого используется команда start Исправим в файле 1.bat строку на
start 2.bat
и запустим файл 1.bat Теперь открылось окно, в котором для продолжения надо нажать любую кнопку, а окно основного пакетного файла (1.bat) отработав закрылось.
Таким образом, для вызова из одного пакетного файла другого, без остановки работы первого пакетного файла, нужно применять команду start.
Рассмотренные команды start и call могут использоваться не только для запуска других пакетных файлов, но и для запуска любых приложений или открытия файлов.
Например, команда start log.txt
, находящаяся в теле пакетного файла, откроет файл log.txt в Notepad без остановки работы пакетного файла.
I have a batch file which runs as a scheduled task. For the sake of example lets call it alltasks.bat
.
It looks like the following:
@ECHO OFF
clearwebtemp.bat > clearwebtemp_out.txt
clearblahtemp.bat > clearblahtemp_out.txt
clearblihtemp.bat > clearblihtemp_out.txt
This works fine when none of the called scripts change directories, but if they do then the main script fails to complete the remaining batch calls or pipe the output to the files.
I tried using the start
command, but that predictably piped the output of the start
command rather than that of the batch file itself.
I also tried retaining the current working directory using the %CD%
variable at the top of the script and then switching back to it after each call, but the piping out to the file was done inside the directory that the script switched to, which didn’t seem to make sense.
Is there an obvious (or not-so-obvious) way to achieve what I’m attempting to accomplish?
asked Aug 22, 2012 at 16:25
3
This should do what you’re asking for:
cmd /c clearwebtemp.bat > clearwebtemp_out.txt
cmd /c clearblahtemp.bat > clearblahtemp_out.txt
cmd /c clearblihtemp.bat > clearblihtemp_out.txt
answered Aug 24, 2012 at 4:24
Harry JohnstonHarry Johnston
5,7647 gold badges31 silver badges55 bronze badges
Another Solution:
@ECHO OFF
pushd .
call clearwebtemp.bat > clearwebtemp_out.txt
popd
pushd .
call clearblahtemp.bat > clearblahtemp_out.txt
popd
pushd .
call clearblihtemp.bat > clearblihtemp_out.txt
or
@ECHO OFF
call clearwebtemp.bat > clearwebtemp_out.txt
%~d0
cd %~p0
call clearblahtemp.bat > clearblahtemp_out.txt
%~d0
cd %~p0
call clearblihtemp.bat > clearblihtemp_out.txt
You can ignore the %~d0
if your bats stay on the same drive.
answered Oct 15, 2015 at 22:51
LimerLimer
4293 silver badges9 bronze badges
You can do this using cmd /c "for command"
in loop:
@cmd /q /s /c "for %%i in (web,blah,blih)do "clear%%~itemp.bat" > "clear%%~itemp_out.txt""
clear+ web +temp.bat > clear+ web + temp_out.txt
clear+ blah +temp.bat > clear+ blah + temp_out.txt
clear+ blih +temp.bat > clear+ blih + temp_out.txt
@cmd /q /s /c "for ( web, blah, blih ) + "clear + %%~i + temp.cmd" > "clear + %%~i + temp_out.txt""
- To call and wait for each to run before calling the next, use
call file.bat
:
@cmd /q /s /c "for %%i in (web,blah,blih)do call "clear%%~itemp.bat" > "clear%%~itemp_out.txt""
answered Jan 11, 2021 at 15:40
Io-oIIo-oI
7,7453 gold badges12 silver badges41 bronze badges
You must log in to answer this question.
Not the answer you’re looking for? Browse other questions tagged
.
Not the answer you’re looking for? Browse other questions tagged
.
1
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
Иногда, при выполнении пакетного файла, возникает необходимость запустить другой пакетный файл. Причем, в некоторых случаях, выполнение основного пакетного файла должно быть приостановлено, пока выполняется вспомогательный файл,а в других вспомогательный файл должен работать параллельно с основным. Для примера создадим два bat файла. Один с именем 1.bat и содержащий всего одну команду call 2.bat Второй с именем 2.bat и также содержащий одну команду pause Теперь запустим файл 1.bat Откроется окно, в котором будет предложено нажать любую клавишу для продолжения, после нажатия которой окно закроется. Таким образом, вызов из одного пакетного файла другого при помощи команды call останавливает исполнение пакетного файла до тех пор, пока не завершится выполнение пакетного файла, вызванного командой call. |
2
В другом случае, надо запустить из bat файла либо приложение, либо другой пакетный файл, не прерывая выполнения основного пакетного файла. Такое нередко бывает нужно сделать, например, принудительно открыв лог работы пакетного файла, запланированного на ночь, чтобы с утра, пользователь мог проконтролировать правильность его выполнения. Для этого используется команда start Исправим в файле 1.bat строку на start 2.bat и запустим файл 1.bat Теперь открылось окно, в котором для продолжения надо нажать любую кнопку, а окно основного пакетного файла (1.bat) отработав закрылось. Таким образом, для вызова из одного пакетного файла другого, без остановки работы первого пакетного файла, нужно применять команду start. Рассмотренные команды start и call могут использоваться не только для запуска других пакетных файлов, но и для запуска любых приложений или открытия файлов. Например, команда start log.txt, находящаяся в теле пакетного файла, откроет файл log.txt в Notepad без остановки работы пакетного файла. |