Powershell: How to pull Event Viewer message and time

Viewed 136

I am trying to pull users out of the logoff events within security. Using the below code I can pull the usernames but I am not sure how to modify it to pull the time from the event log as well?

Many thanks

$events = get-eventlog -logname Security -instanceid 4634 -Newest 5 
  foreach ($ev in $events) {
     $me = $ev.Message   -match "(Account Name:).*"  
     if ($me) {  
         $matches[0] 

     }                                                        
  }
1 Answers

I'm not exactly sure what you are attempting to do. However, Get-EventLog is deprecated in favor of Get-WinEvent which is faster and has much better filtering options, and example may look something like this:

$FilterHash = @{
    LogName = 'Security'
    Id      = 4624
}

Get-WinEvent -FilterHashtable $FilterHash -MaxEvents 5 |
ForEach-Object{
    If($_.Properties[1].Value -eq $me) {
        Write-Host "Account Name : ($_.Properties[1].Value)"
    }
}

The -FilterHashtable parameter is the most popular, but there are also -FilterXPath and -FilterXML params you can look at in the documentation.

Important: In my case, I didn't have 4634 events. The property value and array position can be determined by looking at the XML view of a given log entry in Event Viewer. Just look under then and count the array indices from 0.

Another way to do that is to just isolate a single entry and echo the properties to the screen, and again just count to get the right index number. This is important because different info may be in different positions in different events etc.

Get-WinEvent is really robust. I strongly recommend taking a look at the documentation!

Related