How do I load multiple programs in a Windows batch script? - windows

I'm trying to create a batch file to load multiple Window programs, more specifically, applications that control peripheral flight hardware.
I can't seem to figure out how to open up all applications consecutively. I've tried a number of things including running the executable application:
#echo off
cd "D:\Controls\" & start "D:\HW_Controls\Control1.exe" &
cd "D:\Controls\" & start "D:\HW_Controls\Control2.exe" &
cd "D:\Controls\" & start "D:\HW_Controls\Control3.exe"
That would only run one application at a time, until I exit that application, which is what I don't want. I want them to open consecutively. So I read somewhere on StackOverflow from an old post to try running each application as its own batch file like so:
#echo off
start "D:\Controls1.bat" &
start "D:\Controls2.bat" &
start "D:\Controls3.bat"
In which each batch file within looks similar to this:
cd "D:\Controls\" & start "D:\HW_Controls\Control{1..3}.exe"
I've also tried using chdir:
chdir "D:\Controls\" & start "D:\HW_Controls\Control{1..3}.exe"
When I try to load the batch file within, it doesn't appear to change the directory, and loads only opens a command prompt where the initial batch file is located, in this case, the Desktop directory.
I know there are options to open them on Windows startup, but that's not what I want. I want to load them up when I need to use the applications.
BONUS POINTS: If someone can tell me how to exit all the applications in a batch script as well when I'm finished with them.

The batch parser works line by line. & is used to write two commands in one line. So it doesn't make sense to end a line with a &.
For readability, the use of & should be limited.
cd should be used with the /d switch to be able to switch to another drive.
start takes the first quoted parameter as a window title, so give it a pseudo title.
start has a /d parameter to set the working folder, so you don't need cd at all:
So your batch file simplifies to:
#echo off
start "" /d "D:\Controls\" "D:\HW_Controls\Control1.exe"
start "" /d "D:\Controls\" "D:\HW_Controls\Control2.exe"
start "" /d "D:\Controls\" "D:\HW_Controls\Control3.exe"
echo press any key to kill the program.
pause >nul
taskkill /im "Control1.exe"
taskkill /im "Control2.exe"
taskkill /im "Control3.exe"
Note: taskkill sends a termination signal to the application. If it does not answer correctly by closing itself, you can force-close it with the /f switch.

Here's one method to launch multiple programs at once:
#For %%A in ("notepad.exe" "chrome.exe" "calc.exe") do start "" %%~A

Related

Running Flutter/Dart commands in batch script halts execution [duplicate]

