|
Answer» i WANT a batch file to log when programs have been closed or opened my logic is sound but my batch file doesn't log can someone tell me why and how to fix it
Code: [Select]:ECHO OFF if not exist log.csv goto setup :LOOP IF EXIST 2.dat GOTO COPY TASKLIST >temp.dat for /f "skip=2" %%a in (temp.dat) do echo %%a >>1.dat del temp.dat sleep 15 TASKLIST >temp.dat for /f "skip=2" %%a in (temp.dat) do echo %%a >>2.dat del temp.dat for /f %%a in (1.dat) do ( type 2.dat |find "%%a" echo %errorlevel%==1 >>temp.txt if %errorlevel%==1 echo %%a,%time%,started >>log.csv ) for /f %%a in (2.dat) do ( type 1.dat |find "%%a" echo %errorlevel%==1 >>temp.txt if %errorlevel%==1 echo %%a,%time%,closed >>log.csv ) :copy del 1.dat ren 2.dat 1.dat goto loop :setup echo %DATE%-%time% >log.csv echo Name,Time,start or end? >>log.csv goto loop Nobody's as surprised as me that this works. The problem is the timing in that jobs can start and stop within the sleep frame and never be seen by this code. A better solution would be VBScript which has classes for this very purpose.
Code: [Select]echo off
:reset del tlist?.txt > nul for /f "tokens=1" %%i in ('tasklist /nh') do echo %%i >> tlistA.txt sleep 15 for /f "tokens=1" %%i in ('tasklist /nh') do echo %%i >> tlistB.txt :terminate for /f "tokens=1" %%i in (tlistA.txt) do ( find "%%i" tlistB.txt > nul if errorlevel 1 echo TASK Terminated: %date% %time% %%i ) :startup for /f "tokens=1" %%i in (tlistB.txt) do ( find "%%i" tlistA.txt > nul if errorlevel 1 echo Task Started: %date% %time% %%i ) goto reset
When you write code try and keep it simple. Add some white space (blank lines) and indent constructs such as for and if and code under a :label. There is no rule that your code must fit on the back of a postage stamp.
Good LUCK.
|