I'm trying to populate an Active Directory (AD) security group with computer objects from a specific Organizational Unit (OU). My current method is to get all the computers using `Get-ADComputer -filter * -SearchBase OU=blah,DC=example,dc=edu` and then add them to the group using a loop. But I've realized this process might be slow, especially since most of the computers are likely already members of the group after the first run. I've heard that using `Compare-Object` might speed things up, but I'm not sure if that's the case or if using `Add-ADGroupMember -Identity 'foo' -Members $computers` would be just as fast. Also, I need a solution that can remove computers that shouldn't be in the group anymore. Anyone have suggestions on methods that actually work?
6 Answers
Yes, the target should be that only the computers in your `$computers` variable are members of the 'foo' group. If you empty out the group first and then repopulate, it creates unnecessary churn, which is something to avoid.
I've used a similar method for a large domain with around 70,000 users. I recommend filtering down to just the distinguished names and querying those. It drastically reduced the time needed. You can even check the `memberof` attribute to efficiently handle removals.
There are several ways to handle this. You can definitely use `Compare-Object` to identify which computers need to be added or removed from the group. Just check what’s in the group and what you have in your `$computers` list. Where are you sourcing the data for adds and removes?
The source list is just all computers in the OU. It's frustrating that AD supports dynamic groups for users but not for computers.
Here’s a quick script you can try:
```powershell
$OU = "OU=Workstations,DC=example,DC=com"
$GroupDN = "CN=SpecialComputers,OU=Groups,DC=example,DC=com"
$Computers = Get-ADComputer -SearchBase $OU -LDAPFilter "(!(memberOf:1.2.840.113556.1.4.1941:=$GroupDN))"
Add-ADGroupMember -Identity $GroupDN -Members $Computers
```
This gets only the computers you need and should be more efficient.
You actually don't need to loop through each addition; you can just use the `-Members` parameter with `Add-ADGroupMember`. But I understand you're worried about performance. It might be slower, but you could try using `Compare-Object` to see if it makes a noticeable difference.
True, but the performance concern is valid when dealing with a lot of computers.
You might also want to consider not using object properties directly. Instead, just get the distinguished names of the computers. This approach could significantly speed up your operations and easily go beyond the default object limits AD imposes.

Exactly, it's about the desired state. Make sure that 'foo' just contains what's in `$computers`.