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
Instead of:
| {-Newest 2}
Try this:
| Select-Object -first 2
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With