Extracting information from Event Log 'Message'?

Welcome Forums General PowerShell Q&A Extracting information from Event Log 'Message'?

This topic contains 5 replies, has 3 voices, and was last updated by

 
Member
5 years, 3 months ago.

  • Author
    Posts
  • #12209

    Participant
    Points: 1
    Rank: Member

    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

    Participant
    Points: 0
    Rank: Member

    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

    Participant
    Points: 0
    Rank: Member

    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

    Member
    Points: 0
    Rank: Member

    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

    Participant
    Points: 0
    Rank: Member

    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

    Member
    Points: 0
    Rank: Member

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

The topic ‘Extracting information from Event Log 'Message'?’ is closed to new replies.

denizli escort samsun escort muğla escort ataşehir escort kuşadası escort