Use PowerShell to Disable Exchange Mailboxes Matching Google Export

This script will take a google user export, find mailboxes matching the email addresses in Exchange, and disable the mailboxes. Make sure you are not letting Google AD Sync synchronize until you are done with this process.

#stop script on error
$ErrorActionPreference = "Stop"

#import AD module
Import-Module ActiveDirectory

#pull all users from CSV
$googleusers = Import-Csv -Path C:\source\UserData-itvagabonds.com-20170505.csv -Header("EmailAddress")

#make the google exchange users array to be filled in later
$geusers = @()

#put mailbox data for all google users that have mailboxes into text files
ForEach ($googleuser in $googleusers) {
 #create single username property for current user object
 $googleusername = $googleuser.EmailAddress
 #attempt to pull a mailbox for the google user, if there is no mailbox write the username to a file
 Try
 {
  $exchangeobject = Get-Mailbox $googleusername | Select-Object SamAccountName,PrimarySmtpAddress,CustomAttribute1,EmailAddresses
  $geusers += $exchangeobject
 }
 Catch
 {
 "$googleusername, doesn't have an Exchange Mailbox" >> C:\source\UsersWithoutMailbox.txt
 }
}

#backup all attributes of google users, then remove the mailboxes using list of google users from geusers object
ForEach ($geuser in $geusers) {
 $username = $geuser.SamAccountName
 $PrimarySmtpAddress = $geuser.PrimarySmtpAddress.ToString()
 $proxyAddresses = $geuser.EmailAddresses
 $userobject = $geuser.samaccountname.ToString() + "," + $geuser.PrimarySmtpAddress.ToString() + "," + $geuser.CustomAttribute1.ToString()
 ForEach ($address in $ProxyAddresses) {
  if ($address -like "*SMTP*") {
   $userobject = $userobject + "," + $address.ToString()
  }
 }
 $userobject >> C:\source\UsersBeingDisabled.csv
 #Disable-Mailbox -Identity $username -Confirm:$False
}

#wait for attribute changes to sync after disabling mailbox
Start-Sleep -s 60

#re-add removed attributes if the user's mailbox has been removed
ForEach ($geuser in $geusers) {
 Try
 {
  Get-Mailbox $geuser
 }
 Catch
 {
  $username = $geuser.SamAccountName
  $proxyAddresses = $geuser.EmailAddresses
  $PrimarySmtpAddress = $geuser.PrimarySmtpAddress.ToString()
  Set-ADUser -Identity $username -Replace @{mail="$PrimarySmtpAddress";extensionAttribute1="google"}
  ForEach ($address in $proxyAddresses) {
   if ($address.ToString() -like "*SMTP*") {
    Set-ADUser -Identity $username -Add @{proxyAddresses=$address.ToString()}
   }
  }
 }
}

Don't forget to simulate a sync in Google AD Sync and make sure there aren't modifications that need fixed before letting a full sync run!

 
Tutorial Tags: