Jeremy Stein - Brain

« »

Log batch file output

Say you have a batch file to restart a service and you want to run it periodically from a scheduled task. Here’s one way to do it:

restart.bat:
cd /d %~d0%~p0
echo %date% %time% %Username% > lastrun.log 2>&1
echo -- RUNNING %~d0%~p0restart_do_work.bat -- >> lastrun.log 2>&1
call restart_do_work.bat >> lastrun.log 2>&1
echo -- COMPLETED %~d0%~p0restart_do_work.bat -- >> lastrun.log 2>&1

restart_do_work.bat:
net stop "My Service" > netstop.output
if %errorlevel% equ 2 goto NOT_ADMIN
type netstop.output
findstr /c:"could not be stopped" netstop.output
if errorlevel 1 goto IT_STOPPED
taskkill /im myservice.exe /f
:IT_STOPPED
net start "My Service"
exit /b
:NOT_ADMIN
echo You appear to be running this with insufficient privileges.
exit /b 1

I use two batch files to make it easier to debug. Any output from the _do_work batch file will be stored in the log file. This includes the commands themselves, which shows where the batch file was when the error occurred.

July 19, 2012 No Comments.

No Comments

Be the first to comment!

Leave a Reply

Your email address will not be published. Required fields are marked *

Why ask?

« »