Monitor Event Viewer Security Log – Powershell

These days, in a corporate environment, more people than you think have access to your PC. They could access it via RDP or even as a network path (ie. “\\your_pc\c$\Users\rafael\Documents\”). You wouldn’t even notice that last one.

This powershell script is going to monitor your Security Log in Event Viewer and email you in case the login accessing it is not listed as exception. You can setup a Scheduled Task to execute this script periodically.

 

#How often you will check
$date = (get-date).AddMinutes(-5)

#Add here every login that can be ignored (yours, System, your machine name followed by $, etc..)
$safelogins = @("SYSTEM","YOU_MACHINE_NAME`$", "Rafael.Goncalez")

#Log file with the events found
$path = "C:\Users\rafael.goncalez\Documents\external_access\events_$(Get-Date -format 'yyyyMMddHHmm').csv"

# Grab the LOGON events from a DC            
$Events = Get-WinEvent -ComputerName localhost -FilterHashtable @{Logname='Security';Id=4624; StartTime=$date}            
            
# Parse out the event message data            
ForEach ($Event in $Events) {  
          
    # Convert the event to XML            
    $eventXML = [xml]$Event.ToXml()
          
    # Iterate through each one of the XML message properties            
    For ($i=0; $i -lt $eventXML.Event.EventData.Data.Count; $i++) {            

        # Append these as object properties            
        Add-Member -InputObject $Event -MemberType NoteProperty -Force -Name  $eventXML.Event.EventData.Data[$i].name -Value $eventXML.Event.EventData.Data[$i].'#text'            
    }            
}            

$c = $Events | Select-Object TargetUserName, IpAddress, TimeCreated | ? {$safelogins -notcontains  $_.TargetUserName}  | Measure-Object

if ($c.Count -gt 0) {

# View the results with your favorite output method            
$Events | Select-Object * | ? {$safelogins -notcontains  $_.TargetUserName} | Export-Csv $path
#$Events | Select-Object TargetUserName, IpAddress, TimeCreated | ? {$safelogins -notcontains  $_.TargetUserName} # | Out-GridView 

# Send email with the log file attached
Send-MailMessage -To "youremail@email.com" -From "test@test.com" -Subject "Test mail" -SmtpServer "smtp_server_here" -Attachments $path

}

#Pause

 

Any question, please let me know. 🙂

Thanks.

Rafael.