0

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.

Rolando
  • 1
  • 1

1 Answers1

2

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 = ... }
tomasmu
  • 21
  • 2
  • hey sorry for the late response, thanks for the update. This also helped. The reason I was using Get-EventLog is when I try to use Get-WinEvent on 2003 and 2008 non R2 servers, it would fail on me. When I ran your Get-WinEvent command, it worked perfect on our 2012-2016 servers. Thanks again. – Rolando Jan 10 '19 at 15:00