Powershell search for Active Directory objects excluding an OU

By | November 25, 2012

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

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.