@echo off

rem A simple but effective script to check for unexpected reboots by comparing the date between expected and unexpected reboot 
rem events in the windows eventlog
rem This cmd uses wevtutil, which is only available as of Windows Vista and Windows 2008
rem If you want to check other event types, go lookup the ID in the eventlog and change the Number behind "EventID="
rem Credits to Tom Kerremans
rem License is GPL V2

wevtutil /? > NUL
IF %ERRORLEVEL% == 9009 goto NOWEVTUTIL
echo unknown > EXPECTED.txt
echo unknown > UNEXPECTED.txt

cmd /c "for /l %%l in (1,1,1) do @for /f "tokens=1,2* delims=:" %%a in ('wevtutil qe System /q:"*[System[(EventID=13)]]" /c:5 /f:text /rd:true^|find "Date"') do @ echo %%b:%%c > EXPECTED.txt && exit"
cmd /c "for /l %%l in (1,1,1) do @for /f "tokens=1,2* delims=:" %%a in ('wevtutil qe System /q:"*[System[(EventID=41)]]" /c:5 /f:text /rd:true^|find "Date"') do @ echo %%b:%%c > UNEXPECTED.txt && exit"
SET /p EXPECTED= <EXPECTED.txt
SET /p UNEXPECTED= <UNEXPECTED.txt
del /q EXPECTED.txt
del /q UNEXPECTED.txt

IF %EXPECTED% == unknown IF %UNEXPECTED% == unknown goto UNKNOWNREBOOT
IF %UNEXPECTED% == unknown goto OKREBOOT

IF  %UNEXPECTED% GTR %EXPECTED% goto UNEXPECTEDREBOOT
:OKREBOOT
echo Last reboot at %EXPECTED% was clean
exit 0
:UNKNOWNREBOOT
echo Last reboot is unknown
exit 0
:NOWEVTUTIL
echo "wevtutil to read eventlog not installed
exit 3
:UNEXPECTEDREBOOT
echo Unexpected reboot at %UNEXPECTED%
exit 2
:EOF