How to execute multiple programs in the same time with a .bat file - windows

I made 2 bat files to start apps with examples below:
My expectation is to execute them simultaneously, meaning after double click bat file, then 3 programs will pop up.
With the 1st example, the behavior is to execute outlook first, then both Mircrosoft Edge and OneNote still not pop up, until I stop Outlook.
Example 1
#echo off
"C:\ProgramData\Microsoft\Windows\Start Menu\Programs\Outlook.lnk"
"C:\ProgramData\Microsoft\Windows\Start Menu\Programs\Microsoft Edge.lnk"
"C:\ProgramData\Microsoft\Windows\Start Menu\Programs\OneNote.lnk"
exit
With the 2nd example, both Mrcrosoft Edge and OneNote were executed simultaneously, however Outlook not until I stop OneNote.
Example 2
#echo off
"C:\ProgramData\Microsoft\Windows\Start Menu\Programs\Microsoft Edge.lnk"
"C:\ProgramData\Microsoft\Windows\Start Menu\Programs\OneNote.lnk"
"C:\ProgramData\Microsoft\Windows\Start Menu\Programs\Outlook.lnk"
exit
My questions is why it behaves like this way and how to make these 3 programs start up in the same time ?
Shown below is the Windows config:
Edition Windows 10 Enterprise
Version 21H2
Installed on ‎10/‎27/‎2021
OS build 19044.1826
Experience Windows Feature Experience Pack 120.2212.4180.0

1)Run the first program using the start command.
2)Check the task list in a loop to see if the program has appeared there.
3)Impose some time limitation to the said loop.
4)Run the next program in case of success, exit with notification otherwise.
#ECHO
OFF START program1.exe
FOR /L %%i IN (1,1,100) DO (
(TASKLIST | FIND /I "program.exe") && GOTO :startnext
:: you might add here some delaying
)
ECHO Timeout waiting for program1.exe to start
GOTO :EOF
:startnext
program2.exe
:: or START
program2.exe
Remember that the timing is not precise, especially if you are going to insert delays between the task list checks.

Normally to run tasks parallel, you should add start /b before the command to run.
The start command allows the command to be executed in another process, while /b prevents the opening of a new window.
In this specific case start /b does not work, for reasons unknown to me, but you can always use cmd /c.

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.

Starting a batch file in a new window from a batch file, and keeping the new window open after completion

