Windows OS Hub
  • Windows
    • Windows 11
    • Windows Server 2022
    • Windows 10
    • Windows Server 2019
    • Windows Server 2016
  • Microsoft
    • Active Directory (AD DS)
    • Group Policies (GPOs)
    • Exchange Server
    • Azure and Microsoft 365
    • Microsoft Office
  • Virtualization
    • VMware
    • Hyper-V
  • PowerShell
  • Linux
  • Home
  • About

Windows OS Hub

  • Windows
    • Windows 11
    • Windows Server 2022
    • Windows 10
    • Windows Server 2019
    • Windows Server 2016
  • Microsoft
    • Active Directory (AD DS)
    • Group Policies (GPOs)
    • Exchange Server
    • Azure and Microsoft 365
    • Microsoft Office
  • Virtualization
    • VMware
    • Hyper-V
  • PowerShell
  • Linux

 Windows OS Hub / Active Directory / Implementing Dynamic Groups in Active Directory with PowerShell

October 3, 2024

Implementing Dynamic Groups in Active Directory with PowerShell

When managing access permissions to different resources in an Active Directory domain, an administrator may need to create dynamic security user groups. The idea of a dynamic group is that its membership is automatically formed based on the user’s properties. For example, a group with all users from a specific location (city, OU); users from a certain department or with a specific job title, etc. Users should be automatically added to or removed from such a dynamic membership group based on the current values of their attributes.

On-premises Active Directory doesn’t support dynamic security groups, unlike the cloud Entra ID directory (formerly Azure AD). If you have an on-premises Exchange Server, you can create Dynamic Distribution Groups, but these objects are not security groups and cannot be used for access control purposes.

In this article, we will look at how to implement dynamic groups in AD using a PowerShell script. Such a PowerShell script should run on a schedule, select users from AD based on a certain criterion, add them to a target AD group, and remove users from the group that no longer meet the criteria.

The following PowerShell script automatically adds all users from the specified OUs that have Sales specified in the (Department) field in AD to the target security group.

# Your AD domain name
$ADDomain = 'dc=woshub,dc=com'
# Dynamic group name
$ADGroupname = 'EastSales'
# OU list to search users
$ADOUs = @(
"OU=Users,OU=NewYork,$ADDomain",
"OU=Users,OU=Chicago,$ADDomain"
)
# Department name
$DepartName="Sales"
$users = @()
# Search for users from the target department in the specified OUs
foreach($OU in $ADOUs){
$users += Get-ADUser -SearchBase $OU -Filter {Department -like $DepartName}
}
# Add users to the target security group
foreach($user in $users){
Add-ADGroupMember -Identity $ADGroupname $user.samaccountname -ErrorAction SilentlyContinue
}
# Check that all group members meet the criteria.
# If not (user has been moved to another OU, the Department field has been changed), they must be removed from the group.
$members = Get-ADGroupMember -Identity $ADGroupname
foreach($member in $members) {
$UserOU=($member.distinguishedname -split ',', 2)[1]
if ($ADOUs -notcontains $UserOU){Remove-ADGroupMember -Identity $ADGroupname -Member $member.samaccountname -Confirm:$false}
if ((Get-ADUser -identity $member -properties Department|Select-Object Department).department -notlike $DepartName ){Remove-ADGroupMember -Identity $ADGroupname -Member $member.samaccountname -Confirm:$false}
}

In some cases, it is easier to clear group membership each time the script runs, rather than removing users that are no longer relevant. Simply add the following line at the top of the script:

Get-ADGroup $ADGroupname | Set-ADGroup -Clear member

PowerShell script: to automate Active Directory Dynamic group memberships

The following PowerShell Active Directory module cmdlets are used in the script:

  • Get-ADUser – get user information
  • Add-ADGroupMember, Get-ADGroupMember, and Remove-ADGroupMember — manage AD group membership

To implement dynamic groups that contain computer objects, use the Get-ADComputer cmdlet.

