Active Directory: PowerShell Notification of change in membership of important AD security groups
Issue
Need to monitor particular AD security groups for when the membership list changed. for example if you specifically wanted to know when somebody was added or removed from the Domain Admins group.
Solution
Below is a copy of the PowerShell script I used to accomplish the goal.
Create an AD service account, and create a scheduled task to run every 20 minutes on a trusted server.
The script uses a cache of data stored in CSV files on the local disk of the server to monitor for changes, when it detects a change between the most recent data and the live data it notifies a selected email address, and cycles the files into an archive format, although this is a little crude it allowed me to achieve my goal with little effort.
Script
#Send mail function Function send_mail([string]$message,[string]$subject) { $emailFrom = "ADReports@adatum.com" $emailTo = "it.technical@adatum.com" $smtpServer = "smtp.adatum.com" Send-MailMessage -SmtpServer $smtpServer -To $emailTo -From $emailFrom -Subject $subject -Body $message -BodyAsHtml -Priority High} CLS import-module ActiveDirectory Get-ADGroupMember -identity "Domain Admins" | where {$_.objectclass -eq "User"} | Export-csv c:\DAdminWatcher\dadmins_live.csv $result = Compare-Object $(Get-Content c:\DAdminWatcher\dadmins_live.csv) $(Get-Content c:\DAdminWatcher\dadmins_recent.csv) if ($result -eq $null) { write-host 'No Changes Found' } else{write-host 'Changes found in the Domain Admins Group!' write-host $result $now = get-date -format ddMMMyyhhmmss $NewFileName = 'dadmins_' + '.' + $now rename-item c:\DAdminWatcher\dadmins_recent.csv $NewFileName rename-item c:\Dadminwatcher\dadmins_live.csv dadmins_recent.csv $tests = $result -split '"' if ($result.sideindicator -eq '=>'){ $EmailBody = "A Change has been detected in the Domain Admins Group User " + $tests[3] + " Removed"} else{ $EmailBody = "A Change has been detected in the Domain Admins Group User " + $tests[3] + " Added"} send_mail $EmailBody "Change to Domain Admins"}