Cant start application using .bat file but can stop application - batch-file

I have a .bat file program like this
taskkill /f /im LearnBatV1.0.0.exe
timeout /t 1
start K:\POST\Govind\My Actual Work\LearnBat\LearnBatV1.0.0.exe
exit
LearnBatV1.0.0 is a simple application I created. I run the application and then I run the bat file. Then the bat file will execute the first two lines which will stop and close the application. But then when the third line tries to execut, it shows an error
K: \ POST \ Govind \ My Actual Work \ LearnBat \ LearnBatV1.0.0.exe could not be found. Make sure you typed the name correctly and try
again.
How is that it is correctly able to stop and close the application in the first line but not in the third line. The address is 100% correct. Then why is it giving an error. Kindly help me. Thank you.

I suggest using the following code:
#echo off
setlocal EnableExtensions DisableDelayedExpansion
set "LoopCount=6"
set "ForceKill="
:EndProgramLoop
%SystemRoot%\System32\tasklist.exe /NH /FI "IMAGENAME eq LearnBatV1.0.0.exe" | %SystemRoot%\System32\find.exe /I "LearnBatV1.0.0.exe" >nul || goto StartProgram
set /A LoopCount-=1
if %LoopCount% == 0 (
echo ERROR: Failed to terminate LearnBatV1.0.0.exe!
echo/
pause
goto EndBatch
)
if %LoopCount% == 1 set "ForceKill=/F "
%SystemRoot%\System32\taskkill.exe /IM LearnBatV1.0.0.exe %ForceKill%>nul 2>nul
%SystemRoot%\System32\timeout.exe /T 1 /NOBREAK >nul
goto EndProgramLoop
:StartProgram
start "" "K:\POST\Govind\My Actual Work\LearnBat\LearnBatV1.0.0.exe"
:EndBatch
endlocal
The batch file checks first if LearnBatV1.0.0.exe is running at all. It starts the executable if that is not the case.
The first argument string enclosed in " is interpreted as title string for the console window even if the started executable is a Windows GUI window and so no console window is opened at all. For that reason "" is used to define an empty title string. The fully qualified file name of the executable is enclosed in " as required because of the space character, too. I recommend to use a meaningful title string if the executable is a Windows GUI application.
I hope, your program is coded to work with any directory as current directory as the current directory for LearnBatV1.0.0.exe is defined by the process starting cmd.exe to process this batch file and can be any directory for that reason.
But if LearnBatV1.0.0.exe is really running, there is first decremented by one an environment variable counting how often the loop to end the program is executed already with leaving the loop with an error message if it is not possible to get LearnBatV1.0.0.exe either gracefully self-terminated or finally brutally killed by the operating system.
There is tried four times to send the WM_CLOSE message via TASKKILL to all the running processes LearnBatV1.0.0.exe which should result in a graceful self-termination of the executable on not being very bad coded. There is used finally the option /F to force a brutal kill of the process by the operating system as last attempt.
There is made a delay of one second between each TASKKILL and TASKLIST execution to give the process the time it perhaps needs to gracefully terminate itself.
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 /?
endlocal /?
find /?
goto /?
pause /?
set /?
setlocal /?
start /?
taskkill /?
tasklist /?
timeout /?
See also the Microsoft documentation about Using command redirection operators for an explanation of | and >nul and 2>nul and single line with multiple commands using Windows batch file for an explanation of conditional execution operator ||.

Related

How to run a command after a process was started by another process started by a batch file?

