powershell get-eventlog add if more than 5 times

265 Views Asked by At

I am using:

"%windir%\system32\WindowsPowerShell\v1.0\powershell.exe" $log=Get-EventLog -LogName Security -InstanceID  4625 -After (Get-Date).AddDays(-60); if (($log)) {Write-Output $log[0].Message} ELSE {Write-Output 'WARNING-NoEventFound'} 

This works perfect for me. I want to expand if possible and say write the output if the event happened more than 5 times. Similar to:

Count(*) > 5 that I would use in SQL.

1

There are 1 best solutions below

1
tomasmu On

I'd like to mention an alternative to Get-EventLog: Get-WinEvent

It usually has a lot better performance, both locally and over the network, it can do server side filtering with -FilterHashTable before sending the results. This can come in handy since Active Directory logs can be quite large sometimes.

Since you're only interested in if it's >5 results or not, we can also speed it up by breaking early when we have found 6 results, using -MaxEvents, and then just check whether we found 6 events or not.

$maxEvents = 6
$filterHashtable = @{
    LogName   = 'Security'
    Id        = 4625
    StartTime = (Get-Date).AddDays(-60)
}

$log = Get-WinEvent -FilterHashtable $filterHashtable -MaxEvents $maxEvents
if ($log.Count -ge $maxEvents) {
    #your code here

For readability I prefer to have the hashtable in a variable, but it can also be written inline like this, with ; as separator for the key value pairs:

Get-WinEvent -FilterHashtable @{ LogName = 'Security'; Id = ... }