I'm trying to get my commit-build.bat to execute other .BAT files as part of our build process.
Content of commit-build.bat:
"msbuild.bat"
"unit-tests.bat"
"deploy.bat"
This seems simple enough, but commit-build.bat only executes the first item in the list (msbuild.bat).
I have run each of the files separately with no problems.
Use:
call msbuild.bat
call unit-tests.bat
call deploy.bat
When not using CALL, the current batch file stops and the called batch file starts executing. It's a peculiar behavior dating back to the early MS-DOS days.
All the other answers are correct: use call. For example:
call "msbuild.bat"
History
In ancient DOS versions it was not possible to recursively execute batch files. Then the call command was introduced that called another cmd shell to execute the batch file and returned execution back to the calling cmd shell when finished.
Obviously in later versions no other cmd shell was necessary anymore.
In the early days many batch files depended on the fact that calling a batch file would not return to the calling batch file. Changing that behaviour without additional syntax would have broken many systems like batch menu systems (using batch files for menu structures).
As in many cases with Microsoft, backward compatibility therefore is the reason for this behaviour.
Tips
If your batch files have spaces in their names, use quotes around the name:
call "unit tests.bat"
By the way: if you do not have all the names of the batch files, you could also use for to do this (it does not guarantee the correct order of batch file calls; it follows the order of the file system):
FOR %x IN (*.bat) DO call "%x"
You can also react on errorlevels after a call. Use:
exit /B 1 # Or any other integer value in 0..255
to give back an errorlevel. 0 denotes correct execution. In the calling batch file you can react using
if errorlevel neq 0 <batch command>
Use if errorlevel 1 if you have an older Windows than NT4/2000/XP to catch all errorlevels 1 and greater.
To control the flow of a batch file, there is goto :-(
if errorlevel 2 goto label2
if errorlevel 1 goto label1
...
:label1
...
:label2
...
As others pointed out: have a look at build systems to replace batch files.
If we want to open multiple command prompts then we could use
start cmd /k
/k: is compulsory which will execute.
Launching many command prompts can be done as below.
start cmd /k Call rc_hub.bat 4444
start cmd /k Call rc_grid1.bat 5555
start cmd /k Call rc_grid1.bat 6666
start cmd /k Call rc_grid1.bat 5570.
Try:
call msbuild.bat
call unit-tests.bat
call deploy.bat
You are calling multiple batches in an effort to compile a program.
I take for granted that if an error occurs:
1) The program within the batch will exit with an errorlevel;
2) You want to know about it.
for %%b in ("msbuild.bat" "unit-tests.bat" "deploy.bat") do call %%b|| exit /b 1
'||' tests for an errorlevel higher than 0. This way all batches are called in order but will stop at any error, leaving the screen as it is for you to see any error message.
If we have two batch scripts, aaa.bat and bbb.bat, and call like below
call aaa.bat
call bbb.bat
When executing the script, it will call aaa.bat first, wait for the thread of aaa.bat terminate, and call bbb.bat.
But if you don't want to wait for aaa.bat to terminate to call bbb.bat, try to use the START command:
START ["title"] [/D path] [/I] [/MIN] [/MAX] [/SEPARATE | /SHARED]
[/LOW | /NORMAL | /HIGH | /REALTIME | /ABOVENORMAL | /BELOWNORMAL]
[/AFFINITY <hex affinity>] [/WAIT] [/B] [command/program]
[parameters]
Exam:
start /b aaa.bat
start /b bbb.bat
call msbuild.bat
call unit-tests.bat
call deploy.bat
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
To call a .bat file within a .bat file, use
call foo.bat
(Yes, this is silly, it would make more sense if you could call it with foo.bat, like you could from the command prompt, but the correct way is to use call.)
Simplest Way To Run Multiple Batch Files Parallelly
start "systemLogCollector" /min cmd /k call systemLogCollector.bat
start "uiLogCollector" /min cmd /k call uiLogCollector.bat
start "appLogCollector" /min cmd /k call appLogCollector.bat
Here three batch files are run on separate command windows in a minimized state. If you don't want them minimized, then remove /min. Also, if you don't need to control them later, then you can get rid of the titles. So, a bare-bone command will be- start cmd /k call systemLogCollector.bat
If you want to terminate them, then run these commands-
taskkill /FI "WindowTitle eq appLogCollector*" /T /F
taskkill /FI "WindowTitle eq uiLogCollector*" /T /F
taskkill /FI "WindowTitle eq systemLogCollector*" /T /F
Start msbuild.bat
Start unit-tests.bat
Start deploy.bat
If that doesn't work, replace start with call or try this:
Start msbuild.bat
Goto :1
:1
Start unit-tests.bat
Goto :2
:2
Start deploy.bat
Looking at your filenames, have you considered using a build tool like NAnt or Ant (the Java version). You'll get a lot more control than with bat files.
If you want to open many batch files at once you can use the call command. However, the call command closes the current bat file and goes to another. If you want to open many at once, you may want to try this:
#echo off
start cmd "call ex1.bat&ex2.bat&ex3.bat"
And so on or repeat start cmd "call..." for however many files. This works for Windows 7, but I am not sure about other systems.
Your script should be:
start "msbuild.bat"
start "unit-tests.bat"
start "deploy.bat"
Just use the call command! Here is an example:
call msbuild.bat
call unit-tests.bat
call deploy.bat
With correct quoting (this can be tricky sometimes):
start "" /D "C:\Program Files\ProgramToLaunch" "cmd.exe" "/c call ""C:\Program Files\ProgramToLaunch\programname.bat"""
1st arg - Title (empty in this case)
2nd arg - /D specifies starting directory, can be ommited if want the current working dir (such as "%~dp0")
3rd arg - command to launch, "cmd.exe"
4th arg - arguments to command, with doubled up quotes for the arguments inside it (this is how you escape quotes within quotes in batch)
Running multiple scripts in one I had the same issue. I kept having it die on the first one not realizing that it was exiting on the first script.
:: OneScriptToRunThemAll.bat
CALL ScriptA.bat
CALL ScriptB.bat
EXIT
:: ScriptA.bat
Do Foo
EXIT
::ScriptB.bat
Do bar
EXIT
I removed all 11 of my scripts EXIT lines and tried again and all 11 ran in order one at a time in the same command window.
:: OneScriptToRunThemAll.bat
CALL ScriptA.bat
CALL ScriptB.bat
EXIT
::ScriptA.bat
Do Foo
::ScriptB.bat
Do bar
I know I am a bit late to the party, but here is another way. That is, this method should wait until the first one is done, the second, and so on.
start "" /wait cmd.exe /c msbuild.bat
start "" /wait cmd.exe /c unit-tests.bat
start "" /wait cmd.exe /c deploy.bat
The only issue that may come out of using this method, is that with new instances of cmd.exe being spawned, is that Errorlevel checking is kept within in each instance of cmd.exe.
Or..
start "" /wait call msbuild.bat
start "" /wait call unit-tests.bat
start "" /wait call deploy.bat
Hope this helps.

