Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Filtering for newest security event records

Tags:

powershell

I found some really nice code on how to display user logins from the past 14 days: Powershell Security Log Get-EventLog

$Date = [DateTime]::Now.AddDays(-14)
$Date.tostring("MM-dd-yyyy"), $env:Computername
$eventList = @()
Get-EventLog "Security" -After $Date `
    | Where -FilterScript {$_.EventID -eq 4624 -and $_.ReplacementStrings[4].Length -gt 10 -and $_.ReplacementStrings[5] -notlike "*$"} `
    | foreach-Object {
        $row = "" | Select UserName, LoginTime
        $row.UserName = $_.ReplacementStrings[5]
        $row.LoginTime = $_.TimeGenerated
        $eventList += $row
      }
$eventList

But my question is, how do I modify this code so that it selects the two newest records?

I tried the following:

Get-EventLog "Security" -After $Date `
| Where -FilterScript {$_.EventID -eq 4624 -and $_.ReplacementStrings[4].Length -gt 10 -and $_.ReplacementStrings[5] -notlike "*$"} `
| {-Newest 2} 

And I get the error: Missing expression after unary operator '-'.

What is a clean way to get the last two logins, i.e. current login and the last person who logged in before the current user?

EDIT:Issue solved, here is complete code

$Date = [DateTime]::Now.AddDays(-14)
$Date.tostring("MM-dd-yyyy"), $env:Computername
$eventList = @()
Get-EventLog "Security" -After $Date `
    | Where -FilterScript {$_.EventID -eq 4624 -and $_.ReplacementStrings[4].Length -gt 10 -and $_.ReplacementStrings[5] -notlike "*$"} `
    | Select-Object -First 2 `
    | foreach-Object {
        $row = "" | Select UserName, LoginTime
        $row.UserName = $_.ReplacementStrings[5]
        $row.LoginTime = $_.TimeGenerated
        $eventList += $row
        }
$eventList
like image 694
Glowie Avatar asked Jan 22 '26 16:01

Glowie


1 Answers

Instead of:

| {-Newest 2} 

Try this:

| Select-Object -first 2
like image 161
TheOptimusPrimus Avatar answered Jan 25 '26 00:01

TheOptimusPrimus



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!