I want to kill a process ONLY IF the process exists, I want to do this because I have a tool that runs only if there is no error and I made some tests and indeed there is an error when I try to kill a process that doesn't exists. This is the line I use to kill a process:
taskkill /f /IM notepad.exe
But I want to validate it only executes when the process EXISTS.
Thank you!!!
Taken from this question, you should try this code:
taskkill /f /im notepad.exe /fi "memusage gt 40" 2>NUL | findstr SUCCESS >NUL && if errorlevel 1 ( echo Notepad was not killed ) else ( echo Notepad was killed )
If that does not help, you can look at this and this question.
I hope it helps!
Related
I am unable to call a bat process within another bat.
This is the situation.
I have a n1.bat that basically contains:
TITLE "n1.bat"
...
...
start /b /MIN "n2.bat"
...
The n2.bat contains:
TITLE "n2.bat"
...
...
start someother.bat
start another.bat
exit
Now I use a third bat (n3.bat) that must kill everything.
TITLE "n3.bat"
...
TASKKILL /F /T /PID n1_PID
...
exit 0
Unfortunately when n3.bat ends a window called n1.bat - n2.bat remains active (the echo output belongs to n2.bat).
I tried to kill it in some ways:
1- Tried to get the process pid from tasklist -> there is no process called n2.bat or similar
TASKLIST /V /NH>Tasks.txt
FOR /F "tokens=2 delims= " %%n2_pid IN ('FINDSTR n2.bat Tasks.txt') DO SET PID=%%n2_pid
TASKKILL /PID %n2_pid%
2- Trying to use TASKKILL /F /FI "WINDOWTITLE eq n2.bat" -> no process found
I tried the previous solutions also starting n2.bat with
start /min "n2.bat" (so without /b)
with no success.
The only way I manage to kill it is to calling
TASKKILL /F /IM cmd.exe
that I really would like to avoid since it obviously kills all opened cmd.
Any ideas to retrieve the guilty pid?
I have a X.exe program that takes about 2-6 hours to finish. Exact time is unknown, but I'd like to implement a threshold of 6.5 or 7 hours. If this program does not return any value by this amount of time, it will be killed. How do I implement this using batch *.bat files?
Here is what I had so far: a timer bat1.bat and an actual bat2.bat.
bat1.bat:
start cmd /C bat2.bat & timeout /t 25200 & taskkill /im X.exe /f
bat2.bat:
cd blah
bat1.bat
The problem with this approach is that only after 25200 seconds (or 7 hours) the timer will be stopped, and it won't be terminated before that limit. How do I tell the computer that if the program X.exe is finished then don't wait anymore?
Any help is appreciated!
I think this is a much simpler solution:
rem Start the process that will kill the X.exe program after 7 hours
start "WaitingToKill" cmd /C timeout /t 25200 ^& taskkill /im X.exe /f
rem Run the X.exe program and wait for it to terminate
X.exe
rem Kill the killer process and terminate
taskkill /fi "WINDOWTITLE eq WaitingToKill" /f
In this method there is not any additional code running at same time; just the waiting state of timeout command.
EDIT: Some explanations added
Note that both the "WaitingToKill" cmd.exe process with the timeout command and the X.exe program are running in parallel. If the timeout command ends after 7 hours, the taskkill /im X.exe /f command is executed, the X.exe program is killed and both cmd.exe processes ends.
If the X.exe program ends before the 7 hours, the Batch file execute the next line as usual. This line is taskkill /fi "WINDOWTITLE eq WaitingToKill" /f, so the window with the timeout command is killed and both cmd.exe processes ends.
thanks to #Squashman i was able to build a script on my own. seem to work fine
#echo off
setlocal enableextensions enabledelayedexpansion
set /a "checktime=60"
set /a "elapsedtime=0"
set /a "killtime=150"
set XProg=X.exe
start cmd /C runTest.bat
timeout /t 10
:while1
echo Go to WHILE loop.
echo elapsedtime = %elapsedtime%
echo killtime = %killtime%
set /a "timeleft = %killtime% - %elapsedtime%"
echo timeleft = %timeleft%
if /i %timeleft% geq 0 (
tasklist /fi "imagename eq %XProg%" 2>NUL | find /i /n "%XProg%">NUL
if "%ERRORLEVEL%"=="0" (
echo %XProg% is still running...
) else (
echo %XProg% is finished before timer.
)
set /a "elapsedtime = elapsedtime + checktime"
timeout /t %checktime%
goto :while1
) else (
taskkill /im %XProg% /f
echo %XProg% is terminated.
)
lessons learned:
1. hard to compare numeric variables in batch (compare diff with 0 instead)
2. terminated first time elaspedtime > killtime (might be a bit longer than killtime depending how often it checks)
I've tried various solutions but in the end this is really cumbersome in batch.
If you are willing to use an external tool the simplest way is
"C:\Program Files\Git\usr\bin\timeout.exe" 5 .\test.exe
It properly returns the exit code of the test process, also works if you spawn multiple test processes simultaneously and does not pop up windows all the time.
I am a beginner.I just went curious about cmd so I want to make a batch file that kills the active windows and shutdown/restart the computer safely.
I came across commands like-
taskkill /im "program.exe"
tasklist
shutdown -s
But I want to close all active windows but not forcefully.
If there a specific command or some combination of commands please do mention.
Thanks in Advance.
PS- I came across powershell but I want to know if i can achieve this using batch file (cmd commands) .Below is the link
How to close all windows
If you perform a treekill on explorer.exe, it will close all other programs except background processes. Those batch scripts will only work if they are called in an exceptional manner that makes them background processes, system processes or if they are not a child process of explorer.exe.
Here's the fastest reference implementation of my treekill explorer method
#echo off
echo closing all programs...
taskkill /f /t /im explorer.exe
explorer.exe
Here's an example implementation of my treekill explorer method combined with hibernate to make a fast shutdown and startup script.
#echo off
echo shutting down...
echo closing all programs...
taskkill /f /t /im explorer.exe
echo hibernating...
shutdown /f /h
echo restoring...
explorer.exe
echo thanks you for using JessieTessie's fast shutdown and startup.
You can do
#echo off
#powershell Get-Process | Where-Object {$_.MainWindowTitle -ne ""} | stop-process
taskkill /f /im explorer.exe
It will execute powershell command that will find and close all running programs that isn't hidden or evelated using windowtitle.
But it will close all apps including yours.
To prevent that you need to recode it from c++ (you can use system("somecommand") from windows.h) and before executing closeAll commands put freeconsole() in code. But you will need to find how to get console back.
title Kill all running apps
cd c:\windows\System32
for /f "skip=3 tokens=1" %%i in ('TASKLIST /FI "USERNAME eq %userdomain%\%username%" /FI "STATUS eq running"') do (
if not "%%i"=="svchost.exe" (
if not "%%i"=="explorer.exe" (
if not "%%i"=="cmd.exe" (
if not "%%i"=="tasklist.exe" (
echo.
taskkill /f /im "%%i"
taskkill /f /im explorer.exe
echo.
)
)
)
)
)
pause
I want a batch program, which will check if the process notepad.exe exists.
if notepad.exe exists, it will end the process,
else the batch program will close itself.
Here is what I've done:
#echo off
tasklist /fi "imagename eq notepad.exe" > nul
if errorlevel 1 taskkill /f /im "notepad.exe"
exit
But it doesn't work. What is the wrong in my code?
TASKLIST does not set errorlevel.
echo off
tasklist /fi "imagename eq notepad.exe" |find ":" > nul
if errorlevel 1 taskkill /f /im "notepad.exe"
exit
should do the job, since ":" should appear in TASKLIST output only if the task is NOT found, hence FIND will set the errorlevel to 0 for not found and 1 for found
Nevertheless,
taskkill /f /im "notepad.exe"
will kill a notepad task if it exists - it can do nothing if no notepad task exists, so you don't really need to test - unless there's something else you want to do...like perhaps
echo off
tasklist /fi "imagename eq notepad.exe" |find ":" > nul
if errorlevel 1 taskkill /f /im "notepad.exe"&exit
which would appear to do as you ask - kill the notepad process if it exists, then exit - otherwise continue with the batch
This is a one line solution.
It will run taskkill only if the process is really running otherwise it will just info that it is not running.
tasklist | find /i "notepad.exe" && taskkill /im notepad.exe /F || echo process "notepad.exe" not running.
This is the output in case the process was running:
notepad.exe 1960 Console 0 112,260 K
SUCCESS: The process "notepad.exe" with PID 1960 has been terminated.
This is the output in case not running:
process "notepad.exe" not running.
TASKLIST doesn't set an exit code that you could check in a batch file. One workaround to checking the exit code could be parsing its standard output (which you are presently redirecting to NUL). Apparently, if the process is found, TASKLIST will display its details, which include the image name too. Therefore, you could just use FIND or FINDSTR to check if the TASKLIST's output contains the name you have specified in the request. Both FIND and FINDSTR set a non-null exit code if the search was unsuccessful. So, this would work:
#echo off
tasklist /fi "imagename eq notepad.exe" | find /i "notepad.exe" > nul
if not errorlevel 1 (taskkill /f /im "notepad.exe") else (
specific commands to perform if the process was not found
)
exit
There's also an alternative that doesn't involve TASKLIST at all. Unlike TASKLIST, TASKKILL does set an exit code. In particular, if it couldn't terminate a process because it simply didn't exist, it would set the exit code of 128. You could check for that code to perform your specific actions that you might need to perform in case the specified process didn't exist:
#echo off
taskkill /f /im "notepad.exe" > nul
if errorlevel 128 (
specific commands to perform if the process
was not terminated because it was not found
)
exit
That's why it's not working because you code something that is not right, that's why it always exit and the script executer will read it as not operable batch file that prevent it to exit and stop
so it must be
tasklist /fi "IMAGENAME eq Notepad.exe" 2>NUL | find /I /N "Notepad.exe">NUL
if "%ERRORLEVEL%"=="0" (
msg * Program is running
goto Exit
)
else if "%ERRORLEVEL%"=="1" (
msg * Program is not running
goto Exit
)
rather than
#echo off
tasklist /fi "imagename eq notepad.exe" > nul
if errorlevel 1 taskkill /f /im "notepad.exe"
exit
Try this:
#echo off
set run=
tasklist /fi "imagename eq notepad.exe" | find ":" > nul
if errorlevel 1 set run=yes
if "%run%"=="yes" echo notepad is running
if "%run%"=="" echo notepad is not running
pause
I'm capturing the PID in a variable which I kill later
IF NOT "%SERVICE_PID%" == 0 taskkill /pid %SERVICE_PID% /t /f
though everytime I do this in a batch file it makes my computer restart because it kills some system process
the service pid should be a user defined service launched from cmd
I dont understand why it keeps making my machine croak.
When I run "taskkill /pid %SERVICE_PID% /t /f" on the command line it works fine! =/
help!
Setting SERVICE_PID
FOR /F "tokens=4 delims= " %%A IN ('sc queryex myservice ^|FIND "PID"')
DO SET SERVICE_PID=%%A
I found that using this will get the proper PID:
for /f "tokens=1,2,3,4 delims=/ " %%a in ('sc queryex ServiceName ^|FIND "PID"') do set PID=%%c
taskkill /pid %PID% /t /f
Then it works like a charm.
Try removing /f option, it forces to terminate a process, so system processes might get terminated forcefully without notification.
I am suspecting you are trying to kill some system processes in the batch script, in the sense that in your list of PIDs there might be some system process IDs as well.
Thanks
Make sure you have enabled delayed expansion. See the HELP SET for an explanation.
Insert this line
SETLOCAL ENABLEDELAYEDEXPANSION
as the first line of your batch file.
and use !SERVICE_PID! instead of %SERVICE_PID% to get the environment variable.
taskkill /fi "IMAGENAME eq idsm.exe" /fi "CPUTIME gt 00:30:00"
Image Name PID Session Name Session# Mem Usage
========================= ======== ================ =========== ============
idsm.exe 4556 Console 0 38,328 K
I got the this result, in the same command line how to kill this process, its should run automatically, means how to use this PID for killing
I found this the most reliable
net stop SERVICE_NAME
timeout /t 10
for /f "tokens=1,2,3,4 delims=/ " %%a in ('sc queryex SERVICE_NAME ^|FIND "PID"') do set PID=%%c
if not %PID% == 0 taskkill /pid %PID% /f
timeout /t 10
net start SERVICE_NAME
The timeout is arbitrary.
The first timeout gives service a chance to stop itself properly for some extra amount of time.
The second timeout allows the operating system to react, otherwise you may end up with
The service is starting or stopping. Please try again later. and service will not restart.
I am checking if service is not stopped by if not %PID% == 0 and force killing it if necessary. The /t flag was unnecessary in my case.