Getting a Windows batch file to execute an application in background and then execute the next statement

I am having issue trying to get my Windows batch file to launch the Jetty web server in the background and then launch IE. The current behavior is that after it started my Jetty web server, it doesn't return to launch IE. It simply stuck there until I terminate the web server and then batch script will then proceed and launch IE.
Here's my batch script
SET JAVA_HOME=".\openjdk-1.8.0.141"
SET JETTY_HOME=".\jetty-distribution-9.4.6.v20170531"
start /B cd /d "%~dp0" & %JAVA_HOME%\bin\javaw -DSTOP.PORT=8081 -DSTOP.KEY=stop_jetty -Djetty.base=%JETTY_HOME% -jar %JETTY_HOME%\start.jar
"C:\Program Files\Internet Explorer\iexplore.exe" http://localhost:8080/foo-tools
Can you spot anything obvious here? I already used the 'start /B' to attempt to launch it in the background. I have to change directory back to the current working directory, otherwise the variable that I set will not work.
Thanks in advance!
Why not simplify things and stipulate the script path with the START's /D <Path> parameter?
SET "JAVA_HOME=openjdk-1.8.0.141"
SET "JETTY_HOME=jetty-distribution-9.4.6.v20170531"
START "" /D "%~dp0" "%JAVA_HOME%\bin\javaw" -DSTOP.PORT=8081 -DSTOP.KEY=stop_jetty -Djetty.base="%JETTY_HOME%" -jar "%JETTY_HOME%\start.jar"
START "" "%PROGRAMFILES%\Internet Explorer\iexplore.exe" http://localhost:8080/foo-tools
I missed off START's /B parameter because it was my understanding that javaw.exe doesn't open a CMD window anyhow. If my understanding is incorrect then please add it back just before "%JAVA_HOME%.
The START command for IE is only really necessary if you need the script again or don't want the cmd window to remain open.

Why is the following multiple DOS commands in one line not working correctly? (Passing Values)

