Author Posts

December 28, 2013 at 3:27 am

Not sure if this is doable....

If you run

Get-EventLog -Logname System -InstanceID 2147489661 -Newest 1

you'll get the latest 'uptime' event from the System Event Log (w2k8/Windows 7).

Is it possible to extract the number of seconds from the 'Message' property and assign them to a variable? (i.e. 'The system uptime is 43 seconds')

For example, I'd like to be able to say something along the lines of "if $seconds -ge 10800" then to reboot the machine/send an alert etc?

December 28, 2013 at 10:49 am

Assuming that it is a server you're looking at (i.e. you don't have to consider sleep/hibernate), you could get the system uptime very easily, using WMI. Just compare the LastBootUpTime on Win32_OperatingSystem with the current date. A sample below:

$bootupTime = (Get-CimInstance Win32_OperatingSystem).LastBootUpTime
$uptime = New-TimeSpan -Start $bootupTime -End (Get-Date)

December 28, 2013 at 1:48 pm

Of course, if you really wanted to get the information from the eventlog, you could just run a regular expression on the Message property of the event log entry (assuming that the string never changes format (or language) in any way).

(get-eventlog -LogName system -InstanceId 2147489661 -Newest 1).Message -match "(?\d+)"
$uptimeInSeconds = $Matches["seconds"]

But I think I would rather use the WMI objects (the previous post) instead of parsing it from a string from the eventlog.

December 28, 2013 at 7:59 pm

Event log messages are basically a template with some number of "replacement strings" (think: parameters). In the case of the event that you're working with, the number of seconds is stored in index 4 of the ReplacementStrings array:

$event = Get-EventLog -Logname System -InstanceID 2147489661 -Newest 1
if ($event)
{
    $seconds = $event.ReplacementStrings[4]
}

December 29, 2013 at 4:22 am

Ahh, I wasn't aware it worked using ReplacementStrings. That approach is way better than regexing the Message. Thanks for correcting! Myself, I still prefer the WMI approach, though. Which approach would you have used, Dave?

December 29, 2013 at 5:35 am

For system uptime, I'd be using WMI as well.