Run the script and make sure that all users from the specified OUs with ‘Sales’ in the Department field have been automatically added to the EastSales group. Any user who doesn’t match these criteria will be removed from the group. implementing Dynamic AD Security groups with powershell

Create a scheduled task that runs the specified PowerShell script on the domain controller to update the dynamic group membership regularly (for example, twice a day).

Specify the task parameters:

Program/script: powershell.exe
Add arguments (optional): -ExecutionPolicy Bypass -NonInteractive -WindowStyle Hidden -File "C:\PS\update_dynamic_group_eastsales.ps1"

run sheduled powershell script on a domain controller

It is not recommended to run scheduled scripts as a domain administrator. It is better to create a non-admin user account and delegate AD group management privileges to it, or use a gMSA service account.

This PowerShell script can be used as the basis for creating your own dynamic security group rules in AD.

11 comments
5
Facebook Twitter Google + Pinterest
Active DirectoryPowerShell
previous post
How to Stop an Unresponsive (Stuck) Virtual Machine on VMware ESXi
next post
How to Measure Storage Performance and IOPS on Windows

Related Reading

Get-ADDomainController: Getting Domain Controllers Info via PowerShell

July 8, 2022

Backing Up Active Directory with Windows Server Backup

November 26, 2024

Unable to Access SYSVOL and NETLOGON folders from...

May 10, 2023

Generating Strong Random Password with PowerShell

January 31, 2020

Transferring/Seizing FSMO Roles to Another Domain Controller

March 15, 2024

Restoring Active Directory Domain Controller from a Backup

January 31, 2025

Creating Desktop Shortcuts using Group Policy (GPO)

January 16, 2025

How to Deploy Certificates to Computers Using Group...

February 27, 2024

11 comments

Limey December 5, 2019 - 7:11 pm

You have a slight typo in Lines 20 and 28 and 32 “-Member” instead of “-Members”, at least that’s what it took for me to get it to work.
Thanks, this is fantastic. I just manually created a group last week and this took 10 minutes to do the same task.

Reply
admin January 15, 2020 - 9:40 am

Indeed, there was a mistake. Thanks!

Reply
Michael Guthrie May 19, 2020 - 6:53 pm

I just wanted to say thanks! I just used this to create and populate groups for computers instead of users. Worked like a charm. I am assuming that the typo mentioned by LIMEY is actually fixed in your post as it did not trip me up whatsoever. MANY THANKS!

Reply
Kuriakose December 16, 2022 - 3:18 am

Could you please share your script for the dynamic computer group?
Thanks

Reply
serg January 9, 2023 - 4:02 am

For example, you need to create a dynamic AD group based on OU. Just replace Get-AdUser to Get-ADComputer in the source script.

## Your AD domain name
$ADDomain = ‘dc=woshub,dc=com’
## Dynamic group name
$ADGroupname = ‘EastSalesComps’
## OU list to search computers
$ADOUs = @(
“OU=computers,OU=NewYork,$ADDomain”,
“OU=computers,OU=Chicago,$ADDomain”
)
$computers = @()
# Searching computers in the specified OUs
foreach($OU in $ADOUs){
$computers += Get-ADComputer -SearchBase $OU -Filter *
}
foreach($computer in $computers)
{
Add-ADGroupMember -Identity $ADGroupname -Members $computer.samaccountname -ErrorAction SilentlyContinue
}
## Make sure that each computer in the group meets the selection criteria. If not (moved to another OU), they must be removed from the group
$members = Get-ADGroupMember -Identity $ADGroupname
foreach($member in $members)
{
if($member.distinguishedname -notlike “*OU=computers,OU=NewYork,$ADDomain*” -and $member.distinguishedname -notlike “*OU=computers,OU=Chicago,$ADDomain*”)
{
Remove-ADGroupMember -Identity $ADGroupname -Members $member.samaccountname -Confirm:$false
}
}

Reply
NickS March 10, 2022 - 4:35 pm

