Fist of Tech

Simple PowerShell Active Directory group monitoring.

This post is about a simple solution to monitor active directory group changes using PowerShell. Please note, this is not the best practice and will only give you insight about a new member or if a member was removed from a group.

The best practice way to monitor group membership changes is to change the “Audit Security Group Management” audit policy. There you want to monitor the events 4728, 4732 and 4756. After that those events will tell you who made the change. Including which group was changed and who the new member is. More here from the Microsoft docs.

But if you just want to monitor a single group for changes. Things like ContosoJondoe has been added to the group of the domain admins. Then this is the right post for you. So to monitor Active Directory groups with PowerShell I use the following script:

$GroupToMonitor = "MyTestGroup" #Which group to monitor
$WaitingTimeBetweenScans = 600 #Time between checks
#This function just helps to compare the group members
function Get-ADGroupMemberArray($GroupName) {
    $Array = New-Object System.Collections.ArrayList
    $Users = Get-ADGroupMember -Identity $GroupName
    foreach ($user in $Users) {
        $Array.Add($user) | Out-Null
    return , $Array  
#Initial fetching of the user
$RefObj = Get-ADGroupMemberArray -GroupName $GroupToMonitor
while ($true) {
    #Fetching users of the group
    $DiffObj = Get-ADGroupMemberArray -GroupName $GroupToMonitor
    $Result = Compare-Object  -ReferenceObject $RefObj -DifferenceObject $DiffObj
 <#Since Compare-Object returns nothing when the objects match,
 we only check when there is a string in $Result#>
    if (![string]::IsNullOrEmpty($Result)) {
        <#Sometimes it is nice to know where your script is running,
         when not using a central server for all your scripts.#>
        $Body = "Script running on $env:COMPUTERNAME `r`n " 
        foreach ($Line in $Result) {
            if ($Line.Sideindicator -like "<=") { #Someone was removed
                $Message = "$(Get-Date -Format G)`tUser: $($`tGroup: $GroupToMonitor`taction: Removed`r`n"                 
                $Body += $Message
            elseif ($line.sideindicator -like "=>") { #Someone was added
                $Message = "$(Get-Date -Format G)`tUser: $($`tGroup: $GroupToMonitor`taction: Added`r`n"    
                $Body += $Message
        $Body = $Body
        $Subject = "Active Directory Group Change detected"
        $From = ""
        $To = ""
        $SMTPServer = ""      
        Send-MailMessage -From $From -Subject $Subject -Body $Body -To $To -SmtpServer $SMTPServer -Encoding UTF8
        $RefObj = Get-ADGroupMemberArray -GroupName $GroupToMonitor
    Start-Sleep -Seconds $WaitingTimeBetweenScans

Active Directory is like a mad monkey.

Zen Master xiakit

Exit mobile version