ADDynamicMembership is a PowerShell script that dynamically manages membership of Active Directory Organizational Units (OUs) or groups based on user-defined rules. These rules are written as PowerShell-style filters and stored in a specified attribute of the target containers.
Because objects in Active Directory can belong to only one OU, the script ensures that objects which no longer match a destination OUβs filter are moved back to their appropriate default containers, depending on their object class:
- Users ->
CN=Users,DC=... - Groups ->
CN=Users,DC=... - Computers ->
CN=Computers,DC=... - OUs -> Not moved
π‘ Tip: Schedule this script to run periodically (e.g., every 5 minutes) for near real-time updates and dynamic membership management.
Filters must follow this structure:
<property> <operator> '<value>'- Property: The AD attribute to evaluate (e.g.,
DisplayName,objectClass,distinguishedName) - Operator: A valid PowerShell comparison operator (e.g.,
-eq,-like) Learn more about PowerShell comparison operators - Value: The comparison value, always enclosed in single quotes (
'value')
- Do not wrap the entire filter in double quotes.
- Filters can be combined using logical operators like
-andand-or.
- Match objects where the name starts with
john:
name -like 'john*'- Match computers currently in the Sales OU:
objectClass -eq 'computer' -and distinguishedName -like '*OU=Sales,DC=Contoso,DC=Com'| Parameter | Description |
|---|---|
-Attribute |
The name of the AD attribute that contains the membership filter (default is extensionName). |
-LogPath |
Path where the main script log file will be saved. |
-CsvLogPath |
Path to save the CSV-formatted detailed log. |
-CsvDelimiter |
Delimiter used in the CSV file (default is comma ,). |
The script generates two types of log files:
.logfile: Contains a summary of the scriptβs execution, including actions and any errors..csvfile: A detailed table of every membership change applied during the run.
By default, logs are saved to:
C:\Windows\Temp\AdDynamicMembershipLogs are automatically rotated daily.
- Download the latest version of the script from this Github repository.
- Run it manually in PowerShell or create a scheduled task to run it at regular intervals.
Letβs say you want to move computers named SALES-PCXX from the default Computers container to the Sales OU.
- Go to the Sales OU and set the membership filter in the
extensionNameattribute (or the attribute you defined via-Attributeparameter):
distinguishedName -like 'CN=SALES-PC*,CN=Computers,DC=contoso,DC=com'- Run the script:
.\ADDynamicMembership.ps1- Use meaningful and specific filters to avoid misclassification of AD objects.
- Always test your filters in a non-production environment.
- Schedule regular script execution using Task Scheduler or another automation tool for continuous synchronization.