EDIT: I will try to make it clearer what I actually want.
I have some very long batch files that I want to run in order and only starting after the previous one had completed.
I am trying to control this with a master batch file
I want them starting each in their own window which remains open after completion to look back later
In numerical order:
1.run main batch file
2.open new cmd window
3.run batch file 1
4.waiting for 1 to finish
5.1 finished, keep window open
6.open another new cmd window
7.run batch2
etc
-- original message --
Hi so I have a windows batch file that needs to run other windows batch files sequentially and wait for them to finish before starting the next one.
Something like:
#echo off
setlocal EnableDelayedExpansion
SET RUN="C:first.bat"
start /wait cmd /c %RUN%
SET RUN="C:second.bat"
start /wait cmd /c %RUN%
where first and second for example just echo something like:
#echo off
echo 1st
exit /b 0
When I run this it starts the first script in a new window and keeps the window open after completing like I want, but to progress to the second script I have to close the new cmd window.
How can I make the main batch script start the second.bat without closing the first.bat cmd window?
Thanks
It is a very unusual requirement that
other batch files should not be processed by the cmd.exe instance processing the main batch file, but by other instances of cmd.exe just to have their outputs in a different console window and
keep each other command process running after finishing the processing of the batch file to be able to view their outputs in their console windows and
wait with further processing of main batch file until processing of a batch file finished by the started separate command process, but do not wait for termination of the started other command processes.
The Windows command processor cmd.exe is not designed for a serialized multi-processing of batch files with multiple instances of itself which finally should keep running.
However, here are three batch files which demonstrate that this is possible with one disadvantage explained later.
Main.bat
#echo off & goto Main
:WaitForBatch
start "Run %~nx1" %ComSpec% /D /S /K "(%ComSpec% /D /C "%~1") & title Finished %~n1"
echo Waiting for finished execution of "%~nx1" ...
:CheckBatchRun
%WaitCommand% >nul
%SystemRoot%\System32\tasklist.exe /NH /FI "IMAGENAME eq cmd.exe" /V | %SystemRoot%\System32\find.exe /I "%~nx1" >nul
if errorlevel 1 goto :EOF
goto CheckBatchRun
:Main
setlocal EnableExtensions DisableDelayedExpansion
title Run %~nx0
if exist %SystemRoot%\System32\timeout.exe (
set "WaitCommand=%SystemRoot%\System32\timeout.exe /T 1"
) else (
set "WaitCommand=%SystemRoot%\System32\ping.exe 127.0.0.1 -n 2"
)
call :WaitForBatch "%~dp0First.bat"
call :WaitForBatch "%~dp0Second.bat"
title Finished %~n0
pause
endlocal
First.bat
#echo off
dir %SystemRoot% /B /S
Second.bat
#echo off
dir %SystemRoot%\*.exe
echo/
pause
Main.bat is coded in a manner expecting First.bat and Second.bat in the same directory as Main.bat, but the other batch files can be also in different directories. The current directory on execution of the three batch files can be any directory.
Main.bat first sets up the execution environment for itself which is:
command echo mode turned off and
command extensions enabled and
delayed expansion disabled.
The window title of the console window of cmd.exe processing Main.bat is modified to show Run Main.bat at beginning.
Next is determined if command TIMEOUT is available in which case this command will be used later for a delay of one second (Windows Vista and later Windows client versions) or if command PING must be used for the one second delay (Windows XP).
Then the subroutine WaitForBatch is called the first time with the batch file First.bat.
The subroutine uses the command START to start one more command process in a new console window with window title Run First.bat with ignoring the AutoRun registry string value which by Windows default does not exist.
This second cmd.exe instance keeps running after execution of the command line specified next with the other arguments is finished. The command line for second cmd.exe requires the execution of a third cmd.exe again with ignoring AutoRun registry string value if existing at all to execute the batch file First.bat specified with fully qualified file name. The third cmd.exe instances closes itself on finishing processing of the batch file.
The second cmd.exe changes now the title of its console window to Finished First. Important is here that the batch file extension is not anymore in the window title.
The first cmd.exe instance processing Main.bat continues with batch file processing already after successful start of second cmd.exe. It uses the command to wait one second and then runs TASKLIST to output all running cmd.exe processes with verbose information which is redirected to command FIND to search case-insensitive for the batch file name First.bat.
As long as there is a cmd.exe process running with First.bat, the first cmd.exe continues batch file processing of Main.bat inside subroutine WaitForBatch in a loop with a jump to CheckBatchRun. Otherwise the subroutine is left and processing of Main.bat continues with the second CALL of WaitForBatch with Second.bat.
Finally Main.bat changes also its window title to Finished Main and prompts the user to press any key in case of Main.bat execution was started with a double click on this file in Windows Explorer.
First.bat takes a very long time to finish as thousands of file names must be output into the console window of second cmd.exe. It is possible to click on the X symbol of console window with title Run First.bat to terminate immediately the execution of second and of third cmd.exe which results in first cmd.exe continues with starting two more cmd.exe for processing Second.bat.
It is also possible to interrupt the long running First.bat by pressing Ctrl+C and answer the prompt for termination of batch job with Y (on English Windows) resulting in third cmd.exe stopping really the processing of First.bat and second cmd.exe keeps running showing the output of First.bat and changing the window title of its console window to Finished First. This is detected by first cmd.exe processing Main.bat and it starts the processing of Second.bat.
The disadvantage of this solution is that on pressing Ctrl+C in console window with title Run First.bat while DIR outputs all the file names and pressing now N (on English Windows) results nevertheless in a termination of the batch job. I am not 100% sure why this happens. I have just a supposition for this behavior.
For understanding the used commands and how they work, open a command prompt window, execute there the following commands, and read entirely all help pages displayed for each command very carefully.
call /?
cmd /?
dir /?
echo /?
endlocal /?
find /?
goto /?
if /?
pause /?
ping /?
setlocal /?
start /?
tasklist /?
timeout /?
title /?

