How to Automatically Remove Disabled AD Users from GAL in Exchange 2010

exchange-2010

When an employee leaves our organizations for any reason, currently we disable their AD account but do not immediately delete it. However, the problem with this is that these users still show up in the Global Address List.

I'm sure there is a PowerShell script to remove them but I would like to make things more streamlined.

I'm hoping somebody here might be able to provide a better way to go about disabling users which will automatically remove them from the GAL in the process.

So far I can think of two potential solutions.

  1. Create a script that runs a PS script every hour that will remove disabled users from the GAL.

  2. Use a PS command that will simultaneously disable a user and remove them from the GAL.

Option 2 is likely the better option so if somebody could assist with that, I would greatly appreciate it.

Thanks in advance.

Best Answer

No need to re-invent the wheel, found this elegant solution over at petri.co.il:

# http://www.petri.co.il/forums/showthread.php?p=109975 
# usage: Disable-User [accountname] [enable/disable]

function get-dn ($SAMName)    {
    $root = [ADSI]''
     $searcher = new-object System.DirectoryServices.DirectorySearcher($root)
    $searcher.filter = "(&(objectClass=user)(sAMAccountName= $SAMName))"
    $user = $searcher.findall()

    if ($user.count -gt 1)      {     
            $count = 0
                foreach($i in $user)            { 
            write-host $count ": " $i.path 
                    $count = $count + 1
                }

            $selection = Read-Host "Please select item: "
        return $user[$selection].path

          }      else      { 
          return $user[0].path
          }
}

$Name = $args[0]
$status = $args[1]
$path = get-dn $Name

if ($path -ne $null)    {

    "'" + $path + "'"  
    if ($status -match "enable")     {
        # Enable the account
        $account=[ADSI]$path
        $account.psbase.invokeset("AccountDisabled", "False")
        $account.setinfo()
        Set-Mailbox "$Name" -HiddenFromAddressListsEnabled $False
    }    else    {
        # Disable the account
        $account=[ADSI]$path
        $account.psbase.invokeset("AccountDisabled", "True")
        $account.setinfo()
        Set-Mailbox "$Name" -HiddenFromAddressListsEnabled $True
    }
}    else    {
    write-host "No user account found!" -foregroundcolor white -backgroundcolor red
}

Save it as Disable-User.ps1 and run .\Disable-User.ps1 SAMaccountname disable