PowerShell Script Monitors Security Logs and Sends Email Alerts.

I wrote this PowerShell script to send email alerts when Active Directory User Account, Security and Distribution Group Management events occur in the Security logs.A few parameters will need to be edited to adapt the script to any Active Directory domain environment.Also, the script will not work on Windows Server 2003 Active Directory Domain Controllers because the “FilterHashtable” parameter of the Get-WinEvent cmdlet is not supported. The domain controllers have to be atleast Windows Server 2008 level. The domain controller names are hard coded into the script and assigned to a variable, the server names could also be passed to a variable using a text or csv file.

Using the split() method of a string object, I extracted a line of text/substring from a single event message property.I further cleaned up the extracted string object by removing the return and line space elements to present it in a format suitable for the Send-MailMessage cmdlet Subject parameter.


function Get-ADAuditLogsv2{

## PowerShell AD Audit Alerts ##
## Charles Chukwudozie ##
## 11/1/2014

Param ($from = "adaudits@labdomain.net",
$smtpserver="10.0.0.16",
$to="infrastructure@labdomain.net",
$servers = ("DC01"),
$eventids = @(4720,4729,4727,4728,4726,4756,4761),
$date = ((Get-Date).AddMinutes(-60))

)
$ErrorActionPreference= 'silentlycontinue'
foreach ($server in $servers){
foreach ($eventid in $eventids) {

$events = Get-WinEvent -FilterHashtable @{logname='security';id=$eventid;StartTime=$date} -ComputerName $server
if ($events -ne $null){
foreach ($event in $events){
$eventmessage=$event.message.split("`n")[0..16]
$eventsubject=$event.message.split("`n")[0]
$eventsubject=$eventsubject.replace("`n", "")
$eventsubject=$eventsubject.replace("`r", "")
$timecreated=$event.timecreated
$body = @($timecreated,$eventmessage )| Out-String
$subject= "Event ID" + " " + $eventid + " " + $eventsubject
Send-MailMessage -Body $body -From $from -SmtpServer $smtpserver -Subject $subject -To $to
}
}

}

}
Get-Date | Out-File c:\errorlog.txt -Append -Force
$Error | Out-File c:\errorlog.txt -Append -Force
}
Get-ADAuditLogsv2

3 responses to “PowerShell Script Monitors Security Logs and Sends Email Alerts.”

  1. Anthony Lee Avatar
    Anthony Lee

    How do you get this to run on only a single new event? I’ve got it scheduled to run every 15 minutes and it pumps through a ton of email based on the IDs rather than only sending the newly created event.

  2. jbernec Avatar

    Hello Anthony,
    You would have to filter by just the relevant event ID. Thanks for stopping by.

  3. Tigran Melikyan Avatar
    Tigran Melikyan

    “The String is missing the terminator” after $eventsubject. Is there a chance that’s because script was created on older version of PS? I am using PS v3

Leave a reply to jbernec Cancel reply

Chinny Chukwudozie, Cloud Solutions.

Passion for all things Cloud Technology.