How do I make this loop "check Tasklist" correct - loops

I wanna make a loop that checks in tasklist if program1.exe, program2.exe, etc. is running and if not use the specified program path to run it.
But I have hit a mental break down wall my small programming Iq simply can't figure out how to solve it.
`:Program1
(set program=%ProgramPath1%)
(set MyProcess=program.exe)
goto :CheckIfRunning
:Program2
(set program=%ProgramPath2%)
(set MyProcess=program.exe)
goto :CheckIfRunning
:CheckIfRunning
tasklist /NH /FI "imagename eq %MyProcess%" 2>nul |find /i "%MyProcess%">nul
If not errorlevel 1 GOTO :b else :a
:a
start "" "%program%"
GOTO :done
:b
echo %MyProcess% is running
:done
pause
eof`
I know this is pittyfull but I am trying my best, so please bare with me

Related

How to check if multiple processes is running via a batch script

I got this script form stackoverflow and its working for me . and because i can't comment there im asking my question in new post.
This script check if exe is running in tasklist:
#echo off
SETLOCAL EnableExtensions
set EXE=notepad.exe
FOR /F %%x IN ('tasklist /NH /FI "IMAGENAME eq %EXE%"') DO IF %%x == %EXE% goto ProcessFound
goto ProcessNotFound
:ProcessFound
echo %EXE% is running
goto END
:ProcessNotFound
echo %EXE% is not running
goto END
:END
echo Finished!
The question is :
How can I check multiple process is running on tasklist?
for example exe1 and exe2
thanks in advance
From your comments; if all you want to do is run a third executable if neither of two other executables are running then here is a single line complete batch file example for you:
#TaskList/NH /FI "Status Eq Running"|FindStr/IC:"first.exe" /C:"second.exe">Nul||Start "" "X:\PathTo\third.exe"
Note:Do not change anything other than the names first, second and X:\PathTo\third; all double quotes, ", are necessary!
I've organised your code a bit differently so it's easier to follow and has more functionality. Note: This means it will be slower if you have lots of processes. If you wish to only see if it exists, I'd recommend using findstr.
I've added REM (batch-file equivalent for comments) explaining what each section does.
#echo off
REM Create variable's for exe's and their counter
set exe_1=notepad.exe
set exe_2=explorer.exe
set exe_3=chrome.exe
set "count_1=0"
set "count_2=0"
set "count_3=0"
REM Store all tasklist findings in a temp file
>tasklist.temp (
tasklist /NH /FI "IMAGENAME eq %exe_1%"
tasklist /NH /FI "IMAGENAME eq %exe_2%"
tasklist /NH /FI "IMAGENAME eq %exe_3%"
)
REM Go through all finds and count for each task instance
for /f %%x in (tasklist.temp) do (
if "%%x" EQU "%exe_1%" set /a count_1+=1
if "%%x" EQU "%exe_2%" set /a count_2+=1
if "%%x" EQU "%exe_3%" set /a count_3+=1
)
REM Use variables to see instance count
Echo %exe_1%: %count_1%
Echo %exe_2%: %count_2%
Echo %exe_3%: %count_3%
REM Use GTR 0 to see if process exists
if %count_1% GTR 0 if %count_2% GTR 0 Echo Both notepad and explorer are open
REM Delete temp file once finished. (NB: Will still exist if your code crashes)
del tasklist.temp
Conditional if-statements
As requested from your comment:
if %count_1% GTR 0 if %count_2% GTR 0 (
Echo Both notepad and explorer are open
goto :finish
)
if %count_1% GTR 0 (
Echo Only notepad is open
goto :finish
)
if %count_2% GTR 0 (
Echo Only explorer is open
goto :finish
)
REM Not Finished means none are open
Echo Neither notepad nore explorer are open
:finish
Here is my solution, keeping a similar structure to that of your sample script. Modify the EXE variable to reference the IMAGENAMEs you're interested in checking.
#ECHO OFF
SETLOCAL ENABLEDELAYEDEXPANSION
SET EXE=(notepad.exe wordpad.exe winword.exe thunderbird.exe outlook.exe greenshot.exe)
FOR %%i IN %EXE% DO (
TASKLIST /NH /FI "IMAGENAME EQ %%i" 2>NUL | FIND /I /N "%%i">NUL
IF !ERRORLEVEL! EQU 0 ( CALL :ProcessFound %%i ) ELSE ( CALL :ProcessNotFound %%i )
)
ECHO Finished^^!
EXIT /B 0
:ProcessFound
ECHO %1 is running
EXIT /B 0
:ProcessNotFound
ECHO %1 is not running
EXIT /B 1
If you want to start the program when the process is not found, insert START %1 after ECHO %1 is not running.

Batch file check if a program is running only once and close duplicate instances or launch it if none is running

