WMIC LastBootUptime格式问题:需输出重启后总天数、小时数、分钟数
纯CMD实现计算计算机上次重启时长(天/小时/分钟)
以下是完全基于CMD的解决方案,无需依赖PowerShell,可输出你需要的X Days - Y Hours - Z Minutes格式:
@echo off setlocal enabledelayedexpansion :: 获取系统上次启动时间(截取UTC时间的核心部分) for /f "skip=1 tokens=1 delims=." %%a in ('wmic os get lastbootuptime') do ( set "boot_time=%%a" goto get_current_time ) :get_current_time :: 获取当前系统时间(同样截取核心时间部分) for /f "skip=1 tokens=1 delims=." %%a in ('wmic os get localdatetime') do ( set "current_time=%%a" goto calculate_diff ) :calculate_diff :: 解析启动时间的年/月/日/时/分 set "boot_year=!boot_time:~0,4!" set "boot_month=!boot_time:~4,2!" set "boot_day=!boot_time:~6,2!" set "boot_hour=!boot_time:~8,2!" set "boot_minute=!boot_time:~10,2!" :: 解析当前时间的年/月/日/时/分 set "curr_year=!current_time:~0,4!" set "curr_month=!current_time:~4,2!" set "curr_day=!current_time:~6,2!" set "curr_hour=!current_time:~8,2!" set "curr_minute=!current_time:~10,2!" :: 将时间转换为从1970年开始的总分钟数(简化计算,忽略闰年,误差可忽略) set /a "boot_total=(boot_year-1970)*525600 + (boot_month-1)*43800 + (boot_day-1)*1440 + boot_hour*60 + boot_minute" set /a "curr_total=(curr_year-1970)*525600 + (curr_month-1)*43800 + (curr_day-1)*1440 + curr_hour*60 + curr_minute" :: 计算时间差(总分钟数) set /a "diff_minutes=curr_total - boot_total" :: 分解为天、小时、分钟 set /a "days=diff_minutes / 1440" set /a "remaining=diff_minutes %% 1440" set /a "hours=remaining / 60" set /a "minutes=remaining %% 60" :: 按要求格式输出 echo %days% Days - %hours% Hours - %minutes% Minutes endlocal
关键说明:
- 代码通过
wmic获取系统启动时间和当前时间,截取掉WMIC输出的冗余后缀(如.000000+000)。 - 采用将时间转换为总分钟数的方式计算差值,逻辑简单且适配CMD的整数运算特性。
- 忽略闰年的简化计算,对于重启时长的场景来说误差极小(最多1天),如果需要完全精确的闰年处理,可以额外添加闰年判断逻辑,但会增加代码复杂度。
- 如果需要查询远程计算机,只需修改
wmic命令为:wmic /node:远程主机名 /USER:用户名 /PASSWORD:密码 os get lastbootuptime和对应的localdatetime命令。
内容的提问来源于stack exchange,提问作者Hakan DAŞTAN
相关产品推荐
相关产品推荐

