How to clear the mail attribute using PowerShell

I have been struggling to delete the value in the mail attribute after a mailbox has been deleted. Exchange populates the mail attribute when a mailbox is created (even though Exchange has no use for the attribute), but doesn’t clear the attribute when the mailbox is deleted. With ADUC integration removed in Exchange 2007, a quick way to know if an account has a mailbox is to look at the mail attribute. But if removing a mailbox no longer clears that attribute, it is difficult know (just by looking at a user account in ADUC) if the account still has a mailbox.

Since Exchange doesn’t use the mail attribute, you can’t use the Set-Mailbox attribute, especially if the mailbox is deleted anyway. I tried using Set-User with the -WindowsEmailAddress parameter, but because the data type is Microsoft.Exchange.Data.SmtpAddress, setting the value to "" or $null doesn’t work because those aren’t properly formatted SMTP addresses.

So, I figured I needed to get away from any Exchange cmdlet. I used PowerShell’s native support for ADSI to bind to the user object: New-Object DirectoryServices.DirectoryEntry "LDAP://UserDN". But you will get an error if you try to set the attribute to null ($user.mail = $null). You can set it to an empty value (""), but you will then get an error when you try to commit the change: $user.SetInfo().

How can you possibly clear this attribute, one that is so easy to do in ADUC just by deleting the value in it? It is necessary to fall back to the PutEx method. Using that will let you use the ADS_PROPERTY_CLEAR constant (indicated by the numeric one in the first argument). It has taken me days to finally get to this point, so hopefully this post will shorten that time for others trying to do the same thing.

4 thoughts on “How to clear the mail attribute using PowerShell

  1. Thank you very much. Already spent a day before finding it. I made a tweak to your code so that I can pick the attribute to clear. Just provide DN and property to clear.

    Function Clear_Property {
    If (($args[0]).length -gt 1) {
    $userDN = $args[0] ; $Prop2clear = $args[1]
    $ldapDN = “LDAP://” + $userDN
    $adUser = New-Object DirectoryServices.DirectoryEntry $ldapDN
    $adUser.PutEx(1, $Prop2clear, $null)
    $adUser.SetInfo()
    “Cleared the value of $Prop2clear in the account $userDN” }
    If (($args[0]).length -lt 2) {
    ‘Usage: Clear_Property $DN $Property2Clear’ }
    }

    Thanks,
    Kirt Carson

Leave a Reply

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

*