Skip to content

Instantly share code, notes, and snippets.

@PSingletary
Created February 11, 2020 14:17
Show Gist options
  • Select an option

  • Save PSingletary/bf9fb6f1cb9ea670c6570b777713abf0 to your computer and use it in GitHub Desktop.

Select an option

Save PSingletary/bf9fb6f1cb9ea670c6570b777713abf0 to your computer and use it in GitHub Desktop.
$oldDom = '@newdomain.com'
$newDom = '@olddomain.com'
# USING GET-ADUSER AS INPUT:
# Get all AD users with an email address that ends in the old domain. These will be the ones to change.
$adFilter = 'mail -like "*{0}"' -f $oldDom
$users = @(Get-ADUser -Filter $adFilter -Properties mail, proxyAddresses)
# Loop and process each found user
foreach ($user in $users)
{
# Locate old primary proxyAddress
$oldPrimary = $user.proxyAddresses.Where({$_.StartsWith('SMTP:')})
if ($oldPrimary.Count -ne 1) # That's weird...
{
Write-Warning ("{0} somehow either has multiple or no primary SMTP addresses?" -f $user.Name)
continue
}
else
{
$oldPrimary = $oldPrimary | Select-Object -First 1
}
# Format the new 'mail' property for the given user.
$replacedEmail = $user.mail.Replace($oldDom, $newDom)
# Use the replaced value to make the new primary proxyAddress.
$newPrimary = "SMTP:{0}" -f $replacedEmail
# Format the new UPN
$newUpn = $user.UserPrincipalName.Replace($oldDom, $newDom)
# Transform the 'old' primary from "SMTP:" to "smtp:".
$oldAlias = "{0}{1}" -f $oldPrimary.Substring(0, 4).ToLower(), $oldPrimary.Substring(4)
# Announce
Write-Host ("Will replace '{0}' with '{1}'" -f $oldPrimary, $newPrimary) -f Yellow
Write-Host ("The old alias will be: {0}" -f $oldAlias) -f Yellow
Write-Host ("The new UPN will be: {0}" -f $newUpn) -f Yellow
# Create new collection containing all current proxyAddresses
$addressCol = [Microsoft.ActiveDirectory.Management.ADPropertyValueCollection]::new($user.proxyAddresses)
# Find the index within the new collection of the old primary address.
$index = $addressCol.IndexOf($oldPrimary)
# Replace that entry with the 'new' primary address.
$addressCol[$index] = $newPrimary
# Then add the old primary as an additional proxyAddresses (alias)
[void] $addressCol.Add($oldAlias)
# Build 'Set-ADUser' arguments
$setArguments = @{
Identity = $user.DistinguishedName
EmailAddress = $replacedEmail
Replace = @{ proxyAddresses = $addressCol.Value }
UserPrincipalName = $newUpn
WhatIf = $true # Get rid of me to perform the changes
}
# Execute
Set-ADUser @setArguments
Write-Host "--------------------" -f Yellow # Just a separator between each loop.
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment