Background:

So I was at a customers location and well we got talking about scripts. They had the need for a script that populates a group if the user has a cellphone number configured and remove him the number is removed after. They had already a script that did it. The script did what was needed but I felt there was room for improvement, so I got rid of a try catch where the catch was empty. That is just as bad as ON ERROR RESUME NEXT from the old VBScript days. Anyway I thought later there has got to be a better way of doing this.

The old way:

This is a compressed version written from memory.

Get-ADUSer -Filter {mobile -ne ''}|{Try{Add-AdgroupMember -Identity GroupA -Member $_}Catch{}}
Get-ADGroupMember GroupA|Get-ADUser -properties mobile|Where{$_.mobile -eq $Null}|ForEach{Remove-ADGroupMember -Identity GroupA -Members $_}

The improved way:

So why not just be happy. Well there is still performance improvements and let the DC do the heavy lifting. Lets start using LDAPFilter.

$GroupDN=Get-ADGroup GroupA|Select-Object -ExpandProperty DistinguishedName
#Start by adding all members that have a mobile number but not member of the group.
Add-ADGroupMember -Identity $GroupDN -Members (Get-ADUser -LDAPFilter "(&(mobile=*)(!(memberof=$GroupDN)))")
#Then remove all group members that dont have a mobile number.
Remove-ADGroupMember -Identity $GroupDN -Members (Get-ADUser -LDAPFilter "(&(!(mobile=*))(memberof=$GroupDN))") -Confirm:$False

But I only want user from one part of my AD

Okay so now we got new requirements of course but that is really simple. Lets just instruct the Get-ADUser to search only in one part using SearchBase.

Get-ADUser -Searchbase 'OU=Company,DC=domain,DC=tld' -LDAPFilter .....

So just add the searchbase parameter and path.