@echo off
setlocal enableextensions disabledelayedexpansion
for /f "skip=1 tokens=1,3 delims=. " %%a in ('
"wmic os get LastBootUpTime,LocalDateTime"
') do if not "%%b"=="" (
set "bootUpTime=%%a"
set "currentTime=%%b"
)
rem If last reboot was not today, reboot
if not "%bootUpTime:~0,8%"=="%currentTime:~0,8%" (
shutdown /r /f /t 60
) else (
echo No reboot required
)
for /f
명령은 마지막 부팅 시간과 현지 시간을 검색 할 wmic
명령 줄 도구를 실행합니다. 사용 된 쿼리의 출력 형식은
LastBootUpTime LocalDateTime
20170417110928.382430+120 20170505132724.993000+120
이 출력은 for /f
명령에 사용되는 옵션을 결정합니다. 우리는 우리가 (%%a
에 두 시간 기록을 조회 헤더 라인 (skip=1
)를 건너 뛸 필요가 있고, 구분 기호 (delims=.
)와 같은 공백과 점을 사용하여 다음 줄을 분할, 그래서 우리는 토큰 1과 3을 reqesting하여
v vv v delimiters
20170417110928.382430+120 20170505132724.993000+120
1 = %%a 2 3 = %%b 4 tokens
이 표시된
for
교체 가능 매개 변수) 및
%%b
(다음 교체 가능 매개 변수)을 사용하여 나중에 날짜 만 선택할 수 있도록 두 개의 변수에 저장합니다 (교체 가능한 매개 변수에 대해 하위 문자열 조작을 수행 할 수 없음).
wmic
명령의 출력에도
공백 행이 포함되어 있으므로
if
명령을 사용하여 해당 행을 처리하지 못하도록합니다.
두 개의 타임 스탬프를 사용하면 첫 번째 8 자 (yyyymmdd
)를 검색하고 비교하여 마지막 부팅 날짜와 현재 날짜가 일치하는지 확인하면됩니다. 그렇지 않은 경우 재부팅하십시오.
수정 됨 표시된 시간을 잘못 이해 한 것으로 보입니다. 이전 코드는 00:00
/12:00 midnight
사례를 처리합니다.
@echo off
setlocal enableextensions disabledelayedexpansion
for /f "skip=1 tokens=1,3 delims=. " %%a in ('
"wmic os get LastBootUpTime,LocalDateTime"
') do if not "%%b"=="" (
set "bootUpTime=%%a"
set "currentTime=%%b"
)
rem Calc how many days since last reboot
call :julianDate %currentTime:~0,4% %currentTime:~4,2% %currentTime:~6,2% ct
call :julianDate %bootUpTime:~0,4% %bootUpTime:~4,2% %bootUpTime:~6,2% bt
set /a "upTimeDays=ct-bt"
rem Assume we do not have to reboot and check
set "requireReboot="
rem last reboot was today
if %upTimeDays% equ 0 (
if "%currentTime:~8,6%" gtr "120000" if "%bootUpTime:~8,6%" lss "120000" set "requireReboot=1"
rem last reboot was yesterday
) else if %upTimeDays% equ 1 (
if "%bootUpTime:~8,6%" lss "120000" set "requireReboot=1"
if "%currentTime:~8,6%" gtr "120000" set "requireReboot=1"
rem last reboot was more than one day before
) else (
set "requireReboot=1"
)
if defined requireReboot (
echo shutdown /r /f /t 60
) else (
echo No reboot required
)
goto :eof
:julianDate year month day returnVar
setlocal enableextensions disabledelayedexpansion
set /a "d=100%~3%%100, m=100%~2%%100, a=(14-m)/12, y=%~1+4800-a, m=m+12*a-3"
set /a "jd=d+(153*m+2)/5+365*y+y/4-y/100+y/400-32045"
endlocal & set "%~4=%jd%" & goto :eof
마지막 부팅 시간을 확인하려면 경우
12:00 noon
를 들어, 여기 봐주십시오 : [Windows가 다시 시작 마지막 때 내가 알 수 있습니까?] (https://superuser.com/q/523726/146810) 답변에 나열된 두 가지 접근 방식이 있습니다. – Matt