Does anybody know how to create a batch for starting an application, then setting process priority of another application to a lower priority than normal, next waiting until one more process is started, and finally setting process priority of this last started process to a higher priority than normal?
I would appreciate it if you would help me because this is for my business (Internet Cafe).
So I need the batch file to start Valorant (technically the Riot client on Valorant config). Then set Chrome process to low process priority after user logged in and sets Valorant (technically VALORANT-Win64-Shipping.exe) to high process priority.
Here are the commands required for the task.
The command that runs Valorant (Riot login client) on cmd.
"C:\Riot Games\Riot Client\RiotClientServices.exe" --launch-product=valorant --launch-patchline=live
The command that sets Chrome to low priority (and stops Chrome from taking whole CPU resources of my PC.)
wmic process where name="chrome.exe" call setpriority "64"
The command that sets Valorant (the game process) to high priority.
wmic process where name="VALORANT-Win64-Shipping" call setpriority "128"
Further please note this: After the login client started, the game process doesn't start right away. There must be code added that waits for the game process to start after executing the first command which is basically my problem here.
One more question:
Is this overclocking guide https://www.youtube.com/watch?v=dQw4w9WgXcQ true?
(I don't want my PC to explode and stuff.)
A commented batch file for this task could be:
#echo off
setlocal EnableExtensions DisableDelayedExpansion
rem Start Riot client as parallel running separate process.
start "" /D"C:\Riot Games\Riot Client" "C:\Riot Games\Riot Client\RiotClientServices.exe" --launch-product=valorant --launch-patchline=live
rem Define 120 seconds as maximum time for waiting for game process.
set RetryCount=120
rem In a loop wait one second, then look up in task list if the game process
rem is already running. If game process is running, exit the loop and change
rem the process priorities. Otherwise decrement the retry counter and exit
rem the loop on reaching value zero with informing the batch file user that
rem game process was not started within two minutes.
:WaitLoop
%SystemRoot%\System32\timeout.exe /T 1 /NOBREAK >nul
%SystemRoot%\System32\tasklist.exe /FI "IMAGENAME eq VALORANT-Win64-Shipping.exe" /NH 2>nul | %SystemRoot%\System32\find.exe /C /I "VALORANT-Win64-Shipping" >nul
if not errorlevel 1 goto GameStarted
set /A RetryCount-=1
if not %RetryCount% == 0 goto WaitLoop
echo Valorant game was not started within two minutes.
echo/
pause
goto EndBatch
:GameStarted
%SystemRoot%\System32\wbem\wmic.exe PROCESS where name="chrome.exe" CALL SetPriority 64 >nul
%SystemRoot%\System32\wbem\wmic.exe PROCESS where name="VALORANT-Win64-Shipping.exe" CALL SetPriority 128 >nul
:EndBatch
endlocal
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 /?
endlocal /?
find /?
goto /?
if /?
pause /?
rem /?
set /?
setlocal /?
start /?
tasklist /?
timeout /?
wmic /?
wmic process /?
wmic process call /?
wmic process call setpriority /?
See also:
DosTips forum topic: ECHO. FAILS to give text or blank line - Instead use ECHO/
Microsoft documentation about Using command redirection operators for an explanation of >nul and 2>nul and |.

How to write all files found in one directory into one command line for calling an executable?

I have a directory with a bunch of files with a mix of extensions. I only want to work with files with extension *.abc. Each *.abc file should then be handed over to another software with some parameters. The parameters are always the same for each file. One of the parameters needs to be defined by the user, though.
So my first try was this:
#ECHO OFF
set /p value="Enter required imput value: "
for %%f in (*.abc) do (
START C:\"Program Files"\Software\startsoftware.exe -parameter1 "%%~nf.abc" -parameter2 %value% -parameter3
)
PAUSE
The script works but is causing a memory crash, as the software is getting all request basically at once.
However, if I could manage to write all file names in one command line the software would process all files one by one. It needs to be called like this:
START C:\"Program Files"\Software\startsoftware.exe -parameter1 file1.abc -parameter2 %value% -parameter3 -parameter1 file2.abc -parameter2 %value% -parameter3 -parameter1 file3.abc -parameter2 %value% -parameter3 -parameter1 file4.abc -parameter2 %value% -parameter3
My idea was to generate a files.txt with listing all *.abc using:
dir /b /a-d > files.txt
Then read that list into my command. However, I don't know how to read out the files.txt and apply parameters including the variable %value% to each file.
1. Quote inside an argument string
" inside an argument string is usually not correct. The entire argument string must be usually enclosed in double quotes and not just parts of it. So wrong is C:\"Program Files"\Software\startsoftware.exe and correct would be "C:\Program Files\Software\startsoftware.exe".
That can be seen by opening a command prompt, typing C:\Prog and hitting key TAB to let Windows command processor complete the path to "C:\Program Files". The Windows command processor added automatically the required double quotes around entire path string. The path would change to "C:\Program Files (x86)" on pressing once more key TAB. However, continue typing with "C:\Program Files" displayed by entering \soft and press again TAB and displayed is "C:\Program Files\Software". The second " moved to end of new path. Type next \start and press once more TAB. Now is displayed "C:\Program Files\Software\startsoftware.exe" which is the correct fully qualified file name of this executable enclosed in double quotes as required because of the space character in path.
For more information about this feature of Windows command processor run in command prompt window cmd /? and read the output help from top of first page to bottom of last page.
2. START and TITLE string
The help for command START is output on running start /? in a command prompt window.
START interprets the first double quoted string as optional title string for the console window. For that reason it is advisable to specify first after command name START always a title in double quotes. In case of a Windows GUI application is started on which no console window is opened at all or a console application is executed in background without opening a new console window, the title string can be specified with just "" after START which is just an empty title string.
3. Running applications parallel
The command START is used to run an application or script parallel to the Windows command process which is processing the batch file. This is often useful, but definitely not here on which an application should be executed to process a file of a large set of files which need to be processed all.
The following command line would start for each *.abc file the executable startsoftware.exe for execution parallel to cmd.exe which is processing the batch file.
for %%f in (*.abc) do START "" "C:\Program Files\Software\startsoftware.exe" -parameter1 "%%~nf.abc" -parameter2 %value% -parameter3
This results with many *.abc files in current directory in a situation on which Windows fails to run one more process due to a resource problem as too many processes are running already more or less parallel.
4. Running application in series
It is usually better on processing many files to run an application for processing a file and halt processing of the batch file until the application finished and terminated itself. That can be achieved by not using the command START.
#echo off
setlocal EnableExtensions DisableDelayedExpansion
if not exist *.abc (
echo ERROR: There are no *.abc in folder: "%CD%"
echo/
pause
goto :EOF
)
set "Value="
:UserPrompt
set /P "Value=Enter required input value: "
if not defined Value goto UserPrompt
set "Value=%Value:"=%"
if not defined Value goto UserPrompt
for %%I in (*.abc) do "C:\Program Files\Software\startsoftware.exe" -parameter1 "%%I" -parameter2 "%Value%" -parameter3
endlocal
The behavior on starting an executable from within a batch file is different to doing that from within a command prompt window. The Windows command processor waits for the self-termination of the started executable on being started during processing of a batch file. Therefore this code runs always just one instance of startsoftware.exe in comparison to the loop above using command START to start multiple instances quickly in a short time.
5. Running application with multiple files
It looks like it is possible to run startsoftware.exe with multiple arguments to process several files at once. But the maximum command line length limit of 8191 characters must be taken into account on writing a batch file which runs the executable with a list of arguments to process multiple files at once.
#echo off
setlocal EnableExtensions DisableDelayedExpansion
if not exist *.abc (
echo ERROR: There are no *.abc in folder: "%CD%"
echo/
pause
goto :EOF
)
set "Value="
:UserPrompt
set /P "Value=Enter required input value: "
if not defined Value goto UserPrompt
set "Value=%Value:"=%"
if not defined Value goto UserPrompt
set "Arguments="
set "CmdLineLimit="
for /F "eol=| delims=" %%I in ('dir *.abc /A-D /B 2^>nul') do call :AppendFile "%%I"
if defined Arguments "C:\Program Files\Software\startsoftware.exe"%Arguments%
goto :EOF
:AppendFile
set Arguments=%Arguments% -parameter1 %1 -parameter2 "%Value%" -parameter3
set "CmdLineLimit=%Arguments:~7800,1%"
if not defined CmdLineLimit goto :EOF
"C:\Program Files\Software\startsoftware.exe"%Arguments%
set "Arguments="
set "CmdLineLimit="
goto :EOF
The loop for %%f in (*.abc) do is modified in this code to a for /F loop to get first a list of file names loaded completely into memory instead of processing the directory entries which could change on each execution of startsoftware.exe if it modifies the *.abc files in current directory.
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 /?
dir /?
echo /?
for /?
goto /?
if /?
pause /?
set /?
setlocal /?
See also Where does GOTO :EOF return to?

.BAT file keeps opening unlimited instances after Windows Update

So this bat file was running perfectly right before this latest windows update.
#Echo off
:Start
Start E:\directoryhere?listen -dedicated
echo Press Ctrl-C if you don't want to restart automatically
ping -n 10 localhost
goto Start
So this would start a dedicated server. A command prompt would pop up. When everyone left the server or the game finished, the command prompt would close then the .bat file would reopen it. Now after this update, the .bat file just keeps opening the cmd prompt while its open. So i'll have instantly 20 instances open at once and my cpu is at 100%.
I've also had this code before the windows update before this one which ended up doing the same thing.
#echo off
cd "E:\directoryhere\"
:loop
Start RxGame-Win64-Test.exe server lv_canyon?listen -dedicated | set /P "="
goto loop
That code used to work, but 2 window updates before ended up doing the same thing. It would just keep opening instances and make my cpu 100%.
What's a way to make sure to see if the cmd prompt is open and not to reopen it and keep it running until the cmd prompt closes then reopen it.
A simple fix to this can to check is the process already is open first using tasklist. Please make sure you search what your actual application is called. For this example I'm going to guess it's called RxGame-Win64-Test.exe. Bellow are a few script options.
This script bellow will check to see if the RxGame-Win64-Test.exe app is open first before starting another one:
#ECHO OFF
#SETLOCAL enabledelayedexpansion
GOTO LOOP
:LOOP
Rem | Check If Window Is Open
tasklist /FI "IMAGENAME eq RxGame-Win64-Test.exe" 2>NUL | find /I /N "RxGame-Win64-Test.exe">NUL
if not "%ERRORLEVEL%"=="0" (
Rem | Process Not Found
timeout /T 10 /NOBREAK
Rem | Restart Server
start "" "RxGame-Win64-Test.exe server lv_canyon?listen -dedicated"
Rem | GOTO LOOP
GOTO LOOP
)
GOTO LOOP
Not sure if the RxGame-Win64-Test.exe is CMD based program or not but if it is the script bellow will help you:
#ECHO OFF
#SETLOCAL enabledelayedexpansion
Rem | First Load, Start Server
start "DedicatedServerLauncher" cmd /c "RxGame-Win64-Test.exe server lv_canyon?listen -dedicated"
GOTO LOOP
:LOOP
Rem | Reset PID
Set "PID="
Rem | Grab The Current Window PID
FOR /F "tokens=2" %%# in ('tasklist /v ^| find "DedicatedServerLauncher" ^| find "Console"') do set PID=%%#
Rem | Check If Window Is Open
if "!PID!"=="" (
Rem | Process Not Found
timeout /T 10 /NOBREAK
Rem | Restart Server
start "DedicatedServerLauncher" cmd /c "RxGame-Win64-Test.exe server lv_canyon?listen -dedicated"
Rem | GOTO LOOP
GOTO LOOP
)
GOTO LOOP
For help on any of the commands do the following:
call /?
set /?
for /?
if /?
find /?
So on.

Batch script to find if program is not responding and then start another application else exit batch job

I want a batch script that checks if the program is in running or not responding state. If it is in running state exit the batch script, else kill the program start the other application.
I tried using the following code but it is executing opening application even though the program is in running state. Please help me in finding a solution
#echo off
TASKLIST/IM jusched.exe /FI "STATUS eq NOT RESPONDING">nul /T /F && start "" notepad.exe
You appear to be mixing up the TaskKill and TaskList syntax. (Enter TaskList/? and TaskKill/? at the command prompt for usage information). Also I think TaskList output is always successful so it would probably need to be checked using something which does register if unsuccessful, e.g. Find.exe.
Here is a basic step by step example for you.
#Echo Off
Rem Setting name of target process
Set "TP=jusched.exe"
Rem Setting name of new process
Set "NP=notepad.exe"
Rem Setting TaskList filters to reduce line length
Set "F1=ImageName eq %TP%"
Set "F2=Status eq Not Responding"
Rem Check target process status and exit if no match
TaskList /FI "%F1" /FI "%F2%" /NH|Find /I "%TP%">Nul||Exit/B
Rem Kill unresponsive process and wait a little
TaskKill /IM "%TP%" /T /F>Nul 2>&1&&Timeout 3 /NoBreak>Nul
Rem Open new process
Start "" "%NP%"

My Batch file loop stops because of open file

I am trying to build a batch file that pings multiple devices on our network and continues logging ping results data in an output file in an infinite loop. However, the infinite loop gets hung up because the output file is open. Once I manually close the output file, the loop begins another iteration and logs more data. How do I automate this step? I've gone through so many options with taskkill, but none of them will close the output file for some reason. Other Notepad files close, but not the output file running on notepad.
Thanks for you help! Code is below:
#echo off
if exist C:\Users\Tsgadmin\Desktop\data\computers.txt goto Label1
echo.
echo Cannot find C:\Users\Tsgadmin\Desktop\data\computers.txt
echo.
Pause
goto :eof
:Label1
:loop
echo ================================================= >> C:\Users\Tsgadmin\Desktop\ping_firepanels_output.txt
echo PingTest executed on %date% at %time% >> C:\Users\Tsgadmin\Desktop\ping_firepanels_output.txt
for /f %%i in (C:\Users\Tsgadmin\Desktop\data\computers.txt) do call :Sub %%i
notepad C:\Users\Tsgadmin\Desktop\ping_firepanels_output.txt
choice /n/t:c,<10>/c:cc
echo ================================================= >> C:\Users\Tsgadmin\Desktop\ping_firepanels_output.txt
echo. >> C:\Users\Tsgadmin\Desktop\ping_firepanels_output.txt
start notepad.exe
for /f "tokens=2" %%x in ('tasklist ^| findstr notepad.exe') do set PIDTOKILL=%%x
taskkill /F /IM notepad.exe > nul
goto loop
goto :eof
:Sub
echo Testing %1
ping -n 1 %1 >> C:\Users\Tsgadmin\Desktop\ping_firepanels_output.txt | find /i "(0% loss)"
echo %1 Testing done
echo %1 Testing done >> C:\Users\Tsgadmin\Desktop\ping_firepanels_output.txt
Here is your batch code rewritten for this task:
#echo off
setlocal EnableExtensions DisableDelayedExpansion
set "LogFile=%USERPROFILE%\Desktop\ping_firepanels_output.txt"
set "ListFile=%USERPROFILE%\Desktop\data\computers.txt"
if exist "%ListFile%" goto PrepareForPings
echo/
echo Cannot find file: "%ListFile%"
echo/
endlocal
pause
goto :EOF
rem Delete existing log file before running the echo requests.
rem Get just file name with file extension without path from
rem log file name with path specified at top of the batch file.
:PrepareForPings
del "%LogFile%" 2>nul
for /F %%I in ("%LogFile%") do set "LogFileName=%%~nxI"
rem Always terminate (not kill) running Notepad instance with having
rem the log file opened for viewing before running first/next test run.
:PingLoop
%SystemRoot%\System32\taskkill.exe /FI "WINDOWTITLE eq %LogFileName% - Notepad" >nul 2>nul
echo =================================================>>"%LogFile%"
>>"%LogFile%" echo PingTest executed on %DATE% at %TIME%
echo/>>"%LogFile%"
for /F "usebackq" %%I in ("%ListFile%") do (
echo Testing %%I ...
%SystemRoot%\System32\ping.exe -n 1 -w 500 %%I>nul
if errorlevel 1 (
echo %%I is not available in network (no reply^).>>"%LogFile%"
) else echo %%I is available.>>"%LogFile%"
echo %%I testing done.
)
echo =================================================>>"%LogFile%"
echo/>>"%LogFile%"
start "" %SystemRoot%\notepad.exe "%LogFile%"
echo/
%SystemRoot%\System32\choice.exe /C NY /N /T 10 /D Y /M "Run again (Y/n): "
echo/
if errorlevel 2 goto PingLoop
endlocal
In general it is advisable to define environment variables with names of files specified multiple times in the batch file at top to make it easier to modify them in future.
On referencing those file environment variables it is strongly recommended to enclose the name in double quotes to get a working batch file also when file name with path contains a space character or one of these characters: &()[]{}^=;!'+,`~
If a file name enclosed in double quotes is specified as text file of which lines to read in a for /F command line, it is necessary to use option usebackq to get interpreted the file name enclosed in double quotes as file name and not as string to process by FOR.
The DosTips forum topic ECHO. FAILS to give text or blank line - Instead use ECHO/ explains why it is better to use echo/ instead of echo. to output an empty line.
The TASKKILL command used to send Notepad the terminate signal for a graceful termination should be send only to the Notepad instance having the log file opened and not any other perhaps running Notepad instance.
An ECHO line redirected to a file with > or >> with a space left to redirection operator results in having this space also written as trailing space into the file. For that reason there should be no space between text to write into the file and redirection operator. A space right to > or >> would be no problem as not written into the file.
When a variable text is output on an ECHO line redirected into a file which could end with 1, 2, 3, ... 9, it is necessary to specify the redirection from STDOUT into the file with >> at beginning of the line as otherwise 1>>, 2>>, ... would be interpreted different as expected on execution of the ECHO command line. Read also the Microsoft article about Using Command Redirection Operators.
There is no subroutine necessary for this task. A command block starting with opening parenthesis ( and matching ) can be used here too. That makes the execution of the loop a bit faster, not really noticeable faster, but nevertheless faster.
There is a text written with echo into the log file containing also a closing parenthesis ) not within a double quoted string. This ) would be interpreted as matching ) for opening ( of true branch of IF condition. It is necessary to escape ) with caret character ^ to get ) interpreted as literal character by Windows command interpreter.
PING exits with exit code 1 if the echo request was not replied. Otherwise on successful reply the exit code is 0. It is better to evaluate the exit code via errorlevel than filtering the language dependent output.
New instance of Notepad with the log file to view is started by this batch file using command start to run Notepad in a separate process running parallel to command process executing the batch file. Otherwise the execution of the batch file would be halted as long as the started Notepad instance is not closed by the user. That different behavior can be easily seen on removing start "" at beginning of the command line starting Notepad.
The command CHOICE gives the user of the batch file the possibility to exit the loop by pressing key N (case-insensitive) within 10 seconds. Otherwise the user prompt is automatically answered with choice Y and the loop is executed once again by first terminating running Notepad.
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.
choice /?
del /?
echo /?
endlocal /?
for /?
goto /?
if /?
pause /?
ping /?
set /?
setlocal /?
start /?
taskkill /?
See also Windows Environment Variables for details on environment variables USERPROFILE and SystemRoot as used in this batch file.

Resources