batch file to check if exe is running if so taskkill - loops

I'm having problems with the firefox Flashplayerplugin eating up too much ram and lagging my system when it's not in use. The only solution I found was killing the flashplayerplugin while using firefox, uninstalling, reinstalling or a fresh firefox install or new profile doesn't solve it; however, it's becoming very tedious having to check taskmanager all the time and kill it and the flashplayerplugin always seems to start on it's own.
The question I have is if it's possible to create a batch file to check if FlashPlugin_11_8_800_94.exe is running and kill it after a period of time (5-10 seconds) and continue running the batch file actively, in a loop, scanning if FlashPlugin_11_8_800_94.exe has started again, then kill it after 5 - 10 seconds, rinse and repeat?
Edit:
Found a batch file and modified it, but also seems to be missing some perimeters to actively search if it's running, even when it is not. It doesn't work either way though.
#echo off
:search
TASKLIST|FIND "FlashPlayerPlugin"
IF %ERRORLEVEL% = 0 THEN (GOTO found)
TIMEOUT /T 5
GOTO search
:found
taskkill /im FlashPlayerPlugin_11_8_800_94.exe
--
This batch file doesn't work either.
set tasklist=%windir%\System32\tasklist.exe
set taskkill=%windir%\System32\taskkill.exe
-------------------------------------------------------
:STOPPROC
set wasStopped=0
set procFound=0
set notFound_result=ERROR:
set procName=%1
for /f "usebackq" %%A in (`%taskkill% /IM %procName%`) do (
if NOT %%A==%notFound_result% (set procFound=1)
)
if %procFound%==0 (
echo The process was not running.
goto :EOF
)
set wasStopped=1
set ignore_result=INFO:
:CHECKDEAD
"%windir%\system32\timeout.exe" 3 /NOBREAK
for /f "usebackq" %%A in (`%tasklist% /nh /fi "imagename eq %procName%"`) do (
if not %%A==%ignore_result% (goto :CHECKDEAD)
)
goto :EOF
-------------------------------------------------------
:MAIN
call :STOPPROC FlashPlayerPlugin_11_8_800_94.exe

taskkill /im FlashPlugin_11_8_800_94* /f >nul 2>&1