Batch file to close program after second program opens

I have a frontend program (a.exe) that I use to curate and launch other programs (in this example b.exe). Once the item in the frontend (a.exe) is selected from the list (b.exe) launches. Problem is the frontend (a.exe) stays open and to close it I have to manually exit out of the program it launched (b.exe) to the desktop to do so.
What I am trying to do is have the frontend (a.exe) close after an item within it is selected (b.exe). This would be trigged by a double click.
How would I go about creating a batch file to do this?
The frontend program (a.exe) has a GUI interface.
#echo off
cd "C:\Program Files\a.exe folder"
start a.exe
then what?
The best solution would be contacting the author of a.exe and asking for an option to automatically exit a.exe after starting application b.exe as separate and detached process.
The second best solution would be finding out which environment b.exe needs to run successfully and create with a batch file this environment and start b.exe.
However, if the best two solutions are not possible for whatever reason, then the following batch file code be helpful.
#echo off
start "" /D"C:\Program Files\a.exe folder" "a.exe"
set "LoopCount=0"
:Loop
%SystemRoot%\System32\timeout.exe /T 1 /NOBREAK >nul
%SystemRoot%\System32\tasklist.exe /NH | %SystemRoot%\System32\findstr.exe /B /C:"b.exe" /C:"c.exe" /C:"d.exe" >nul
if not errorlevel 1 (
%SystemRoot%\System32\taskkill.exe /IM "a.exe"
goto EndBatch
)
%SystemRoot%\System32\tasklist.exe /NH | %SystemRoot%\System32\findstr.exe /B /C:"a.exe"
if errorlevel 1 goto EndBatch
set /A LoopCount+=1
if not %LoopCount% == 60 goto Loop
:EndBatch
set "LoopCount="
The batch file first starts a.exe with its program files directory set as current directory before starting it as separate process.
Windows command processor immediately continues execution of the batch file after starting a.exe and defines next the environment variable LoopCount with value 0.
Inside the loop the external command TIMEOUT available since Windows Vista by default is used to wait one second.
Then external command TASKLIST is executed to output all running processes without header. This output is redirected with | to external command FINDSTR which searches case-sensitive at beginning of all lines output by TASKLIST for one of the strings specified with the option /C:. For a case-insensitive search use additionally FINDSTR option /I if not knowing how the executables started by a.exe are in list output by TASKLIST.
FINDSTR exits with value 0 on having found at least one line starting with one of the searched strings and with value 1 if nothing matched. The output of FINDSTR is of no interest and therefore redirected to device NUL.
The terminate signal is sent with external command TASKKILL to the executable a.exe on having found one of the processes in the list. a.exe should terminate itself on receiving and processing this signal. In case of a.exe is ignoring this signal or it terminates, but before terminates also the started application, it would be necessary to use additionally the TASKKILL option /F to force a real kill of a.exe process by the Windows operating system. In general the option /F should not be used as it can result in corrupt files in case of application killed by the operating system has one or more files open for write operations.
But if after one second none of the processes started by a.exe is running, the batch file checks next if a.exe itself is still running. The batch file exits if this is not the case. Otherwise it increments the environment variable LoopCount and compares its value with 60 to exit batch file after having waited already 60 seconds with the checks to avoid a nearly endless running batch file.
For understanding the used commands and how they work, open a command prompt window, execute there the following commands, and read entirely all help pages displayed for each command very carefully.
echo /?
findstr /?
goto /?
if /?
set /?
start /?
taskkill /?
tasklist /?
timeout /?
See also Microsoft article about Using command redirection operators.

