Search code examples
powershellactive-directoryget-winevent

How to Filter EventLog to get one log per a day - PowerShell


I wrote powershell script to get where specific user was logon. But I want to get only one result per a day.

The script is working perfectly, but gives a lot result per day.

Here is my script:

$StartDate = Get-Date -Year 2019 -Month 12 -Day 01 
$computers = Get-ADComputer -SearchBase 'ou=XXX,dc=XXX,dc=org,dc=XX' -Filter "Name -like 'XXXX*'" 
foreach ($comp in $computers) { 
    $Computer = $comp.Name 
    Get-WinEvent -max 3 -Computername $Computer -FilterHashtable @{LogName='Security';ID='4624' ;StartTime=$StartDate } | 
    where {($.Id -eq '4624') -and ($.properties[8].value -eq 3) -and ($.properties[5].value -eq 'XXXXX')} |
    select-Object -Property TimeCreated, MachineName , @{ Name = 'TargetUserName'; Expression = { $.Properties[5].Value } }
}

Solution

  • As commented, the code is missing the underscores for the $_ automatic variable.
    Also, I would advise to use .Date on the startDate to omit the time part, effectively settting it to midnight.

    # set the startdate, remove the time part so it wil be the date at midnight
    $StartDate = (Get-Date -Year 2019 -Month 12 -Day 01 ).Date
    $LogonUser = 'XXXXX'
    $computers = Get-ADComputer -SearchBase 'ou=XXX,dc=XXX,dc=org,dc=XX' -Filter "Name -like 'XXXX*'" 
    
    foreach ($comp in $computers) { 
        $Computer =  $comp.Name 
        Get-WinEvent -Computername $Computer -FilterHashtable @{LogName='Security';ID=4624;StartTime=$StartDate } | 
        Where-Object {($_.Properties[8].Value -eq 3) -and ($_.Properties[5].Value -eq $LogonUser) } |
        Select-Object -Property TimeCreated, MachineName, 
                                @{ Name = 'TargetUserName'; Expression = { $_.Properties[5].Value } } |
        Group-Object @{Expression = {$_.TimeCreated.Date}} | ForEach-Object { 
            $_.Group | Select-Object -First 1
        }
    

    For those wondering about the $_.Properties:

    $_.Properties[5].Value --> TargetUserName
    $_.Properties[8].Value --> LogonType. Value = 3 --> Network
    

    See: Audit logon events