@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
命令使用的選項。我們需要跳過標題行(skip=1
),並分割使用的空間和點作爲分隔符(delims=.
)的下一行,所以我們必須
v vv v delimiters
20170417110928.382430+120 20170505132724.993000+120
1 = %%a 2 3 = %%b 4 tokens
通過reqesting令牌1和3,我們檢索兩個時間戳爲%%a
(指示for
替換參數)和%%b
(下一個替換參數),我們將存入兩個變量來後只選擇日期(我們不能做替換參數的子字符串操作)。作爲wmic
命令的輸出也包含結束空行,一個if
命令被用來防止處理那些行。
使用兩個時間戳,我們只需要檢索並比較前八個字符(yyyymmdd
)以查看上次啓動日期和當前日期是否匹配。如果沒有,重啓。
編輯看來我沒誤會指示小時。上面的代碼處理00:00
/12:00 midnight
情況。對於12:00 noon
情況
@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
要找出最後的引導時,請看看這裏:我如何才能找到當Windows上次重新啓動?(https://superuser.com/q/523726/146810 )答案中列出了幾種不同的方法。 – Matt