Clean Deleted Users from Shared Mailbox Folder Permissions

I don’t know about you, but it really bugs me to see dead accounts in the ACLs of mailbox folders. I wrote this PowerShell script to clean them up whenever I see them. It gets a list of all of the folders in a mailbox, checks each one for any permissions entries where the username = “NT User:S-1*”, and removes those entries, leaving all others alone.

Remove deleted users from mailbox folder permission ACLs

As always, your mileage may vary. Use at your own discretion.

Remove deleted users from mailbox folder permission ACLs

Just change the value of $MyDC to one of your domain controllers and run this script from within the Exchange Management Console.

# Usage: 
# clean_perms <SharedMailbox>
# Where <SharedMailbox> is the SamAccountName, UPN, alias, or 
# PrimarySMTPAddress of any mailbox.

# Return an error if no mailbox or user name was entered.
    [string]$Mailbox = `
        $(throw "No value entered for the shared mailbox identity.")

$MyDC = ""
$Mbx = (Get-Mailbox $Mailbox -DomainController $MyDC -ea SilentlyContinue)

# Run if the mailbox name is valid.
if ($Mbx) {
    # Remove any permissions on the mailbox root for non-existent users.
    $Root = $Mailbox+":\"
    $RootPerm = (Get-MailboxFolderPermission $Root -DomainController $MyDC `
        | ?{$_.User -like "NT User:S-1*"}) 
    if ($RootPerm) {
        $RootPerm | foreach {
            $RootUser = $_.User.DisplayName
            Remove-MailboxFolderPermission $Root -User $RootUser -Confirm:$False
    # Get a list of all other mailbox folders. Skips
    # folders that usually cause errors or that don't matter.
    $MBXFolders = (Get-MailboxFolderStatistics $Mailbox -DomainController $MyDC `
        | ?{($_.FolderPath -ne "/Top of Information Store") -and ($_.FolderPath `
        -ne "/Recoverable Items") -and ($_.FolderPath -ne "/Deletions") `
        -and ($_.FolderPath -ne "/Purges") -and ($_.FolderPath -ne "/Versions")})

    # For each folder in the mailbox, find and remove any permission 
    # entries for dead users.
    ForEach($Folder in $MBXFolders) {
        $FolderPath = $Mailbox + ":" + $Folder.FolderPath.Replace("/","\")
        $Perm = (Get-MailboxFolderPermission $FolderPath -DomainController $MyDC `
            | ?{$_.User -like "NT User:S-1*"}) 
        if ($Perm) {
            $Perm | foreach {
                $User = $_.User.DisplayName
                Remove-MailboxFolderPermission $FolderPath -User $User `
#Display an error if the mailbox is not valid.
else {Write-Host "Mailbox $Mailbox not found." -ForegroundColor Red}

…and, of course, it should work on any kind of mailbox, not just shared mailboxes.

Leave a Reply

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