Batch – Reboot Computer if Up Time Greater than 5 Days

email me

This is how you would use day-in-year (like 272/365) to judge whether or not a computer has been rebooted in the last 5  days. To make the comparison, I use WMIC OS GET LASTBOOTUPTIME and WMIC OS GET LOCALDATETIME, with some DTS translation. So, it’s basically (today’s day-in-year) minus (uptime day-in-year) = x.

Screenshot

Computer up for 14 days

Computer was rebooted today

 

Script

@echo off
setlocal EnableDelayedExpansion
title Computer Reboot
cls

echo Reboot if computer has greater than 5 up days
echo.
echo Subtracts Up Time from Today, using day in year
echo.
echo.



::UP TIME
::returns timestamp in long format - not very usable as is
for /f %%A in ('WMIC OS GET LASTBOOTUPTIME ^| find "."') DO set DTS=%%A
::return day in year of up time date
call :SUB1
set DayInYear1=%dayYear%

::TODAY
::returns timestamp in long format - not very usable as is
for /f %%B in ('WMIC OS GET LOCALDATETIME ^| find "."') DO set DTS=%%B
::return day in year of today
call :SUB1
set DayInYear2=%dayYear%


::MATH
set Bool=NO
echo DayInYear1: %DayInYear1%
echo DayInYear2: %DayInYear2%
echo Math: %DayInYear2% - %DayInYear1% = X
:: do the math between days in year
set /A Answer=%DayInYear2%-%DayInYear1%
echo How many days since last reboot: %Answer%
echo.
:: if greater than 5, REBOOT computer
if %Answer% GTR 5 set Bool=YES
echo Reboot computer? %bool%

echo.
pause

if %bool% EQU YES goto SUB2

exit

:SUB1
:: RETURN DAY IN YEAR
:: Check end of month days
set /A i=0, daySum=0
for %%C in (31 28 31 30 31 30 31 31 30 31 30 31) do (
   set /A i+=1
   set /A dayCount[!i!]=daySum, daySum+=%%C
)
::uses DTS, long timestamp to extrapolate discrete elements
set /A month=1%DTS:~4,2%-100, day=1%DTS:~6,2%-100
set /A yMOD4=%DTS:~0,4% %% 4
set /A yMOD100=%DTS:~0,4% %% 100, yMOD400=%DTS:~0,4% %% 400
set /A dayYear=!dayCount[%month%]!+day
::checking feb for day 29
if %month% gtr 2 (
::checks for leap year
if %yMOD4% equ 0 set /A dayYear+=1
if %yMOD400% neq 0 if %yMOD100% equ 0 set /A dayYear-=1
)
endlocal & set dayYear=%dayYear%
GOTO:EOF

:SUB2
::RUN SHUTDOWN
:: 900 seconds = 15 minutes
start "" shutdown -r -f -t 900 -c "Please save any open work. Your computer will restart in 15 minutes for weekly scheduled maintenance."
exit