I am trying to create a text file via DOS commands. The commands asks one for the name of the file prior to creating it. I have looked here and here and elsewhere to get me started.
I would like the code to work in one line. So, I should be able to type the entire code in Windows Start > Run box.
This is what I have:
cmd /k #ECHO OFF & SET /P filename=What File name: & copy NUL %filename%.txt & :End
This however ignores the name of the file I gave when asked, and creates %filename%.txt.
I have tried changing the operator before the word copy to |, &&, and & but these don't even ask me for a file name and simply create %filename%.txt
Also, the cmd box stays open after the text file is created.
P.S. I know I can use /q before /k for echo off.
I look forward to your help.
This works here: delayed expansion is used in another cmd process
cmd /c #ECHO OFF & SET /P filename=What File name: & cmd /v /c copy NUL !filename!.txt & exit
The command line has no path defined for the directory and when using the RUN box it will probably be created in the c:\windows\system32 folder, except you will not have write access to that folder.

Command to start a process in the background and run silently

I'm trying to write a command in a bat file to run an installer exe file. The important part is to start and run the installer in silent mode. To clarify, I DO NOT want the user to see the installer and click through the wizard. They should just be able to double click the bat file and walk away. I have attempted this command in my bat file:
#echo off
REM Next command runs installer in silent mode
start /d "%USERPROFILE%\Desktop" MyInstaller_7.1.51.14.exe –s –v –qn
The –s –v –qn are supposed to enable the installer to run in the background, but they are not working.
Can anyone help me improve my command in my bat file so that MyInstaller_7.1.51.14.exe is indeed running in the background, silently, with no UI or wizard of any kind visible to the user??
Please help.
You can try one of these START command options to see if it gives you the effect you want:
/B = Start application without creating a new window
/MIN = Start window minimized
Edited:
Try putting the command with its switches inside quotes:
start /d "%USERPROFILE%\Desktop" "MyInstaller_7.1.51.14.exe –s –v –qn"
Another solution you can test :
Create a file RunHide.vbs and put this line in it :
CreateObject("Wscript.Shell").Run """" & WScript.Arguments(0) & """", 0, False
and then run your batch file like this :
wscript.exe "RunHide.vbs" "Install.bat"
and your batch file will be run without any windows (and maybe your Installer to)
I finally figured it out.
Here is the correct code:
#echo off
REM Next command runs installer in silent mode
start "%USERPROFILE%\Desktop" MyInstaller_7.1.51.14.exe /s /v /qn
The change was between –s –v –qn and /s /v /qn where the former does not work, and the latter does.

How do I minimize the command prompt from my bat file

I have this bat file and I want to minimize the cmd window when I run it:
#echo off
cd /d C:\leads\ssh
call C:\Ruby192\bin\setrbvars.bat
ruby C:\leads\ssh\put_leads.rb
I want the command window minimized immediately. Any ideas on how to do this?
There is a quite interesting way to execute script minimized by making him restart itself minimised. Here is the code to put in the beginning of your script:
if not DEFINED IS_MINIMIZED set IS_MINIMIZED=1 && start "" /min "%~dpnx0" %* && exit
... script logic here ...
exit
How it works
When the script is being executed IS_MINIMIZED is not defined (if not DEFINED IS_MINIMIZED) so:
IS_MINIMIZED is set to 1: set IS_MINIMIZED=1.
Script starts a copy of itself using start command && start "" /min "%~dpnx0" %* where:
"" - empty title for the window.
/min - switch to run minimized.
"%~dpnx0" - full path to your script.
%* - passing through all your script's parameters.
Then initial script finishes its work: && exit.
For the started copy of the script variable IS_MINIMIZED is set by the original script so it just skips the execution of the first line and goes directly to the script logic.
Remarks
You have to reserve some variable name to use it as a flag.
The script should be ended with exit, otherwise the cmd window wouldn't be closed after the script execution.
If your script doesn't accept arguments you could use argument as a flag instead of variable:
if "%1" == "" start "" /min "%~dpnx0" MY_FLAG && exit
or shorter
if "%1" == "" start "" /min "%~f0" MY_FLAG && exit
Use the start command, with the /min switch to run minimized. For example:
start /min C:\Ruby192\bin\setrbvars.bat
Since you've specified a batch file as the argument, the command processor is run, passing the /k switch. This means that the window will remain on screen after the command has finished. You can alter that behavior by explicitly running cmd.exe yourself and passing the appropriate switches if necessary.
Alternatively, you can create a shortcut to the batch file (are PIF files still around), and then alter its properties so that it starts minimized.
The only way I know is by creating a Windows shortcut to the batch file and then changing its properties to run minimized by default.
Using PowerShell you can minimize from the same file without opening a new instance.
powershell -window minimized -command ""
Also -window hidden and -window normal is available to hide completely or restore.
source: https://stackoverflow.com/a/45061676/1178975
If you want to start the batch for Win-Run / autostart, I found I nice solution here https://www.computerhope.com/issues/ch000932.htm & https://superuser.com/questions/364799/how-to-run-the-command-prompt-minimized
cmd.exe /c start /min myfile.bat ^& exit
the cmd.exe is needed as start is no windows command that can be executed outside a batch
/c = exit after the start is finished
the ^& exit part ensures that the window closes even if the batch does not end with exit
However, the initial cmd is still not minimized.
One way to 'minimise' the cmd window is to reduce the size of the console using something like...
echo DO NOT CLOSE THIS WINDOW
MODE CON COLS=30 LINES=2
You can reduce the COLS to about 18 and the LINES to 1 if you wish.
The advantage is that it works under WinPE, 32-bit or 64-bit, and does not require any 3rd party utility.
If you type this text in your bat file:
start /min blah.exe
It will immediately minimize as soon as it opens the program. You will only see a brief flash of it and it will disappear.
You could try running a script as follows
var WindowStyle_Hidden = 0
var objShell = WScript.CreateObject("WScript.Shell")
var result = objShell.Run("cmd.exe /c setrbvars.bat", WindowStyle_Hidden)
save the file as filename.js
Yet another free 3rd party tool that is capable of minimizing the console window at any time (not only when starting the script) is Tcl with the TWAPI extension:
echo package require twapi;twapi::minimize_window [twapi::get_console_window] | tclkitsh -
here tclkitsh.exe is in the PATH and is one of the tclkit-cli-*-twapi-*.exe files downloadable from sourceforge.net/projects/twapi/files/Tcl binaries/Tclkits with TWAPI/. I prefer it to the much lighter min.exe mentioned in Bernard Chen's answer because I use TWAPI for countless other purposes already.
You can minimize the command prompt on during the run but you'll need two additional scripts: windowMode and getCmdPid.bat:
#echo off
call getCmdPid
call windowMode -pid %errorlevel% -mode minimized
cd /d C:\leads\ssh
call C:\Ruby192\bin\setrbvars.bat
ruby C:\leads\ssh\put_leads.rb
One option is to find one of the various utilities that can change the window state of the currently running console window and make a call to it from within the batch script.
You can run it as the first thing in your batch script. Here are two such tools:
min.exe
http://www.paulsadowski.com/wsh/cmdprogs.htm
cmdow
http://www.commandline.co.uk/cmdow/index.html
Another option that works fine for me is to use ConEmu, see http://conemu.github.io/en/ConEmuArgs.html
"C:\Program Files\ConEmu\ConEmu64.exe" -min -run myfile.bat
try these
CONSOLESTATE /Min
or:
SETCONSOLE /minimize
or:
TITLE MinimizeMePlease
FOR /F %%A IN ('CMDOW ˆ| FIND "MinimizeMePlease"') DO CMDOW %%A /MIN
http://conemu.github.io/en/ConEmuArgs.html download flagged by Virus Total.
May have Malware.

Resources