johnnyb
johnnyb

Reputation: 1815

Identify first and last event from an event log .net or powershell

I am trying to find the first and last event timestamp in offline evtx files. I am trying to use the EventLogReader.Seek Method (SeekOrigin, Int64) with powershell. I know how to find the Events based on event id as below.

$reader = [Diagnostics.Eventing.Reader.EventLogReader]::new(
    [Diagnostics.Eventing.Reader.EventLogQuery]::new($eventLogPath,
        [Diagnostics.Eventing.Reader.PathType]::FilePath, $query)
)

how would I find the first and last events in a query similar to above? Thanks

Upvotes: 2

Views: 1732

Answers (1)

Mathias R. Jessen
Mathias R. Jessen

Reputation: 174445

$reader will read from the oldest to the newest event by default, unless the ReverseDirection property on the EventLogQuery object is set to $true:

# create default reader
$queryObject = [Diagnostics.Eventing.Reader.EventLogQuery]::new($eventLogPath, 'FilePath', $query)
$forwardReader = [Diagnostics.Eventing.Reader.EventLogReader]::new($queryObject)

# read oldest event
$oldestEvent = $forwardReader.ReadEvent()

# Now change the query direction and create a new reader
$queryObject.ReverseDirection = $true
$reverseReader = [Diagnostics.Eventing.Reader.EventLogReader]::new($queryObject)

# read the newest event
$newestEvent = $forwardReader.ReadEvent()

There is no need to do any of the above manually though, you can use the Get-WinEvent cmdlet instead:

$oldestEvent = Get-WinEvent -Path $eventLogPath -FilterXPath $query -MaxEvents 1 -Oldest 
$newestEvent = Get-WinEvent -Path $eventLogPath -FilterXPath $query -MaxEvents 1

Upvotes: 2

Related Questions