Batch to check if process exists

I'd like a batch that will check if the process firefox.exe exists (after it has been started by the start command).
If the process exists, it will go to the label :fullscreen,
else the batch will go the the label :timeout. Then, it will check again if the process firefox.exe exists and if not, it will go again to the label :fullscreen until the process exists.
Here is my batch:
#echo off
start "C:\Program Files (x86)\Mozilla Firefox\firefox.exe"
:timeout
timeout /t 5
:fullscreen
nircmd sendkeypress F11
exit
How can I do this check ?
You can also use QUERY PROCESS:
#Echo Off
If Not Exist "%ProgramFiles(x86)%\Mozilla Firefox\firefox.exe" Exit/B
Start "" "%ProgramFiles(x86)%\Mozilla Firefox\firefox.exe"
:Loop
Timeout 5 /NoBreak>Nul
QProcess firefox.exe>Nul 2>&1||GoTo :Loop
NirCmd SendKeyPress F11
I suggest for this task the batch file:
#echo off
start "" /max firefox.exe
if errorlevel 1 goto :EOF
set LoopCount=0
:WaitLoop
%SystemRoot%\System32\timeout.exe /T 5
%SystemRoot%\System32\tasklist.exe /FI "IMAGENAME eq firefox.exe" 2>nul | %SystemRoot%\System32\find.exe /I "firefox.exe" >nul
if not errorlevel 1 nircmd.exe sendkeypress F11 & goto :EOF
set /A LoopCount+=1
if not %LoopCount% == 6 goto WaitLoop
Let me explain the few command lines used here.
1. Starting Firefox
The command START being an internal command of cmd.exe interprets the first double quoted string as optional title for the console window. Therefore the command line
start "C:\Program Files (x86)\Mozilla Firefox\firefox.exe"
results just in opening a new console window with the window title:
C:\Program Files (x86)\Mozilla Firefox\firefox.exe
For that reason "" is specified as first START argument to define an empty title. Firefox is a GUI application. So no console window is opened which means an empty window title is really enough.
The parameter /max would not be really necessary, but the goal is to get Firefox into full screen mode after starting. So why not starting it already maximized?
32-bit version of Firefox is by default installed in directory %ProgramFiles% on 32-bit Windows and in %ProgramFiles(x86)% on 64-bit Windows. But it is possible during the installation to install Firefox into any other folder. But Firefox installer is well coded and registers firefox.exe in Windows registry under key:
HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\App Paths
This is recommended by Microsoft as written in MSDN article Application Registration.
The command START searches also in Windows registry under this key for an executable specified as argument without path as explained in answer on Where is “START” searching for executables?
This is the reason for using just firefox.exe on START command line because that starts an installed Firefox independent on installation location.
START displays an appropriate message box if firefox.exe could not be started and exits in this case with a return code greater 0 (9059 in my test on one computer).
The help output on running if /? in a command prompt window explains how to evaluate the exit code of a previous command or application without usage of immediate or delayed environment variable expansion and therefore working anywhere in a batch file from MS-DOS (really!) to currently latest Windows 10.
The command line if errorlevel 1 goto :EOF means IF start failed to start firefox.exe indicated by an exit code greater or equal 1 THEN exit execution of this batch file. For details on exiting batch file execution see answer on Where does GOTO :EOF return to?
2. Checking for running Firefox
The command TASKLIST being an external command, i.e. a console application in system directory of Windows, outputs a list of running processes. This list can be already filtered by TASKLIST itself for a specific process as done in batch file with /FI "IMAGENAME eq firefox.exe".
But TASKLIST is designed for just printing a list of processes. It is not designed for checking if a specific process is running and returning the result to the calling process via exit code. TASKLIST always exits with 0.
But an error message is output to handle STDERR on using a filter and no process can be found in process list matching this filter. For that reason 2>nul is used to suppress this error message by redirecting it to device NUL. Read the Microsoft article about Using Command Redirection Operators for more information about redirection.
A simple method to get a simple false/true respectively 0/1 result on checking for running Firefox is filtering output of TASKLIST with external command FIND which exits with 0 if the string to find was indeed found or with 1 if the searched string could not be found in the text read in this case from STDIN. The output of FIND is of no interest and therefore suppressed with redirection to device NUL using >nul.
Instead of using TASKLIST and FIND it is also possible to use QPROCESS:
%SystemRoot%\System32\qprocess.exe firefox.exe >nul 2>&1
QPROCESS exits with exit code 1 if firefox.exe could not be found in list of running processes. Otherwise the exit code is 0 on firefox.exe is running.
3. Evaluating Firefox process checking result
if not errorlevel 1 nircmd.exe sendkeypress F11 & goto :EOF
The IF command checks if exit code of FIND is NOT greater or equal 1 which means if exit code is lower than 1. Command FIND exits never with a negative value. So if this condition is true then it is time to execute nircmd.exe to send key press F11 to application in foreground hopefully being Firefox (not guaranteed by this code) and exit batch file processing.
Otherwise the batch file should wait once again 5 seconds and then do the check again. This can very easily result in an endless running batch file in case of started Firefox is immediately closed by the user before the 5 seconds wait timed out. For that reason it is counted how often the wait loop is already executed. After 6 loop runs, or 30 seconds, it is really time to no longer wait for Firefox and exit the batch file.
4. Getting more information about used commands
For understanding the used commands and how they work, open a command prompt window, execute there the following commands, and read entirely all help pages displayed for each command very carefully.
echo /?
find /?
if /?
qprocess /?
set /?
start /?
tasklist /?
timeout /?
And Single line with multiple commands using Windows batch file should be also read explaining operator & in addition to all other web pages referenced already above.
You can show a list of opened programs like this:
tasklist
To check if firefox exists:
EDIT: Code edited to show a fully working example
#echo off
start "C:\Program Files (x86)\Mozilla Firefox\firefox.exe"
goto :checkloop
:checkloop
tasklist|find "firefox.exe" > NUL
if %ERRORLEVEL% == 0 (
call :fullscreen
exit
) else (
call :timeout
goto :checkloop
)
:fullscreen
nircmd sendkeypress F11
goto :EOF
:timeout
timeout /t 5
goto :EOF

