Some common scenarios where you might want to remove an old domain:
- An SMB deployment of Exchange Server where a .local domain was added as the first domain for email addresses.
- Old GroupWise addresses are left in place from an older migration.
- Obsolete domain left over from a company merger many years ago
A few things to note:
- You need to set $RemovePattern to identify the domain to be removed. Any email addresses matching this pattern will be removed from proxyAddresses attribute in Active Directory objects.
- The script uses Get-ADObject rather than Get-ADUser to make sure that the domain is removed from distribution groups too.
- This version of the script is capable of removing multiple instances of a matching email address. So, if a user has several email addresses in the old domain, all of them are removed.
- At the end of the script, I use Write-Progress to display a status bar. It's not necessary, but if there is a large number of users it's nice to see activity on the screen instead of just waiting and hoping it's doing something.
#This pattern is used to match the email addresses being removed.
#Test that this pattern finds the correct users and email addresses
#before running this script.
#Example: $pattern = "smtp:*@olddomain.com"
$RemovePattern = "smtp:*@olddomain.local"
Import-Module ActiveDirectory #only required for 2008 R2
#Get the users that have an email address that matches the pattern
Clear-Host
Write-Host "Querying objects...This may take a moment"
Write-Host ""
$objects = Get-ADObject -Filter {ProxyAddresses -like $RemovePattern} -Properties ProxyAddresses
#Identify address being removed from first user for warning
[String]$proxyexample = $objects[0].proxyaddresses -like $RemovePattern
#Display warning and get confirmation
Write-Host "You are going to remove email addresses that match the following pattern:"
Write-Host -ForegroundColor Red "$RemovePattern"
Write-Host ""
Write-Host "This is an example from the first object:"
Write-Host -ForegroundColor Red "$proxyexample"
Write-Host ""
Write-Host "This will modify $($objects.count) objects"
Write-Host ""
$confirm = Read-Host "Enter Y to continue"
If ($confirm -ne "Y") {Break}
#Prepare variables for processing status
$total = $objects.count
$current = 0
#Processing users to remove addresses
Foreach ($o in $objects) {
#Build list of addresses to remove for object
#required because there might be multiple that match
$proxy= New-Object System.Collections.ArrayList
Foreach ($a in ($o.ProxyAddresses)) {
If ($a -like $RemovePattern) {
$proxy.add($a) | Out-Null
} #end if
} #end foreach
#Remove each bad address
Foreach ($p in $proxy) {
Set-ADObject $o -Remove @{'proxyAddresses'=$p}
}
#Pause
#Processing status
$current += 1
Write-Progress -Activity "Removing email addresses that match pattern" -Status "Progress: $current" -PercentComplete ($current/$total*100)
} #end foreach
No comments:
Post a Comment