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

Advertisements
This entry was posted in Active Directory, Active Directory Domain Services, Audit Logs, Domain Controller, Event Logs, PowerShell, PowerShell 3.0, Powershell 4.0, Windows Server 2008 R2 Backup, Windows Server 2012, Windows Server 2012 R2 and tagged , , , . Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s