I'm trying to realize a batch file that checks if a program is running and if not launch it, and more if is it launched more than one time close all the duplicate instances.
this is the code I implemented using also some tips found here in stackoverflow:
:check
tasklist /fi "imagename eq notepad.exe" /nh |find /i /c "notepad.exe" > "%temp%\variable.txt" #here I count how many instances are running
set /p value=<"%temp%\variable.txt" #and save the value in the variable.txt file
##check and choose action
if %value% equ nul goto none
if %value% geq 2 goto more
if %value% equ 1 goto one
:more
for /f "tokens=2" %%x in ('tasklist ^| findstr notepad.exe') do set PIDTOKILL=%%x
taskkill /F /PID %PIDTOKILL%
goto check
:none
start notepad.exe
goto check
:one
timeout 10 > nul
goto check
But some strange behavior happens when I test it...
if only one instances is running all fine, but if I close notepad while the batch file is running the routine goes to the :more label apparently without any reason...what I'm doing wrong?
thanks for any help
stupid error ... this is the working code:
:check
timeout 10 > nul
tasklist /fi "imagename eq notepad.exe" /nh |find /i /c "notepad.exe" > "%temp%\variable.txt"
set /p value=<"%temp%\variable.txt"
if %value% equ 0 goto none
if %value% geq 2 goto more
if %value% equ 1 goto check
:more
for /f "tokens=2" %%x in ('tasklist ^| findstr notepad.exe') do set PIDTOKILL=%%x
taskkill /F /PID %PIDTOKILL%
goto check
:none
start notepad.exe
goto check

Batch File to Check for Running Program and Start if not Running is not working

I have been trying to get this batch file to work but keep running into issues. I think I am close but need help getting this working. When the script runs I get Find: Parameter format not correct.
I am running this on a Windows Server 2008 R2 Standard.
#echo off
tasklist /FI "IMAGENAME eq program.exe" | find /i “program.exe"
IF ERRORLEVEL 2 GOTO NEXTPROGRAM
IF ERRORLEVEL 1 GOTO LAUNCHPROGRAM
:NEXTPROGRAM
goto SMADMIN
:LAUNCHPROGRAM
start "" "C:\path\to\program.exe"
goto SMADMIN
:SMADMIN
tasklist /FI "IMAGENAME eq program1.exe" | find /i “program1.exe"
IF ERRORLEVEL 2 GOTO NEXTPROGRAM2
IF ERRORLEVEL 1 GOTO LAUNCHPROGRAM2
:NEXTPROGRAM2
goto COMPLETE
:LAUNCHPROGRAM2
start "" "C:\path\to\program1.exe"
goto COMPLETE
You can check whether the exe is running this way:
SET running=0
FOR /f "tokens=*" %%A IN ('tasklist^ /v^| findstr /i /c:"program.exe"') DO SET running=1
IF %running%=1 GOTO NEXTPROGRAM
IF %running%=0 GOTO LAUNCHPROGRAM
Afterwards you just have to check if the %ProgramRunning% is set to 1.
Don't forget to reset the %running% flag back to 0 before reusing it.

How to keep GOTO :EOF but bypass it to finish the rest of the script?

Please look at this code below. It works but at the goto :EOF it stops the script and doesn't complete what is below it. Is there a work around? There of course is more to this script but the goto :EOF needs to be there in order for it to work.
:stripdup
>_.vbs echo set regex=new regexp
>>_.vbs echo regex.global=true
>>_.vbs echo regEx.IgnoreCase=False
>>_.vbs echo regex.pattern="%~3"
>>_.vbs echo wscript.stdOut.write regex.replace(wscript.stdin.readall,"%~4")
cscript /nologo _.vbs <"%~1" >"%~2"
del _.vbs
goto :EOF
del Campaign_RND.mis
copy Campaign_RND.mis.tmp Campaign_RND.mis
del Campaign_RND.mis.tmp
del "C:\Users\P Ditty\Documents\SH3\data\cfg\Backups_RND" /q
rd "C:\Users\P Ditty\Documents\SH3\data\cfg\Backups_RND"
tasklist /FI "IMAGENAME eq sh3.exe" | find /i "sh3.exe"
IF ERRORLEVEL 2 GOTO TEST2
IF ERRORLEVEL 1 GOTO TEST1
:TEST2
goto start
:TEST1
exit
If you want the GOTO to work in some cases and be omitted in others, then you need to make your jump conditional:
IF condition GOTO :EOF
At this point only you can say what this condition must be.
goto :EOF
is going to do exactly that every time! You will need to restructure your code if you need to do something else.

Exit status of tasklist in batch file?

I am executing following command in a label inside a batch file:
tasklist.exe /FI "USERNAME eq %USERDOMAIN%\%USERNAME%" /FI "IMAGENAME eq %1" /FI "PID eq %2" 2>nul && echo errorl:%errorlevel%
%1 is process running and %2 is its PID.
Even if process and its PID matches or doesnt matches, I m getting "errorl:1" in o/p.
I am not sure whats wrong here. Any idea?
You could pipe tasklist through the find command and get an errorlevel off of it.
Example:
tasklist | find "firefox.exe"
echo Error level = %ERRORLEVEL%
REM If firefox is running, the errorlevel is set to 0
REM If firefox is not running, errorlevel is set to 1
In my opinion, you can't use errorlevel at all,
because tasklist always returns a 0 even if the pid isn't found.
I suppose, you have to parse the output of tasklist.
To fetch the output of a command, FOR /F is a good choice.
To avoid problems wth the quoting in the FOR /F, I build first a cmd variable which is expanded with delayed expansion to avoid any side effects of special characters.
#echo off
setlocal enableDelayedExpansion
set "cmd=tasklist.exe /FI "USERNAME eq %USERDOMAIN%\%USERNAME%" /FI "IMAGENAME eq %1" /FI "PID eq %2""
for /F "delims=*" %%p in ('!cmd! ^| findstr "%2" ') do (
echo found %%p
)
%variables% are expanded before executing the line, so %errorlevel% will expand to some old value. (The fact that the code after && executes at all is your clue that the command returned 0)
You options are:
Use %errorlevel% or the more correct IF errorlevel 1 ... on the next line
Call setlocal ENABLEDELAYEDEXPANSION first and then use !errorlevel!
Edit:
I guess tasklist is buggy and/or stupid when it comes to exit codes, I wrote some code that does not use the exit code at all:
#echo off
if "%~1"=="SOTEST" (
start calc
ping -n 2 localhost >nul
for /F "tokens=1,2 skip=3" %%A in ('tasklist /FI "IMAGENAME eq calc.exe"') do (
call "%~0" %%A %%B
)
call "%~0" dummy.exe 666
goto :EOF
)
goto main
:IsTaskRunning
setlocal ENABLEEXTENSIONS&set _r=0
>nul 2>&1 (for /F "tokens=1,2" %%A in ('tasklist /FO LIST %*') do (
if /I "%%~A"=="PID:" set _r=1
))
endlocal&set IsTaskRunning=%_r%&goto :EOF
:main
call :IsTaskRunning /FI "USERNAME eq %USERDOMAIN%\%USERNAME%" /FI "IMAGENAME eq %1" /FI "PID eq %2"
if %IsTaskRunning% gtr 0 (echo.%1:%2 is running) else (echo.%1:%2 is NOT running)
Run it as test.cmd SOTEST and it prints:
calc.exe:4852 is running
dummy.exe:666 is NOT running
Easy solution to this, given that
1) you can't get an errorlevel from tasklist, and
2) you can't directly pipe it to a FIND
Just write it to a file using output redirection and use FIND to check the file. Each time this is run, it will overwrite the previous iteration, so no need to even do any file cleanup. Amazing how many bat/cmd file limitations can be overcome with a simple scratchpad file!!
:TOP
rem swap rems from good to bad to test
set findvar=goodfile.exe
rem set findvar=badfile.exe
set scratchfile=scratch.txt
tasklist /fi "status eq running" /fi "imagename eq %findvar%">%scratchfile%
type %scratchfile%
pause
echo Looking for %findvar%
find "%findvar%" %scratchfile%
echo Error level = %errorlevel%
pause
IF errorlevel 1 GOTO BAD
IF errorlevel 0 GOTO GOOD
GOTO OTHER
:BAD
echo Errrlevel 1 - task not found
PAUSE
GOTO TOP
:GOOD
echo Errrlevel 0 - task is running
pause
GOTO TOP
:OTHER
echo something else ????? you blew it somewhere!
tasklist returns 0 when executes successfully:
If you're looking for existence of some process or some attribute of a process, one method is to supply the attributes to tasklist and check if it returned any process names. If no matching processes are found, it'll return "INFO: No tasks are running which match the specified criteria."
The result of tasklist may be checked either via for command embedding (and parse command output) or filter via find or findstr, which accepts regular expressions & wildcards.
eg. To check if the any process is running with following criteria:
tasklist.exe /FI "USERNAME eq %USERDOMAIN%\%USERNAME%" /FI "IMAGENAME eq %1" /FI "PID eq %2" | find /v "No task" >nul && (echo process exists) || (echo na man).
Above method can also find if any document (window) is open, in addition to the underlying process, like "firefox.exe".
eg. close high speed vpn ad window if/when it pops up without notice:
tasklist /fi "windowtitle eq High-Speed*" | find /v "No task" >nul && (taskkill /fi "windowtitle eq High-Speed*")
Tested on Win 10 CMD

Resources