r/PowerShell • u/staze • Apr 25 '26
Improving efficiency of AD group membership from powershell and AD attributes
I have a script that runs every hour that updates some AD groups based on things like Department, Location, and a few other attributes set on computer objects.
It is, annoyingly slow (takes over 8 minutes to run).
The issue I think is for each group, I'm having to do something silly (this is just an example):
Get-ADComputer -Filter * -SearchBase $OU -properties MemberOf | where-object {[string]$_.MemberOf -notlike "*$GROUP*"} | ForEach-Object {try {Add-ADPrincipalGroupMembership -Identity $_ -MemberOf $GROUP -Credential $cred} catch { write-warning "Computer $_ moved or disappeared while processing..." }}
Get-ADGroupMember -Identity $ALLCOMPUTERS | Where-Object {$_.distinguishedName -notlike "*$OU*"} | ForEach-Object {try {Remove-ADPrincipalGroupMembership -Identity $_ -MemberOf $GROUP -Confirm:$false -Credential $cred} catch { write-warning "Computer $_ moved or disappeared while processing..." }}
Basically, add all the members then remove everyone that shouldn't be there (they got moved to some other OU).
I can probably shorten a lot of this by just doing once
Get-ADComputer -Filter * -Properties name,department,location,memberOf -SearchBase "OU=Computers,DC=example,DC=edu"
Then just work within that.
Though actually... Get-ADGroupMember may be the culprit for the slowness. So maybe just using something like this instead of the removal piece
Get-ADGroup -Identity $ALLCOMPUTERS | Where-Object {$_ -notlike "*$OU*"} | ForEach-Object {try {Remove-ADGroupMember -Identity $_ -MemberOf $GROUP -Confirm:$false -Credential $cred} catch { write-warning "Computer $_ moved or disappeared while processing..." }}
Also looks like I'm using Add and Remove-ADPrincipalGroupMembership instead of just Add-ADGroupMember and Remove-ADGroupMember... not sure if there's a performance difference there. Ideally I'd skip that if the computer was already a member of the group, but I'm unsure how to check that efficiently. I'm also not entirely sure it matters that much?
I guess the main question here is, does someone already have something similar to this?
Otherwise I'm thinking pull list of computers and their memberships. Then for each group, check if computer already a member (get-adgroup seems pretty speedy), and check membership. Then for groups that are location based, remove the member if the location is wrong, or department groups remove if department is wrong. I looked into some of the performance stuff a while back and compare-object, but not sure it made that big of a difference (other than some nice log output).
2
u/PinchesTheCrab Apr 25 '26 edited Apr 25 '26
I'd experiment with filters more. Bear in mind properties like Manager, DirectReports, Member, and Memberof are valid filter parameters.
All computers in a specific OU which are not a member of a specific group:
Bear in mind too that add-adgroupmember doesn't care if a computer is already in a group, so you could even just make a CSV of groups and filters:
Note that when you filter on properties you don't actually need to retrieve them. This is about letting your DC do the work and reducing the data it has to send to you.
For the love of God though, test this first because I'm writing this on my personal computer without the AD module available.
7
u/justaguyonthebus Apr 25 '26
You might be able to do something clever with last modified date so you don't have to reprocess everything every time
1
u/Verukins Apr 25 '26
Hey - so my understanding based on what you have said is to
- Update (add or remove) group memberships for AD computers based on atttributes on the objects that may have been updated
Your efficiency gains can come from
- Only look at computer objects updated in the last 24 hours... less objects to process - as i imagine most objects dont change that often .e.g
$24Hours = (Get-Date).AddHours(-24)
Get-ADComputer -Filter {WhenChanged -ge $24Hours} -SearchBase $OU -Properties MemberOf
- use an LDAP filter to determine if its a group member already or not, dont pull the memberships for everything then determine... e.g.
Get-ADComputer -LDAPFilter "(&(objectClass=computer)(whenChanged>=$24Hours)(!memberOf=$GROUP_DN))" -SearchBase $OU
6
u/DonL314 Apr 25 '26 edited Apr 25 '26
You should use the Add- and Remove-AdGroupMember - then you'd only have to do a single invocation to each, instead of doing 1 change per member. (You can pass arrays to those cmdlets)
Just do like
Write-Host (get-date);
Inside your ForEaches, then you can see what actually takes time.
Ah. And I noticed that you try to remove each and every AD object from the group, no matter of it's member or not. That's time consuming. Maybe do something like
(Written on my phone, so not tested. Just an idea. )
2
u/zrv433 Apr 25 '26 edited Apr 25 '26
Which segments are taking the most time? Add some debug statements to see.
https://www.tutorialspoint.com/article/how-to-use-stopwatch-in-powershell
If you're looping enough, -Ne $groupDN may be a little faster than -NotLike *$GROUP*
Build the lists of which objects to add/remove. Do not add/remove within a foreach loop. Only invoke add/remove once (per task) after the loop has built the list of objects to be changed.
At a quick glance, it seems like your task is to ensure all computers within a certain Ou are within a certain group?
If speed is the goal, the logic and therefore execution time may be faster if:
Be sure to observe the only invoke once logic I mentioned with this method.
2
u/BlackV Apr 25 '26
do all those computers need to be in the list? then add them all regardless, does not matter if they're in there or not
You can get 2 list of computers one or all computer and 1 of the ones in a group, then filter using those in memory object
Then add to the group in 1 go
You're are making 1 change 300 times instead of 300 items in 1 change
Using the filter parameter can also improve times vs the where object
2
u/odwulf Apr 25 '26
In my last life, I regularly had to script AD modifications on hundreds if not thousands of users and computers, and yes, it can easily become very long to process. That being said:
What's costly in time is to make a request to AD, you want to lessen the number of those. Your first line basically says : here's a computer, add it to the group. Here's another computer, add it to the same group. Here's another, add it..."
Add-ADGroupMember takes an array for the Members parameter. Try to remove the ForEach:
You can re-add the condition about the DistinguishedName in the computers selection, but I think AD is sufficiently optimized internally for it not to make a difference, it will not try to add what's already there.
Now for your second line: you are selecting the computers in the group based on their DistinguishedName. You DON'T NEED to ask AD for the full object just to extract that DistinguishedName, that's what's already in the Members property of the group. Similarly to the first request, Remove-ADGroupMember takes an array of ADPrincipals for its Members parameter, and the DistinguishedName should be enough to be considered an ADPrincipal. So: Get your group, including its members, select the members you want to remove, and ask for a bulk removal:
By doing so, you should be able to lessen the numbers of requests to AD from several per computer down to four.
Keep two things in mind:
1
u/Mesmerise Apr 25 '26
What about simply:
Set-ADGroup <GROUP> -Clear memberAnd then add members to the group.
1
u/purplemonkeymad Apr 25 '26
I can't parse your logic from what you have posted but in general you want to pull both memberships, store them, then compare the list with something like Compare-Object so you can get only the differences ie:
Then you know items with a side indicator of <= need to be added and => need to be removed, (Add- and Remove- both take lists so this can be done in a two ad requests, instead of the number of computers.)
If you have relativity few computers (<~3000) you can probably just pull any that have a location and filter for each location after getting the full list. Store the full list in a variable so you don't have to pull it multiple times! For ad you really want to reduce the number of calls to commands as each will one will do a request to a DC.
0
u/BrettStah Apr 25 '26
This is something nowadays to just ask Claude, Copilot, ChatGPT, etc. You'll get a pretty good response on this type of question with example code to review, then test in non-prod of course.