显示系统运行时间
strcomputer ="." Set dtmConvertedDate = CreateObject("WbemScripting.SWbemDateTime") Set objWMIService = GetObject("winmgmts:" _ & "{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2") Set colOperatingSystems = objWMIService.ExecQuery _ ("Select * from Win32_OperatingSystem") For Each objOS in colOperatingSystems dtmConvertedDate.Value = objOS.LastBootUpTime dtmLastBootUpTime = dtmConvertedDate.GetVarDate dtmSystemUptime = stoHMS(datediff("s", dtmLastBootUpTime, now)) WScript.Echo dtmSystemUptime Next Function StoHMS(Sec) H = Int(Sec/3600) :H1 = Sec Mod 3600 :M = Int(H1/60) :S = H1 Mod 60 StoHMS = H & "小时" & M & "分钟" & S &"秒" End Function
该例还可简化为for each objOS in GetObject("winmgmts:").InstancesOf ("Win32_OperatingSystem") Next
再来个AHK版的
For objOS In ComObjGet("winmgmts:\\").InstancesOf("Win32_OperatingSystem") { temp := objOS.LastBootUpTime StringLeft, dtmLastBootUpTime, temp, 14 dtmSystemUpTime := %A_Now% EnvSub, dtmSystemUpTime, %dtmLastBootUpTime%, Seconds Sec := dtmSystemUpTime H := Sec//3600 H1 := Mod(Sec,3600) M := H1//60 S := Mod(H1,60) MsgBox %H%小时%M%分钟%S%秒 }
再来个调用Win32_NTLogEvent查寻最近开关机时间
If (Lcase(Right(Wscript.FullName,11)) = "wscript.exe") Then CreateObject("WScript.Shell").Run("%Comspec% /C " &Chr(34)&"mode con cols=100&Cscript.exe //NoLogo "&Chr(34)& Wscript.ScriptFullName &Chr(34)&"&&(Echo 此窗口40秒后自动关闭...&Ping -n 40 127.0.1>nul&Exit)"&Chr(34)),3:Wscript.Quit Wscript.Quit End If Set WMI = GetObject("winmgmts:{impersonationLevel=impersonate}!\\.\root\cimv2") Set colLoggedEvents = WMI.ExecQuery("Select * from Win32_NTLogEvent Where Logfile = 'System' And EventCode = '6005' Or EventCode = '6006' Or EventCode = '6008'") For Each objEvent In colLoggedEvents Flag = Flag + 1 If Flag = 1 Then Wscript.Echo "本次开机时间: " & UTCtoNow(objEvent.TimeWritten) ElseIf (Flag Mod 2) = 0 Then G = UTCtoNow(objEvent.TimeWritten) Else K = UTCtoNow(objEvent.TimeWritten) Wscript.Echo "前次开机:"&K&" "&vbTab&"对应关机:"&G&" "&vbTab& "运行时长:" &StoHMS(DateDiff("s", K, G)) End If Next Function UTCtoNow(nD) If Not IsNull(nD) Then Set SWDT = CreateObject("WbemScripting.SWbemDateTime") SWDT.Value = nD UTCtoNow = SWDT.GetVarDate(True) End If End Function Function StoHMS(Sec) H = Int(Sec/3600) :H1 = Sec Mod 3600:M = Int(H1/60) :S = H1 Mod 60 StoHMS = H & "小时" & M & "分钟" & S &"秒" End Function