Sep 13, 2006

Uptime on Windows

Here's a VBScript script which runs in the Windows Scripting Host and shows you how long your computer has been running:

strComputer = "."
Set objWMIService = GetObject("winmgmts:\\" & strComputer & "\root\cimv2")

Set colOses = objWMIService.ExecQuery("SELECT LastBootUpTime From Win32_OperatingSystem")
For Each objOs In colOses
diffMin = DateDiff("n", wmiDateStringToDate(objOs.LastBootUpTime), Now)
diffDays = Fix(diffMin / (60 * 24))
diffMin = diffMin - diffDays * 24 * 60
If diffDays >= 1 Then
uptimeStr = uptimeStr & CStr(diffDays) & "d "
End If
diffHours = Fix(diffMin / 60)
diffMin = diffMin - diffHours * 60
If diffHours >= 1 Then
uptimeStr = uptimeStr & CStr(diffHours) & "h "
End If
If diffMin >= 1 Then
uptimeStr = uptimeStr & CStr(diffMin) & "min"
End If

WScript.Echo "Uptime: " & uptimeStr

Function wmiDateStringToDate(dtmDate)
wmiDateStringToDate = CDate(Mid(dtmDate, 5, 2) & "/" & Mid(dtmDate, 7, 2) & "/" & Left(dtmDate, 4) & " " & Mid (dtmDate, 9, 2) & ":" & Mid(dtmDate, 11, 2) & ":" & Mid(dtmDate, 13, 2))
End Function

Save it as a VBS file and try running it. Because it runs in the Windows Scripting Host, the uptime script can (generally) be run just by double-clicking on the file in Windows. If that doesn't work, somehow Windows' connection between the VBS file format and the WScript.exe program has been severed, and you'll have to run WScript.exe with the script name as an argument.

The script is basically my current fascination with the Windows scripting environment. There's a lot of documentation available, especially the Microsoft Windows 2000 Scripting Guide, which has been the most useful to me in understanding Windows' built-in scripting architecture.

Other ideas on what to do with this tool are kind of floating around in my head right now: using it to automatically download and tabulate exchange rates from Yahoo, then analysing the data with Excel; recording system uptime and usage statistics like how often and how long I use the computer; creating a script to quickly log in to Windows (Live?) Messenger and send a message to someone; rewriting the sparklines document in straight VBScript to run in the Windows Scripting Host environment, instead of having to open up the sparklines.doc document every time I want to create some sparklines.

All pretty cool ideas, at least from my point of view. And beyond them I might even look into accessing the Windows common controls and trying to create real graphical programs using just WSH. But that's in the far future.