timeout or close when process is finished - windows

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.

Related

How to keep batch file running whilst using TASKKILL /f /t /im explorer.exe?

In short, I need to start 1.bat, that can CALL or START 2.bat to execute TASKKILL /im explorer.exe /f /t but keeps "1.bat" running (or reopens it) once "2.bat" is finished. The difficulty is, I need to keep the /t switch in TASKKILL to make it transferable.
Full Explanation:
I have several older laptops running Windows 7 x64. They will run games, but only if I use Task Manager to end Explorer, it's associated processes and stop several unneeded services. This frees up RAM and CPU to start games via Task Manager..
To avoid ending each process/service individually every time, I wrote 2 cmd batch files:
1) Options.bat -- (SHORTENED)
#echo off
:begin
echo (0) Kill Processes
echo (1) Run [game]
SET /p op=Select Task:
if "%op%"=="0" goto killall
if "%op%"=="1" goto op1
killall:
CALL "C:\TK.bat"
cls
goto begin
op1:
start " " /realtime "C:\[exe path]"
goto exit
:exit
exit
2) TK.bat -- (SHORTENED)
net stop [service]
taskkill /im explorer.exe /f /t
taskkill /im [specific process].exe /f /t
Both of which work as intended - provided I initially start Options.bat via Task Manager.
Problem: when I run Options.bat from Windows Explorer (even "Run As Administrator") and call the TK.bat script to run TASKKILL /im explorer.exe /f /t it does work, but also closes the CMD window, when i want it to return to the options selection. This does make sense when i'm using the "tree" attribute for TASKKILL.
However, if I run Options.bat via Task Manager, and CALL TK.bat, it will execute the commands (without closing itself) then return to the task selection - which is exactly what i want to happen!
I assume this is because it is running as the Local System account via Task Manager and not mine or the built in Administrator account?
I have tried the RUNAS command within Options.bat -
RUNAS /user:Adminstrator "C:\TK.bat"
which runs TK.bat, executes the TASKKILL command and then RUNAS again to return to the first batch file in my username. This does work, but I still have to press enter at each password prompt.
I have also tried numerous variations of the TASKKILL /FI switch:
TASKKILL /fi IMAGENAME ne cmd.exe /im explorer.exe /f /t`
TASKKILL /fi USERNAME eq [name] /fi WINDOWTITLE ne Options.bat /im explorer.exe /f /t
Which, I thought, would end all processes "not equal" to cmd.exe/Options.bat but I cannot get it to work.
Question: Is there a way of executing the TASKKILL /im explorer.exe /f /t within TK.bat, that will not close the currently running batch file and without having to run it from Task Manager? Perhaps a different command or giving the Options.bat some sort of elevated authority to stop it from being closed when Explorer.exe /t is ended. Ideally, without installing separate 3rd party tools?
I know I could edit the batch file to end explorer.exe, end each associated .exe and then stop the services I do not need, individually, but this is time consuming and defeats the point of writing the file to make it automated and transferable (if needed).
Any help would be greatly appreciated and I can upload the full code of both batch files, if that would help.
Strangely enough, the simple taskkill /F /IM explorer.exe & start explorer command does this task. I don't know why, but it works.
To prevent taskkill /im explorer.exe /f /t from killing the cmd instance which is executing your batch file, You need to break the parent-child relationship between that particular instance of cmd.exe and explorer.exe.
The trick is to use two extra instances of nested cmds. The first one launches the second one and terminates immediately so the second instance becomes an orphaned process which can not be determined as descendant of exeplorer.exe. At this point the second instance can safely execute taskkill /im explorer.exe /f /t
start "Chain breaker" /min cmd /d /c start "Orphaned Process" cmd /d /c Options.bat
The above can be used from Command Prompt or from another batch file.
You can also incorporate this technique directly in to the Options.bat file, But extra logic is needed for Options.bat to determine when to launch itself in nested cmd and when to execute the actual code.
A sample script demonstrating the concept would be:
#echo off
setlocal EnableExtensions DisableDelayedExpansion
for /F "tokens=3 delims=:" %%L in ("%~0") do goto %%L
REM Reinvoke the batch file forcing it to jump to the :main label
start "Chain breaker" /min cmd /d /c start "Orphaned Process" cmd /d /c #"%~d0\:main:\..%~pnx0"
exit /b
:main
taskkill /im explorer.exe /f /t
echo I'm alive
pause
exit /b

How to close all active windows/applications using a batch file

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

Restart terminal application with a batch file

I need a .bat file that will close and re-open start.cmd (C:\Users\Jake\Desktop\PocketMine-MP\start.cmd) <-- that's the file location. I need it to close and re-open every 75 min. The terminal has to close it can't stay open and launch another all I've gotten so far is:
#echo off
:loop
start "start.cmd" "C:\Users\Jake\Desktop\PocketMine-MP\start.cmd
timeout /t 20
taskkill /f /im "start.cmd" >nul
goto loop
Its starting the terminal every 20 seconds like I want it too but its not closing the old one.
If anyone can help it would assist me and my small network greatly.
Rename start.cmd to bat_start.cmd then try the following.
#echo off
:loop
start "bat_start.cmd" "C:\Users\Jake\Desktop\PocketMine-MP\bat_start.cmd"
timeout /t 20
taskkill /f /fi "windowtitle eq bat_start.cmd*" /im "cmd.exe" >nul
goto loop
If you use same file for control the loop and start file again, then it's fall in recursion. Following example work for me,
#echo off
:loop
start "test2" "C:\test2.bat"
timeout /t 60
taskkill /f /fi "windowtitle eq test2*" /im "cmd.exe" >nul
goto loop
test2 file
#echo off
echo "start job here"
:: Do your work here
pause :: remove the pause, it's just for simulating
exit
You can use the TimeCommander plugin. Set to run a restart command every 75 minutes.

Batch file - how to kill process if there is only one instance of it running?

I'm trying to write a batch that checks how many instances of the process "example.exe" are running, and if there are two or more instances, leave it running. But if there is only one instance running, end the process. Here's what I have:
#echo off
wmic process where name="example.exe" | find "example" /c > %temp%\variable.txt
set /p value=<%temp%\variable.txt
if %value% lss 2 goto endprocess
if %value% gtr 1 goto continue
:endprocess
start taskkill /f /im example.exe
:continue
ECHO continue
#echo off
My issue is this: It always thinks value is lss 2 (it thinks there are less than 2 instances of the process running). However, in my task manager, I can see that there is obviously 2 instances running. I think it's an issue with defining the value maybe? I don't know, I'm quite new to this. Any help? Thanks!
UPDATE
Okay I've now changed it to this (suggested by Magoo)
#echo off
wmic process where name="example.exe" | find "example" /c > "%temp%\variable.txt"
set /p value=<"%temp%\variable.txt"
if %value% equ 1 goto endprocess
if %value% neq 1 goto continue
:endprocess
start taskkill /f /im example.exe
:continue
ECHO continue
#echo off
This still doesn't exactly work, but i changed the number of instances from 1 to 0 and it ended the process. In other words, 1 process was running, but this batch file thought that 0 were running. Any ideas now?
This uses tasklist in XP Pro and higher:
#echo off
tasklist /fi "imagename eq example.exe" /nh |find /i /c "example.exe" > "%temp%\variable.txt"
set /p value=<"%temp%\variable.txt"
if %value% equ 1 taskkill /f /im example.exe
ECHO continue
#echo off
You can do it with one line and no temp file also - this uses another findstr filter to check if the number is a single 1 on a line and then && is a conditional operator that will launch taskkill if it does find 1.
#echo off
tasklist /fi "imagename eq example.exe" /nh |find /i /c "example.exe"|findstr "^1$" >nul && taskkill /f /im example.exe
ECHO continue
#echo off
I'd suggest that you have a fault with your logic.
The code should go to endprocess if the number found is <2 - that is, 0 or 1. If the lss 2 test is failed, then the count must be 3+, so the gtr 1 test will always succeed.
I've no idea why you don't use simply
if %value% neq 1 goto continue
or even
if %value% equ 1 start taskkill /f /im example.exe
But probably you've not told us that you want to be able to detect other instance-counts - as well as concealing the name of the executable for which you are checking.
Now - it may have been really useful to show us the content of the file. Are you sure the file is actually being generated? What happens if you try using "%temp%\variable.txt" instead of %temp%\variable.txt - that is, "quote the filename" ?

How can I kill child process using taskkill in a batch script?

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.

Resources