For anyone who still might find it useful:
This is a small script that scans tasklist for processes containing processname once every 5 seconds. For example, if you put "notepad" for the processname, it will end processes like "notepad.exe" and "notepad++.exe". To use the script, copy and paste the following into notepad and save has "simple_pk.cmd". processname can have any characters except double quotes("), ampersands (&), or commas (,).
::Simple monitor and kill process
#echo off&prompt :&mode con cols=50 lines=10
set processname=flashplayerplugin
:loop
cls&echo Searching for %processname%...
for /f "tokens=1 delims=," %%a in ('tasklist /fo csv ^|FINDSTR /I /C:"%processname%"') do call :killprocess %%a
ping -n 6 127.0.0.1>NUL
goto :loop
:killprocess
echo. |set /p d=killing %*...
taskkill /f /im "%*">nul 2>&1
set err=%errorlevel%
set success=Success
if not %err%==0 set success=fail (err code: %err%)
if %err%==128 set success=fail (process not found)
echo %success%&goto :eof
This is a slightly different version of the same script. This will only end processes that match the whole name exactly:
::Simple monitor and kill process (exact name)
#echo off&prompt :&mode con cols=50 lines=10
set processname=FlashPlayerPlugin_11_8_800_94.exe
:loop
cls&echo Searching for %processname%...
for /f "tokens=1 delims=," %%a in ('tasklist /fo csv ^|FINDSTR /C:"%processname%"') do call :killprocess %%a
ping -n 6 127.0.0.1>NUL
goto :loop
:killprocess
set name=%*
set name=.,;%name:"=%;,.
echo %name%|FINDSTR /C:".,;%processname%;,.">nul || goto :eof
echo. |set /p d=killing %*...
taskkill /f /im "%*">nul 2>&1
set err=%errorlevel%
set success=Success
if not %err%==0 set success=fail (err code: %err%)
if %err%==128 set success=fail (process not found)
echo %success%&goto :eof

Your IF is not correct:
#echo off
:search
TASKLIST|FIND "setup.exe"
IF %ERRORLEVEL% equ 0 (GOTO found)
TIMEOUT /T 5
GOTO search
:found
taskkill /im setup.exe

More simpler form
#echo off
:search
TASKLIST|FIND "setup.exe"
IF %ERRORLEVEL% equ 0 (taskkill /im setup.exe
exit)
TIMEOUT /T 5
GOTO search

I was looking over the first bit of code at top and I find a way, I believe. This is what I got; really simple.
#echo off
cls
:start
timeout /t 5
tasklist|find "explorer.exe"
goto found
goto start
:found
taskkill /f /im explorer.exe
goto start
Of course, any program will work.

Related

Auto close non responding , unknown or frozen Game

My batch file is supposed to auto exit my game if it freezes or isn`t booting , which happens from time to time as it's finicky due to the RE Engine. Solution would be to have the game auto exit as soon as there's less than 10% Cpu usage or if its not responding or unknown status.
This is what I've got so far in my batch file:
#echo OFF
start "" "Autolaunch DMC5 aka Steam, required for Playing.ahk"
TIMEOUT /t 20
start "" "steam://rungameid/601150"
TIMEOUT /t 30
start /min "" "DMCVTrainer.exe"
start /min "" "SSSiyanCollabTU5.CT"
set "process_name=DevilMayCry5.exe"
::remove .exe suffix if there is
set pn=%process_name:.exe=%
setlocal enableDelayedExpansion
set c=0
:: getting three snapshots of CPU usage of the given process
for /f skip^=2^ tokens^=3^ delims^=^" %%p in ('typeperf "\Process(%pn%)\%% Processor Time" -sc 3') do (
set /a counter=counter+1
for /f "tokens=1,2 delims=." %%a in ("%%p") do set "process_snapshot_!counter!=%%a%%b"
)
:: remove rem to see the cpu usage from the three snapshots
rem set process_snapshot_
:: if all three snapshots are less than 0000010 process will be killed
if 1%process_snapshot_1% LSS 10000010 if 1%process_snapshot_2% LSS 10000010 if 1%process_snapshot_3% LSS 10000010 (
tskill %pn%
)
:RUNNING
tasklist|findstr DevilMayCry5.exe > nul
if errorlevel 1 (
timeout /t 1
taskkill /F /IM cheatengine-x86_64.exe
taskkill /F /IM DMCVTrainer.exe
taskkill /F /IM Steam.exe
) & GOTO ENDLOOP
timeout /t 1
GOTO RUNNING
:ENDLOOP
exit /B
wont let me update because my code isnt in proper format.

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

Wait for process to end and continue code in CMD/BATCH

I am trying to wait for the process to end, Can't use the "Start /W" because the process opens from another program.
So all in all, I need some kind of scanner to look for if the process in the WaitSession and then continue the code to the KillSession
#echo off
color 02
cd /D C:\Windows\System32
timeout -t 1
***WaitSession***
(Wait for this process to end) MightyQuest.exe
***KillSession***
taskkill /f /im PublicLauncher.exe
taskkill /f /im AwesomiumProcess.exe
Thanks
This should do it:
#echo off
color 02
cd /D C:\Windows\System32
timeout -t 1
SET TempFile="%Temp%\%RANDOM%.txt"
:WaitSession
REM Fetch the current process list. Store in a temp file for easy searching.
TASKLIST > %TempFile%
REM Reset the process "flag" variable.
SET "Process="
REM Check for a process with the target name by searching the task list for the target process name.
REM If output is returned, it will be put into the Process "flag" variable.
FOR /F "usebackq tokens=1 delims=-" %%A IN (`FINDSTR /I "MightyQuest.exe" %TempFile%`) DO SET Process=%%A
REM If nothing was returned, it means the process isn't running.
IF "%Process%"=="" GOTO KillSession
ECHO Process is still running.
REM Wait and then try again.
TIMEOUT /T 20
GOTO WaitSession
:KillSession
taskkill /f /im PublicLauncher.exe
taskkill /f /im AwesomiumProcess.exe
REM Cleanup.
DEL %TempFile% > nul
The idea here is you keep polling the active task list and when the target process is found, you delay for a few seconds and then try again.
Once it is not found in the task list, you jump to the KillSession steps.
Use wmic Windows Management Instrumentation Command
#echo off
color 02
rem why? cd /D C:\Windows\System32
timeout -t 1
:wait
TIMEOUT -t 3 /NOBREAK>nul
rem ***WaitSession***
rem (Wait for this process to end) MightyQuest.exe
for /F "tokens=*" %%G in (
'wmic process where "name='MightyQuest.exe'" get name'
) do if /i not "%%G"=="No Instance(s) Available." goto :wait
rem ***KillSession***
taskkill /f /im PublicLauncher.exe
taskkill /f /im AwesomiumProcess.exe
A vbscript
Set WshShell = WScript.CreateObject("WScript.Shell")
Set objWMIService = GetObject("winmgmts:\\.\root\CIMV2")
Set objEvents = objWMIService.ExecNotificationQuery _
("SELECT * FROM Win32_ProcessTrace")
Do
Set objReceivedEvent = objEvents.NextEvent
msgbox objReceivedEvent.ProcessName
Loop
Use Win32_ProcessTraceStop to only catch terminations.

Combination of `sleep` and `pause` command

Ok, after seeing crazy stuff being completed in so little code, I have high hopes this is possible.
Pretty much, I want to use the pause command normally, however, if the user doesn't input anything for a specified duration of time, it automatically continues.
In pseudo code:
(sleep %sleep-time%&Echo Pass)1>0 & pause
I thought at first I could do this using start /b to create a process that echoed input while being paused i the current thread, but that could cause problems if the user does input something.
Bonus
What would be really cool is if the errorlevel would be changed based on whether the user inputted something, or if the pause command timed out.
I suggest using timeout:
timeout /T 60 >NUL
This will sleep your script for 1 minute, or unless the user hits a key.
#echo off
setlocal
rem TimedPause.bat - Antonio Perez Ayala
if "%1" equ ":PausePart" goto PausePart
if "%1" neq "" goto begin
echo TimedPause.bat seconds
echo/
echo Wait for given seconds or until user press a key
echo At end, the presence of keyPressed.txt file indicate the cause of exit
goto :EOF
:begin
set seconds=%1
start "" /B "%~F0" :PausePart
for /F "skip=2 tokens=2 delims=," %%a in ('tasklist /FI "IMAGENAME eq cmd.exe" /FO CSV') do (
set PausePart=%%a
goto TimePart
)
:TimePart
ping -n 2 localhost > NUL
if exist keyPressed.txt goto :EOF
set /A seconds-=1
if %seconds% gtr 0 goto TimePart
taskkill /PID %PausePart% /F > NUL
goto :EOF
:PausePart
del keyPressed.txt 2> NUL
pause
echo %time% > keyPressed.txt
exit

Perform summation of integers on each line in a file in `cmd`

Time for some command line fu in the least fu conducive shell, cmd.exe.
How can I perform a summation of integers contained in a file?
You might consider the following to work:
taskkill /f /im rsync.exe
echo %errorlevel% > %temp%/kill_site.log
taskkill /f /im ssh.exe
echo %errorlevel% >> %temp%/kill_site.log
taskkill /f /im 7za.exe
echo %errorlevel% >> %temp%/kill_site.log
set /a errorresult=1
for /F "tokens=*" %%G in (%temp%/kill_site.log) do set /A errorresult=%%G+%errorresult%
But, it appears that %errorresult% will always be the value before the for loop during the for loop. Meaning, the resulting %errorlevel% always has [the integer value of the last line in %temp%/kill_site.log] + [the %errorlevel% set, which is 1].
In the case of exit codes provided by taskkill, if taskkill succeeds in killing an existing process, the exit code is 0, then resulting %errorresult% in this case will be 1. If a process doesn't exist when taskkill is called to kill it, the exit code is 128; in this case the %errorresult% will be129`.
I'd like %errorresult% to be the total of all integers contained on lines in %temp%/kill_site.log. How do I do this?
[update]
Thanks to Stephen's answer below, I have a final script as follows that I wanted to include for future reference by other users:
setlocal enabledelayedexpansion
taskkill /f /im rsync.exe
echo %errorlevel% > %temp%/kill_site.log
taskkill /f /im ssh.exe
echo %errorlevel% >> %temp%/kill_site.log
taskkill /f /im 7za.exe
echo %errorlevel% >> %temp%/kill_site.log
set /a errorresult=1
for /F "tokens=*" %%G in (%temp%/kill_site.log) do set /A errorresult=%%G+!errorresult!
if %errorresult% lss 255 sendmail.vbs && eventcreate /l application /so backup_scripts /t warning /id 1 /d "website rsync has to be killed because it was long running."
endlocal
It utilizes endlocal.
I also just realized this is a bit backwards, as I should be checking if the processes are running previous to taking any invalid action against the non-existent processes, but the question is still resolved. Finding if a specific running process exists with a batch script actually uses a similar method of checking the %errorlevel% is also quite easy.
within a forloop you need delayed expansion for your variables:
use
SETLOCAL ENABLEDELAYEDEXPANSION
at the beginning of your batchfile
and change your for-loop to
for /F "tokens=*" %%G in (%temp%/kill_site.log) do set /A errorresult=%%G+!errorresult!
This is because in your for-loop %errorresult% will always use the value at Parse-time. !errorresult! will use the value at run-time.
Stephan's answer works fine, but there is a simpler method that doesn't require delayed expansion.
The SET /A command does its own expansion of variable names, and it always uses the current value.
set /a errorresult=1
for /F "tokens=*" %%G in (%temp%/kill_site.log) do set /A errorresult=%%G+errorresult
Or better yet
set /a errorresult=1
for /F "tokens=*" %%G in (%temp%/kill_site.log) do set /A errorresult+=%%G
Note - I don't understand why you initialize errorresult to 1. I should think 0 would make more sense.
Here is a non portable solution, but it is NOT the answer, but may assist others that come across this problem in the future:
taskkill /f /im rsync.exe
echo %errorlevel% > "%temp%/kill_site.log"
set /p res1=< "%temp%/kill_site.log"
echo > "%temp%/kill_site.log"
taskkill /f /im ssh.exe
echo %errorlevel% > "%temp%/kill_site.log"
set /p res2=< "%temp%/kill_site.log"
echo > "%temp%/kill_site.log"
taskkill /f /im 7za.exe
echo %errorlevel% > "%temp%/kill_site.log"
set /p res3=< "%temp%/kill_site.log"
echo > "%temp%/kill_site.log"
set /A errorresult=%res1% + %res2% + %res3%
I have marked this as a community wiki as the question is still pending an answer.

Resources