If you’re familiar with LDAP searches you will probably at some point have been frustrated at the inability to exclude objects in a specific Organisational Unit, i.e “Give me all User objects in the domain, except those in the Sales OU”. To workaround the problem you typically need to do some scripting. There are several methods by which you exclude objects using Powershell, but I really like the one published by fellow MVP Ilya Sazonov.
Here’s an example using Ilya’s method. In this scenario the goal is to move all Contact objects not currently in the Contacts OU to the Contacts OU. To do this we have to first find all Contacts excluding those in the Contacts OU.
$conou = "OU=Contacts,DC=mydomain,dc=com" $exclcons = Get-ADObject -LDAPFilter "(objectclass=contact)" -SearchBase $conou ` | select -ExpandProperty distinguishedname $tomove = Get-ADObject -LDAPFilter "(objectclass=contact)" ` | ? {$exclcons -notcontains $_.DistinguishedName} foreach ($con in $tomove) { Move-ADObject -Identity $con -TargetPath $conou -Confirm:$false } # end foreach