set loop to open the following process on batch file scripting - windows

in my batch script,
tasklist /nh /fi "imagename eq udp-receiver.exe" | find /i "udp-receiver.exe" > 2 || (start c:\udp-receiver.exe -f 1.zip --nosync --interface 00-00-ab-00-00-CD --portbase 989)
(start d:udp-receiver.exe -f 1.zip --nosync --interface 00-00-ab-00-00-CF --portbase 989)
to open 2 session for udp recieve. I am require to use a loop to reopen the either 2 seesion if it close. how do i write the loop in batch file?

find /i "udp-receiver.exe" > 2
is incorrect. > is a redirection operator (output of the "find" will be redirected to the file "2").
If you want to count the number of lines containing a string, then you need to apply the /c switch to the find command.
for /f %%a in ('
tasklist /nh /fi "imagename eq udp-receiver.exe" ^| find /i /c "udp-receiver.exe"'
) do if %%a gtr 2 (echo more than 2) else (echo 2 or fewer)
may give you the results you seek.

Related

Start a program from Batch while preventing duplicates

I am starting a program from Batch, but if the program is already running, I want to avoid starting a second instance.
So far, I have crafted the following code, which seems to work:
TASKLIST /FI "IMAGENAME eq speedfan.exe" | FIND "speedfan.exe" >NUL
IF %ERRORLEVEL%==0 (
TASKKILL /F /IM speedfan.exe
)
START "" "C:\Program Files (x86)\SpeedFan\speedfan.exe"
Alternatively, if I want to keep the current instance instead of starting a new one:
TASKLIST /FI "IMAGENAME eq speedfan.exe" | FIND "speedfan.exe" >NUL
IF NOT %ERRORLEVEL%==0 (
START "" "C:\Program Files (x86)\SpeedFan\speedfan.exe"
)
Can this be improved/simplified?
Update: Thank you all for your comments! So far, my revised code is becoming:
TASKLIST /FI "IMAGENAME eq speedfan.exe" | FINDSTR /BLI "speedfan.exe " >NUL || (
START "" "C:\Program Files (x86)\SpeedFan\speedfan.exe"
)
(and maybe I'll drop the /FI "IMAGENAME eq speedfan.exe" part for the sake of simplicity)
Here's a quick example intended to request input confirmation to close it, if it is running, or to just open it if isn't running. I hope it is robust enough for your purposes.
#"%__AppDir__%tasklist.exe" /Fi "ImageName Eq speedfan.exe" /Fo CSV /NH^
| "%__AppDir__%find.exe" ":" > NUL && (
Start "" "C:\Program Files (x86)\SpeedFan\speedfan.exe") || (
"%__AppDir__%choice.exe" /M "Would you like to close SpeedFan"
If Not ErrorLevel 2 "%__AppDir__%taskkill.exe" /Im speedfan.exe /T > NUL)
I have split the long first line over two for tidiness, and because you don't particularly like long lines.

Batch File which checks for another Batch File process

so google didn't help me at all i need to ask here again.
I use this kind of method to check if my servers are running in 2 batch files.
tasklist /FI "IMAGENAME eq server_64.exe" 2> nul | find "server_64.exe" > nul
IF ERRORLEVEL == 1 (
echo Server is not running
echo.
) else (
echo Stopping Server ...
echo.
taskkill /F /IM server_64.exe > nul 2>&1
)
One to start and one to stop the servers.
Well this works great but when it comes to batch files it wont work for me...
I have one server which runs on phyton so start it via batch file.
My question is, is there a way to get somehow the batch file process status and stop it like it works for exe?
I hope i explained it good enough.
Thx in advance! :)
You can try it with a batch file like this :
#echo off
set "Process=server_64.exe"
Title Checking for status of this process ===^> "%Process%"
tasklist /nh /fi "imagename eq %Process%" 2>nul |find /i "%Process%" >nul
IF '%ERRORLEVEL%' EQU '1' (
Color 0B
echo.
echo "%Process%" is not running
) else (
Color 0C
echo.
echo Stopping "%Process%" ...
taskkill /F /IM "%Process%" > nul 2>&1
)
pause
Omg i found the solution, this was a beast...
tasklist /fi "imagename eq cmd.exe" /v /fo table /nh | find /i "Broker" 2>nul
but what is starmnge is that i cant get the output to be silnce...
when i try to mute it it gives me always error level 1.
tasklist /fi "imagename eq cmd.exe" /v /fo table /nh 2>nul | find /i "Broker" 2>nul
so whats wrong with this? ^

how do I kill all cmd.exe except the one currently running from batch?

The past few days I have been working on a script that I thought would be rather easy but it seems not, and I do understand why. My problem is how to get around it.
The batch script I need explained:
I have a script that runs in cmd.exe that does a bunch of things like moving a huge amount of files from a location to another. Lets call it
movefile.cmd. This script works, but happens to stop sometimes (very rarely - lets not go into why and that script). Its important that this script always runs, so my idea here was to create a batch that exits cmd.exe and then re-opens the script each hour or so. Lets call this script restartcmd.bat
Sounds perfectly easy as I could do this:
#echo off
:loop
start c:\script\movefile.cmd
Timeout /nobreak /t 3600
Taskkill cmd.exe
goto loop
But obviously this doesn't work because my new script also runs in cmd.exe, so it would kill this process as well.
What I've tried:
So I made a copy of cmd.exe and renamed it into dontkillthis.exe. I run dontkillthis.exe and then open the restardcmd.bat from dontkillthis.exe - this works perfectly! But I need to be able to just dobbleclick my script instead of doing that. Why? Because its supposed to be as easy as possible and I want my restartcmd.bat to be in my startup folder.
I've been looking at the ideas of getting the exact process ID of cmd.exe and shutting that so that my dontkillthis.exe will remain, but I can't seem to nail it. Tried all thats written in here how to kill all batch files except the one currently running , but I can't get it to work.
I'm not sure if I'm being confused or if it actually is a bit hard to do this.
I'd really appreciate some help here.
Best Regards
MO
first you'll need the PID of the current CMD instance. The topic has been discussed here . I will offer you my solution - getCmdPID.bat
and here's the script (getCmdPID should in the same directory ):
#echo off
call getCmdPID
set "current_pid=%errorlevel%"
for /f "skip=3 tokens=2 delims= " %%a in ('tasklist /fi "imagename eq cmd.exe"') do (
if "%%a" neq "%current_pid%" (
TASKKILL /PID %%a /f >nul 2>nul
)
)
Normally with the following command I should be able to find the PID. Unfortunately this is not the case.
title exclude &tasklist /NH /v /fo csv /FI "WINDOWTITLE ne exclude*" /FI "IMAGENAME eq cmd.exe" /FI "STATUS eq running"
So to achieve my goal, I used the following command:
FIND /I "exclude" 1>NUL
#echo off
TITLE exclude
(for /f "usebackq tokens=*" %%a in (`tasklist /NH /v /fo csv /FI "IMAGENAME eq cmd.exe" /FI "STATUS eq running"`) do (
(
echo %%a | FIND /I "exclude" 1>NUL
) || (
for /f "usebackq tokens=2 delims=," %%i in (`echo %%a`) do (
echo TASKKILL /PID %%~i /f
)
)
)
)>_output-taskill.txt
TYPE _output-taskill.txt
Another approach to kill all the processes in a single line is to use filters on the command taskkill with filters should look like:
TASKKILL /F /FI "PID ne XXXX" /FI "IMAGENAME eq cmd.exe" /IM cmd.exe
eq (equal)
ne (not equal)
gt (greater than)
lt (lesser than)
#echo off
TITLE exclude
(for /f "usebackq tokens=2 delims=," %%a in (`tasklist /NH /v /fo csv /FI "IMAGENAME eq cmd.exe" /FI "STATUS eq running" ^| FIND /I "exclude"`) do (
echo TASKKILL /F /FI "PID ne %%~a" /FI "IMAGENAME eq cmd.exe" /IM cmd.exe
)
)>_output-taskill.txt
TYPE _output-taskill.txt
I have found a solution that utilizes text files to keep track of all previous PIDs the bat file has had. It attempts to kill them silently and then adds the current PID to the list after.
If you don't want it to kill the old, already existing process, simply replace the line that has "taskkill" with whatever you were wanting to do with it.
(might require you to run as admin in order to have permissions to kill the duplicate process. see permission elevation code below for optional implementation if you don't want to have to run as admin every time.)
#echo off
set WorkingDir=%cd%
if exist MostRecentPID.txt ( del "PIDinfo.txt" /f /q ) > nul
cd ..\..\..\..\..\..\..
title mycmd
tasklist /v /fo csv | findstr /i "mycmd" > %WorkingDir%\PIDinfo.txt
set /p PIDinfo=<%WorkingDir%\PIDinfo.txt
REM below, the 11 means get substring starting a position 11 with length of 5 characters. The tasklist command gives a long and verbose value so this will get just the PID part of the string.
set PID5chars=%PIDinfo:~11,5%
set PID4chars=%PIDinfo:~11,4%
if exist PreviousPIDs.txt (
for /F "tokens=*" %%A in (PreviousPIDs.txt) do taskkill.exe /F /T /PID %%A > nul 2>&1
goto CheckIfFourCharPID
)
:CheckIfFourCharPID
if %PID4chars% gtr 8100 (
for /F "tokens=*" %%A in (PreviousPIDs.txt) do taskkill.exe /F /T /PID %%A > nul 2>&1
echo %PID4chars% >> "PreviousPIDs.txt"
) else (
echo %PID5chars% >> "PreviousPIDs.txt"
)
Explanation: (warning: very technical)
-This solution gets a substring of the tasklist command to get just the PID. There will not be a PID for cmd.exe that is greater than 18100 so check if PID4chars is greater than 8100 so we know if it's a 4 digit or 5 digit number
case 1: a 5 digit PID like 17504 has a PID5chars val 17504 and a PID4chars val of 1750, so we add PID5chars to the text files of PIDs to kill
case 2: a 4 digit PID like 8205 has a PID5chars val of 8205" and a PID4chars val of 8205, so we add PID4chars to the text files of PIDs to kill
case 3: a 4 digit PID like 4352 has a PID5chars val of 4352" and a PID4chars val of 4352, so we add PID4chars to the text files of PIDs to kill
OPTIONAL PERMISSION ELEVATION CODE
(put this at the top of your bat file and it will auto-run it as admin.)
#echo off
setlocal DisableDelayedExpansion
set "batchPath=%~0"
for %%k in (%0) do set batchName=%%~nk
cd ..\..\..\..\..\..\..\..
if exist %cd%\Temp (
set temp=%cd%\Temp
goto vbsGetPrivileges
)
if exist %cd%\Windows\Temp (
set temp=%cd%\Windows\Temp
goto vbsGetPrivileges
)
set temp=%cd%
:vbsGetPrivileges
set "vbsGetPrivileges=%temp%\OEgetPriv_%batchName%.vbs"
setlocal EnableDelayedExpansion
:CheckIfRunningAsAdmin
net session >nul 2>&1
if %ERRORLEVEL% == 0 (
goto gotPrivileges
) else ( goto ElevatePermissions )
:ElevatePermissions
if '%1'=='ELEV' (echo ELEV & shift /1 & goto gotPrivileges)
ECHO Set UAC = CreateObject^("Shell.Application"^) > "%vbsGetPrivileges%"
ECHO args = "ELEV " >> "%vbsGetPrivileges%"
ECHO For Each strArg in WScript.Arguments >> "%vbsGetPrivileges%"
ECHO args = args ^& strArg ^& " " >> "%vbsGetPrivileges%"
ECHO Next >> "%vbsGetPrivileges%"
ECHO UAC.ShellExecute "!batchPath!", args, "", "runas", 1 >> "%vbsGetPrivileges%"
"%SystemRoot%\System32\WScript.exe" "%vbsGetPrivileges%" %*
exit /B
:gotPrivileges
setlocal & pushd .
cd /d %~dp0
if '%1'=='ELEV' (del "%vbsGetPrivileges%" 1>nul 2>nul & shift /1)
net session >nul 2>&1
if %ERRORLEVEL% == 0 (
goto Continue
) else (
REM unable to elevate permissions so tell user to run file as admin manually
echo Please re-run this file as administrator. Press any key to exit...
pause > nul
goto Exit
)
:Continue
<insert rest of code here>
It would be much better to get the PID of your movefile.cmd. If you can edit it, add a title MyMoveFileProcess and get it's PID with
for /f "tokens=2" %%i in ('tasklist /v ^|find "MyMoveFileProcess"') do set PID=%%i
Then you can kill it with taskkill /pid %pid%
Instead of changing your movefile.cmd, you can also just start it with an title:
start "MyMoveFileProcess" c:\script\movefile.cmd
A couple of lines will help you achieve this:
TITLE exclude
taskkill /IM cmd.exe /FI "WINDOWTITLE ne exclude*"

Tasklist doesn't have access to a certain process

I made a batch file with the following script:
#echo off
goto start
:start
"C:\Games\SV_Debug\Data\Win32\InvisibleM2.vbs"
goto check
:check
tasklist /FI "IMAGENAME eq Launcher2.exe" >swap | find /I /N "Launcher2.exe" >swap
if "%ERRORLEVEL%" == "0" (
goto waitrecheck
) else "%ERRORLEVEL%" (
goto start
)
:waitrecheck
ping 127.0.0.1 -n 3
goto check
This batch file is executed by a vbscript that make's this batch invisible.
The batch file runs a vbscript that runs Launcher2.exe normal and not invisible.
But this batch above here can't check is Launcher2.exe is running.
When it tries I get this error:
The process does not have access to the file because it's being used by another program.
How do I fix this?
tasklist /FI "IMAGENAME eq Launcher2.exe" >swap | find /I /N "Launcher2.exe" >swap
You can not send the output of two programs to the same file at the same time
tasklist /FI "IMAGENAME eq Launcher2.exe" | find /I /N "Launcher2.exe" >nul

How to count amount of processes with identical name currently running, using a batchfile

I would like to use a batch file to compare the number of processes named "standard.exe", that are running on my Windows 7 machine, with the number of processes named "basic.exe". If the amount of processes called "standard.exe" equals the amount of processes called "basic.exe" nothing should happen, if the numbers are unequal, basic.exe should be restarted.
Any ideas? Already found the following code to check whether a process is running, but now I would like to count the number of processes carrying the same name.
tasklist /FI "IMAGENAME eq myapp.exe" 2>NUL | find /I /N "myapp.exe">NUL
if "%ERRORLEVEL%"=="0" echo Programm is running
Thanks in advance!
Using your example simply replace the /N in find with /C to return the count of processes.
tasklist /FI "IMAGENAME eq myapp.exe" 2>NUL | find /I /C "myapp.exe"
Then you can just reduce it down to :
tasklist | find /I /C "myapp.exe"
Although as Andriy M points out it will match both myapp.exe and notmyapp.exe.
As for the second part of your question, simply do this:
set a=tasklist /FI "IMAGENAME eq myapp.exe" 2>NUL | find /I /C "myapp.exe"
set b=tasklist /FI "IMAGENAME eq myapp2.exe" 2>NUL | find /I /C "myapp2.exe"
if not a==b do (
stuff
)
If you don't want to write a file, replace the tasklist and set var1 commands with
for /f "tokens=1,*" %%a in ('tasklist ^| find /I /C "standard.exe"') do set var1=%%a
same for the second ones.
for /f "tokens=1,*" %%a in ('tasklist ^| find /I /C "basic.exe"') do set var2=%%a
There is probably a neater way to do it, but the following code seems to do the trick:
:begin
tasklist | find /I /C "standard.exe">D:\tmpfile1.txt
tasklist | find /I /C "basic.exe">D:\tmpfile2.txt
set /p var1= <D:\tmpfile1.txt
set /p var2= <D:\tmpfile2.txt
if %var1% LSS %var2% goto restart
if %var1% EQU %var2% goto wait
:wait
echo waiting..
ping -n 300 127.0.0.1 > nul
goto begin
:restart
echo error has occured, all processes will be restarted
taskkill /f /im standard.exe
taskkill /f /im basic.exe
ping -n 30 127.0.0.1 > nul
goto begin
Cheers!

Resources