18 March 2017

Batch file logfile pattern for scheduled Tasks

Batch file logfile pattern for scheduled Tasks

A simple and robust pattern for generating a log file when creating a scheduled task batchfile is the following. If you set a double  >> %log%  at the first reference to %log% the log file will not be emptied but will just grow with the job.

The result is a file called the same as the task:



 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
@echo off
if not DEFINED bin (
  set bin=%~dp0
)
set log="%bin%%~nx0.log"
title %~nx0

rem Resetting the log for each run because it otherwise will grow to large
echo %date% (%time:~0,8%) Starting %~nx0 ---------------- > %log%
echo. >> %log%
echo Running automated sms reminder service for vagter in flyveklubben >> %log%
echo. >> %log%

D:\Tasks\Flyveklub-Reminder-Service\Reminder-Service.exe 12 >> %log%

rem IF ERRORLEVEL statements should be read as IF Errorlevel >= number 
if %errorlevel% EQU 0 echo Success & goto:end >> %log%

echo Error occured see %~nx0.log (sending email to it support) >> %log%
%bin%bmail -s localhost -t my@mail.dk -f my@mail.dk -a "%COMPUTERNAME% %~nx0 exit code %errorlevel%" -h -m "%log%" -c 

:end
echo. >> %log%
echo %date% (%time:~0,8%) Ending %~nx0---------------- >> %log%

GOTO :EOF
bmail is a command line mailer that sends the log file as attachment to the mail specified.

No comments: