3

I'm trying to find the oldest retained Event in the Security Event Log through powershell.

Using the following command: (Get-EventLog Security | Sort-Object -Property Time -Descending)

This returns a list which is not sorted in the least. What am I doing wrong here?

Leander
  • 47
  • 4
  • 1
    `Time` isn't a property of events at all. Unfortunately `Sort-Object` doesn't care; `Sort-Object -Property Banana` will give you the same result. Even if this *did* work, though, it could be very slow if the security log is large. Try `(Get-WinEvent -LogName Security -Oldest -MaxEvents 1).TimeCreated` instead. – Jeroen Mostert Aug 02 '18 at 16:27
  • It would be helpful if PowerShell would inform the user that the property does not exist. – lit Aug 02 '18 at 18:54
  • 1
    @lit Pretty sure this is pertinent https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.core/set-strictmode?view=powershell-6 – Matt Aug 03 '18 at 02:04

2 Answers2

4

This is not a problem with Get-EventLog, but caused by the fact that the output of Get-EventLog does not have a Porperty Time.

Use Get-Member to show a list of available properties.

Get-EventLog | Get-Member

You'll see, that there is a TimeGenerated property, which you can use.

Get-EventLog Security | Sort-Object -Property TimeGenerated -Descending

Furthermore I'd like to add, that that's the default order anyway. But if you want to switch the order, I recommend using Get-WinEvent instead, which has a -Oldest switch.

Get-WinEvent -LogName Security -Oldest
vrdse
  • 2,899
  • 10
  • 20
3

"Time" is a generated string for output purposes not a datetime object so the sorting that is happening isn't chronological but non-existent.

Looking at the DotNetTypes.format.ps1xml you will see that it is using a formatted version of the TimeGenerated property.

<TableColumnHeader>
    <Label>Time</Label>
    <Width>13</Width>
</TableColumnHeader>
...
...
<PropertyName>TimeGenerated</PropertyName>
<FormatString>{0:MMM} {0:dd} {0:HH}:{0:mm}</FormatString>

This is done to have friendlier default output with the caveat of issues like the one you are having.

So, sort-object was "working" with a null value hence the lack of visible change.

Either way use the property TimeGenerated property instead

Matt
  • 45,022
  • 8
  • 78
  • 119