Home > database >  How can I make a batchfile that constantly checks if a program is open and if it is not, start it mi
How can I make a batchfile that constantly checks if a program is open and if it is not, start it mi

Time:12-09

I am fairly new to coding and batch files, so bare with me.

The program I want to start that way is opera. But the batch file doesnt seem to find it. This is how far I got:

tasklist /FI "opera.exe" 2>NUL | find /I /N "opera.exe">NUL
if NOT "%ERRORLEVEL%" == "0" start "" "C:\Users\leonv\AppData\Local\Programs\Opera.exe"
PAUSE 

CodePudding user response:

I would take the verification check, just a little bit further. I would look to see if an ImageName of Opera.exe, with a Status of Running, and for the current UserName is returned:

@%SystemRoot%\System32\tasklist.exe /Fi "Status Eq Running" /Fi "ImageName Eq Opera.exe" /Fi "UserName Eq %UserDomain%\%UserName%" | %SystemRoot%\System32\find.exe "="
@If ErrorLevel 1 Start "" /Min "%LocalAppData%\Programs\Opera.exe"

CodePudding user response:

You need to specify IMAGENAME eq processname like:

tasklist /fi "IMAGENAME eq opera.exe"

Additionally, no need to run if statements, you can use conditional operators && and ||

(tasklist /fi "IMAGENAME eq opera.exe"| findstr /I "opera.exe")>nul && echo It's running || start "" "%LocalAppData%\Programs\Opera.exe"

and to run it in a loop, checking every N of seconds:

@echo of
:loop
(tasklist /fi "IMAGENAME eq opera.exe"| findstr /I "opera.exe")>nul && echo It's running || start "" "%LocalAppData%\Programs\Opera.exe"
timeout /t 20
goto :loop
  • Related