This script works great thank you.
How can add more than 1 attribute?
I tried -like “***” or “***” but it doesn’t like it.
Can you give me a pointer please?

Reply
admin March 11, 2022 - 7:19 am

Use the following syntax:
(Attribute1 -like “***”) -or (attribute2 -like “***”) -or (attribute3 -like “***”)

Reply
NickS May 9, 2022 - 11:29 am

Hi
The issue I have is that I want to create a group that consists of a location and a department.
The script keeps failing on parameter names

1st part of the script:
)
$users = @()
# Searching users in the specified OUs
foreach($OU in $ADOUs){
$users += Get-ADUser -SearchBase $OU -Filter {Department -like “Finance”} -and {l -like “London”}
}

2nd part of the script:
Remove-ADGroupMember -Identity $ADGroupname -Members $member.samaccountname -Confirm:$false
}
if ((Get-ADUser -identity $member -properties Department|Select-Object Department).department -notlike “Finance” ) -and ((Get-ADUser -identity $member -properties l|Select-Object l).l -notlike “London” )
{
Remove-ADGroupMember -Identity $ADGroupname -Members $member.samaccountname -Confirm:$false
}
}

Any help would be greatly appreciated, Thank you

Reply
NickS May 9, 2022 - 1:23 pm

Also, many thanks for taking the time before. I have only just seen this. Thank you

Reply
Jason Knowles August 29, 2023 - 9:42 pm

This was extremely helpful! While testing, I noticed that Get-ADUser -SearchBase is recursive to child OUs, which is what I needed, but RemoveADGroupMember is not recursive, so it doesn’t remove users that were in child OUs. This may be a little brute force, but I decided to clear the group membership near the start of the script so each time it runs, it removes all users and generates a fresh membership rather than remove users that are no longer applicable.
$ADGroupname = ‘EastSales’
Get-ADGroup $ADGroupname | Set-ADGroup -Clear member
I also grabbed a piece from a Microsoft example so Disabled users are not added to the group. I modified this line:
$users += Get-ADUser -LDAPFilter ‘(!userAccountControl:1.2.840.113556.1.4.803:=2)’ -SearchBase $OU -Filter {Department -like “Sales”}

Reply
Mark F December 5, 2023 - 4:38 pm

Love the script but I want to get hold of users via the Office field. I have tried physicalDeliveryOfficeName but it does not work, any ideas?

Reply

Leave a Comment Cancel Reply

join us telegram channel https://t.me/woshub
Join WindowsHub Telegram channel to get the latest updates!

Recent Posts

  • Map a Network Drive over SSH (SSHFS) in Windows

    May 13, 2025
  • Configure NTP Time Source for Active Directory Domain

    May 6, 2025
  • Cannot Install Network Adapter Drivers on Windows Server

    April 29, 2025
  • Change BIOS from Legacy to UEFI without Reinstalling Windows

    April 21, 2025
  • How to Prefer IPv4 over IPv6 in Windows Networks

    April 9, 2025
  • Load Drivers from WinPE or Recovery CMD

    March 26, 2025
  • How to Block Common (Weak) Passwords in Active Directory

    March 25, 2025
  • Fix: The referenced assembly could not be found error (0x80073701) on Windows

    March 17, 2025
  • Exclude a Specific User or Computer from Group Policy

    March 12, 2025
  • AD Domain Join: Computer Account Re-use Blocked

    March 11, 2025

Follow us

  • Facebook
  • Twitter
  • Telegram
Popular Posts
  • Using WMI Filters to Target Group Policies in Active Directory
  • Set Desktop Wallpaper and Logon Screen Background via Group Policy
  • How to Set a User Thumbnail Photo in Active Directory
  • Restoring Active Directory Domain Controller from a Backup
  • Windows: Block Remote Network Access for Local User Accounts
  • Configuring Password Expiration Notifications for AD Users
  • Backing Up Active Directory with Windows Server Backup
Footer Logo

@2014 - 2024 - Windows OS Hub. All about operating systems for sysadmins


Back To Top