• ARTICLES
SEARCH

How-To Geek

Batch Script to Conditionally Restart an Application

Common system and/or environmental events such as resuming from standby or losing network connection can cause problems for certain applications which expect to be always on and connected. So if you have a certain application which crashes or goes into “not responding” mode somewhat frequently and a restart is the only fix for it, we have a simple fix for you in the form of a customizable batch script to simply kill the application and restart it.

In addition to the obvious situation above, this script can be used for a variety of useful tasks, such as:

  • Easily restart an application by double-clicking or using a hot key.
  • Restart a program only when it is hung or not responding.
  • Run as a scheduled task to make sure an application is always running.
  • Anywhere else you want to automate conditional restarting of an application.

Customizing the script should be pretty self explanatory by the comments, so just configure the script appropriately and you are all set.

The Script

@ECHO OFF
ECHO Restart Application
ECHO Written by: Jason Faulkner
ECHO SysadminGeek.com
ECHO.
ECHO.

SETLOCAL EnableExtensions

REM Enter the application information.
SET AppName=Application Name
SET ExeFile=FileToLaunch.exe
SET ExePath=C:PathToApplication

REM Select the conditions to kill the application.
REM A value of 1 = Yes, 0 = No
SET KillIfRunning=1
SET KillIfNotResponding=1
SET KillIfUnknownStatus=1

REM Specify when to start the application:
REM 1 = Start only if the process was previous killed.
REM 0 = Start the application regardless.
SET StartOnlyIfKilled=1

SET KillStatus="%TEMP%KillStatus.tmp.txt"
SET Success=0

ECHO Killing existing %AppName% instance...
IF {%KillIfRunning%}=={1} CALL :CheckKillStatus "%ExeFile%" "RUNNING"
IF {%KillIfNotResponding%}=={1} CALL :CheckKillStatus "%ExeFile%" "NOT RESPONDING"
IF {%KillIfUnknownStatus%}=={1} CALL :CheckKillStatus "%ExeFile%" "UNKNOWN"
ECHO.

IF {%StartOnlyIfKilled%}=={1} (
	IF {%Success%}=={0} GOTO End
)
ECHO Restarting %AppName%...
START "%ExeFile%" "%ExePath%%ExeFile%"
ECHO.

IF EXIST %KillStatus% DEL /F /Q %KillStatus%

ENDLOCAL


:CheckKillStatus
ECHO Killing with status: %~2
TASKKILL /FI "STATUS eq %~2" /IM "%~1" /F > %KillStatus%
SET /P KillResult= < %KillStatus%
FOR /F "tokens=1,* delims=:" %%A IN ("%KillResult%") DO (
	ECHO %%A:%%B
	IF /I {%%A}=={SUCCESS} SET /A Success=%Success%+1
)


:End

Conclusion

While you can find applications out there which perform basically the same function, using a simple script such as this avoids having “yet another program” running in the background.

Jason Faulkner is a developer and IT professional who never has a hot cup of coffee far away. Interact with him on Google+

  • Published 08/27/10

Get Free Articles in Your Inbox!

Join 134,000 newsletter readers

Email:

Go check your email!