To provide a secure environment, it's critical to ensure that no unwanted Active Directory (AD) users or groups are added to authoritative AD groups.
Administrators can assign rights to specific users and control who can and cannot add and remove group members from essential groups, but it's still critical to monitor groups like Enterprise Admins and Domain Admins for new members. Using PowerShell, we can create a monitor to do just that.
Prerequisites for using PowerShell to monitor AD
If you'd like to follow along with this article, I'll be assuming a few things:
- You are working on a computer that's already joined to an Active Directory domain.
- You are logged in with a user with rights to read AD group memberships.
- You have the Remote Server Administration Tools (RSAT) package installed.
- You have an intermediate level of knowledge about PowerShell.
With those prerequisites out of the way, let's see how we can monitor AD groups for changes with PowerShell.
How to get started with using PowerShell to monitor AD
Creating an AD group monitor in PowerShell is a five-step process:
- Read the previous group membership.
- Read the current group membership.
- Store the current group membership.
- Compare group memberships.
- Take action.
First, we need to figure out how to read group memberships in PowerShell. The easiest way to do that is with the Get-AdGroupMember command in the ActiveDirectory PowerShell module. Using this command, we can pull out all of the group members. I'll be using the Domain Admins group as an example throughout this article.
Once we have the current list of members, we then need to store that list somewhere so we can read it later. I'll use a CSV file. Since I'd like to know when that membership is recorded, I'll also include the time.
Next, since I now have a CSV file to query, I can create some code to query the previous group membership. Below I'm querying our state file and finding the latest time the file has.
Next, I can create some code to compare the previous and current members and then run some code to take whatever action I need to if my monitor detects a difference in membership.
Once I have all of the steps in place, I can bring it all together in a script and run it.
When run, the script will then create a file called C:\DomainAdminGroupMemberShip.csv and C:\DomainAdminsGroupChanges.csv that will contain the list of group members every time the script is run and whether or not the group membership changed during that run.
Protecting your environment with PowerShell
Building an AD group membership monitor with PowerShell allows you to create a free, custom solution that's highly flexible and can easily be tuned to your environment. Once you have the script, this script can be executed at regular intervals using a Windows scheduled task or another execution engine of your choosing.