Extracting information from Event Log 'Message'?

This topic contains 5 replies, has 3 voices, and was last updated by Profile photo of Dave Wyatt Dave Wyatt 3 years, 6 months ago.

  • Author
    Posts
  • #12209
    Profile photo of thickgit
    thickgit
    Participant

    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?

  • #12213
    Profile photo of Robert Westerlund
    Robert Westerlund
    Participant

    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)

  • #12214
    Profile photo of Robert Westerlund
    Robert Westerlund
    Participant

    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.

  • #12215
    Profile photo of Dave Wyatt
    Dave Wyatt
    Moderator

    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]
    }
    
  • #12216
    Profile photo of Robert Westerlund
    Robert Westerlund
    Participant

    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?

  • #12217
    Profile photo of Dave Wyatt
    Dave Wyatt
    Moderator

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

You must be logged in to reply to this topic.