Batch file to uninstall a program

I'm trying to uninstall a program EXE via batch file and am not having any success.
The uninstall string found in the registry is as follows:
C:\PROGRA~1\Kofax\Capture\ACUnInst.exe /Workstation
C:\PROGRA~1\Kofax\Capture\UNWISE.EXE /U
C:\PROGRA~1\Kofax\Capture\INSTALL.LOG
If I run that from CMD or batch it does nothing.
If I run C:\PROGRA~1\Kofax\Capture\UNWISE.EXE /U from CMD it will open up a dialog box to point to the INSTALL.LOG file and then proceed to uninstall.
At the end, it will ask me to click finish.
I need this to be silent, can you point me in the right direction? This is on XP and 7.
Every program that properly installs itself according to Microsoft's guidelines makes a registry entry in either HKLM\Software\Microsoft\Windows\CurrentVersion\Uninstall (for machine installs) or HKCU\Software\Microsoft\Windows\CurrentVersion\Uninstall (for user profile installs). Usually, the key for the program will be its GUID, or else the name of the program. Within that key will be an entry called UninstallString. This contains the command to execute to uninstall the program.
If you already know ahead of time what you will be uninstalling, it should be easy enough to just put that in your batch file. It gets tricky when you try to automate that process though. You can use the reg command to get data from the registry, but it returns a lot of text around the actual value of a given key, making it hard to use. You may want to experiment with using VBscript or PowerShell, as they have better options for getting data from the registry into a variable.
This might help you further.....
How to Create a script via batch file that will uninstall a program if it was installed on windows 7 64-bit or 32-bit
I've had the same problem and this is what I came up with.
Before you start using this method though, you might wanna look up the name of the application on WMIC using CMD so..
First you wanna do: WMIC product > C:\Users\"currentuser"\Desktop\allapps.txt
I'd recommend to output the command to an TXT file because it's really confusing to read it in the Cmd prompt, plus is easier to find the data you are looking for.
Now what you wanna do is find the actual name of the app... If you look at the code I put in, the app name says SkypeT because skype has "™" in the end of it and the command prompt can't interpretate that as it is.
After you got the app name, just put in the find in the 4th line and substitute, a few lines which contain my examples with skype...
Also you can probably creat a variable called %APP% and not worry as much, but at it's current it works just fine...
One thing to note! with me the msi /quiet command did not work, the program would not install or uninstall so I used /passive, which lets the users see what's going on.
#Echo off
CD %cd%
:VerInstall
for /f "tokens=12,*" %%a in ('wmic product list system ^| Find /I "SkypeT"') do (
if Errorlevel = 0 (
Echo Skype is installed! )
if Errorlevel = 1 ( Echo Skype is not installed, proceding to the installation!
Ping localhost -n 7 >nul
goto :Reinstall )
)
:Status
tasklist /nh /fi "IMAGENAME eq "APP.exe" | find ":"> nul
if errorlevel = 1 goto :force
goto :Uninstall
:Force
echo We are killing the proccess... Please do not use the application during this process!
Ping localhost -n 7 > nul
taskkill /F /FI "STATUS eq RUNNING" /IM APP* /T
echo The task was killed with success! Uninstalling...
Ping localhost -n 7 > nul
:Uninstall
cls
for /f "tokens=12,*" %%a in ('wmic product list system ^| Find /I "SkypeT"') do (
set %%a=%%a: =%
msiexec.exe /x %%a /passive /norestart
)
:DoWhile
cls
Tasklist /fi "IMAGENAME eq msi*" /fi "STATUS eq RUNNING" | Find ":" >nul
if errorlevel = 1 (
echo Installation in progress
Goto :DoWhile
)
echo Skype is Uninstalled
:Reinstall
msiexec.exe /i SkypeSetup.msi /passive /norestart
:reinstallLoop
Tasklist /fi "IMAGENAME eq msi*" /fi "STATUS eq RUNNING" | Find ":" >nul
if errorlevel = 1 (
echo Installation in progress
goto :reinstallLoop
)
echo Skype is installed
:end
cls
color 0A
Echo Done!
exit
One last thing. I used this as an Invisible EXE task, so the user couldn't interact with the command prompt and eventually close the window (I know, I know, it makes the whole echoes stupid, but it was for testing purposes).for that I used BAT to EXE converter 2.3.1, you can put everything to work on the background and it will work very nicelly. if you want to show progress to users just write START Echo "info" and replace the info with whatever you want, it will open another prompt and show the info you need.
Remember, Wmic commands sometimes take up to 20 seconds to execute since it's querying the conputer's system, so it might look like it's doing nothing at first but it will run! ;)
Good luck :)
We needed a batch file to remove a program and we couldn't use programmatic access to the registry.
For us, we needed to remove a custom MSI with a unique name. This only works for installers that use msi or integrate such that their cached installer is placed in the Package_Cache folder. It also requires a unique, known name for the msi or exe. That said, it is useful for those cases.
dir/s/b/x "c:\programdata\packag~1\your-installer.msi" > removeIt.bat
set /p RemoveIt=< removeIt.bat
echo ^"%RemoveIt%^" /quiet /uninstall > removeIt.bat
removeIt.bat
This works by writing all paths for 'your-installer.msi' to the new file 'removeIt.bat'
It then assigns the first line of that bat file to the variable 'RemoveIt'
Next, it creates a new 'removeIt.bat' that contains the path/name of the .msi to remove along with the needed switches to do so.
Finally, it runs the batch file which executes the command to uninstall the msi. This could be done with an .exe as well.
You will probably want to place the 'removeIt.bat' file into a known writable location, for us that was the temp folder.

Resources