<#
using a powershell script to modify the mail attribute for users in our AD
#>


Param (
[string]$oldDomain = "domain.org",
[string]$newDomain = "domain.com",
[string]$SearchBase = "OU=Staff,OU=school,DC=domain,DC=domian,DC=net"
)

### Import the Active Directory module if not already loaded
Write-Verbose "$(Get-Date): Loading ActiveDirectory module..."
Try { Import-Module ActiveDirectory -ErrorAction Stop }
Catch { Write-Host "Unable to load Active Directory module, is RSAT installed?" -ForegroundColor Red; Exit }

Get-ADUser -filter * -Properties givenName, Surname, mail, sAMAccountName -searchbase $SearchBase | %{
### If the Surname is null in active directory, make the email address Firstname@newdomain.net
if ($_.mail -ne $null -and $_.mail -like "*$($oldDomain)*")
{
  $OrigEmail = $($_.mail)
  $FirstElement = $OrigEmail.Split("@")[1]
  $NewEmail = $OrigEmail.Replace($FirstElement,$newDomain)
  Set-ADUser -Identity $_ -mail $NewEmail
  If ((Get-ADUser -Identity $_).EmailAddress  -eq $NewEmail)
  {
   Write-Host "User Name:" $($_.sAMAccountName) "has been updated to" $($NewEmail) -ForegroundColor Yellow
  }
  else
  {
   Write-Host "Something went wrong with " $($_.sAMAccountName) "...the email address was not updated." -ForegroundColor Yellow
  }
}
}
