Cannot remove AD user with nested leaf objects

Whilst working on some Microsoft Exchange and ActiveSync device Powershell scripts recently, I came across a problem where I could not delete an active directory user even after the ActiveSync device had been removed.

The particular error was, “The directory service can perform the requested operation only on a leaf object.”

This was because the ActiveSync device was created as a container object under the user object and to get around this, I simply looked up and removed the container using Remove-ADObject.

The following code should give you enough information to get the process going:

# Find and remove the ActiveSync device
Get-ActiveSyncDevice -Organization $organization -Mailbox $mailboxName \
| Remove-ActiveSyncDevice -Confirm:$false
# Remove the child objects
$adUser = Get-AdUser -Identity $mailbox.DistinguishedName
Get-AdObject -Filter * -SearchScope oneLevel -SearchBase $adUser.DistinguishedName \
| Remove-AdObject -Recursive -Confirm:$false
# Remove the AD user
Get-AdUser -Filter { EmailAddress -eq  $mailbox.UserPrincipalName } \
| Remove-AdUser -Confirm:$false

For formatting, I’ve split the longs lines using the “\” character.

Leave a Reply

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


You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre lang="" line="" escaped="" highlight="">