切换到宽版
  • 6988阅读
  • 0回复

[求助]使用脚本进行迁移后的清除工作 [复制链接]

上一主题 下一主题
 
只看楼主 倒序阅读 0楼  发表于: 2011-03-20
— 本帖被 YOYO 从 Exchange 脚本中心 移动到本区(2015-06-25) —
  • 脚本环境:PowerShell
  • 适合版本:Exchange 2007
  • 适用平台:
# Copyright (c) Microsoft Corporation. All rights reserved.  
#
# THIS CODE IS MADE AVAILABLE AS IS, WITHOUT WARRANTY OF ANY KIND. THE ENTIRE RISK
# OF THE USE OR THE RESULTS FROM THE USE OF THIS CODE REMAINS WITH THE USER.
# Synopsis: This script is designed to move mailboxes and create a contact or mail enable the user on the source Forest.
#
#
# Usage:
#
#    .\migrationCleanup.ps1 -UsersFile "D:\users.csv" -TargetDatabase 'ExServer1\Mailbox Database'
#     -SourceForestCredential $s -TargetForestCredential $t
#     -SourceGlobalCatalog gc.test-dom1.com -SourceDomainController dc.test-dom1.com
#     -GlobalCatalog gc.test-dom2.com -DomainController dc.test-dom2.com
#     -NTAccountOU 'CN=Users,DC=test-dom2,DC=com' -ContactsOU "ContactsOU"
#     -SourceMailboxCleanupOptions DeleteSourceMailbox -TargetSMTPDomain "test-dom1.com"
#
#     Moves mailboxes listed on D:\users.csv from Org test-dom1.com to ExServer1\Mailbox Database on Org test-dom2,
#     deletes the source mailbox and mail enables the source user so email is redirected to the mailbox on test-dom2
#
#
#    .\migrationCleanup.ps1 -UsersFile "D:\users.csv" -TargetDatabase 'ExServer1\Mailbox Database'
#     -SourceForestCredential $s -TargetForestCredential $t
#     -SourceGlobalCatalog gc.test-dom1.com -SourceDomainController dc.test-dom1.com
#     -GlobalCatalog gc.test-dom2.com -DomainController dc.test-dom2.com
#     -NTAccountOU 'CN=Users,DC=test-dom2,DC=com' -ContactsOU "ContactsOU"
#     -SourceMailboxCleanupOptions DeleteSourceNTAccount -TargetSMTPDomain "test-dom1.com"
#
#     Moves mailboxes listed on D:\users.csv from Org test-dom1.com to ExServer1\Mailbox Database on Org test-dom2,
#     deletes the source user and creates a contact so email is redirected to the mailbox on test-dom2
#

Param(
[string] $SourceGlobalCatalog = $(throw "Missing parameter: The -SourceGlobalCatalog parameter is required."),
[string] $SourceDomainController = $(throw "Missing parameter: The -SourceDomainController parameter is required."),
[string] $GlobalCatalog = $(throw "Missing parameter: The -GlobalCatalog parameter is required."),
[string] $DomainController = $(throw "Missing parameter: The -DomainController parameter is required."),
[string] $NTAccountOU = $(throw "Missing parameter: The -NTAccountOU parameter is required."),
[string] $ContactsOU = $(throw "Missing parameter: The -ContactsOU parameter is required."),
[string] $UsersFile = $(throw "Missing parameter: The -UsersFile parameter is required."),
[string] $TargetDatabase = $(throw "Missing parameter: The -TargetDatabase parameter is required."),
        [String] $SourceMailboxCleanupOptions = $(throw "Missing parameter: The -SourceMailboxCleanupOptions parameter is required. Options are: DeleteSourceMailbox and DeleteSourceNTAccount."),
[System.Management.automation.PSCredential] $SourceForestCredential = $(throw "Missing parameter: The -SourceForestCredential parameter is required."),
[System.Management.automation.PSCredential] $TargetForestCredential = $(throw "Missing parameter: The -TargetForestCredential parameter is required."),
[string] $TargetSMTPDomain = $(throw "Missing parameter: The -TargetSMTPDomain parameter is required.")
)
############################################################ Variable Declarations ################################################################
# Suppress warnings during script execution
$WarningPreference="SilentlyContinue"
# Opens log file
$this_date = get-date
$format_date = $this_date.ToString("d") -replace "/", ""
$file_date = $format_date+"_"+$this_date.TimeOfDay.Hours+$this_date.TimeOfDay.Minutes+$this_date.TimeOfDay.Seconds
# Log is saved on the directory defined here
$file_name = "C:\$($file_date)movecleanup.log"
############################################################ Variable Declarations End ############################################################
############################################################ Function Declarations ################################################################
# Adds to log file
function log
{
   Param($header,$Message)
   $log_date = get-date
   echo "[$($log_date)]: [$($header)]: $($Message)" >> $file_name
}
function logExit
{
   Param($header,$exitMessage)
   log $header $exitMessage
   echo "$($header): $($exitMessage)"
   break
}
############################################################ Function Declarations End ############################################################
############################################################ Main Script Block ####################################################################

log "Initializing" "Starting Migration: $($a_date)"
# checks if Contacts OU is valid
$error.Clear()
$rc = get-recipient -OrganizationalUnit $ContactsOU -ErrorAction SilentlyContinue -ResultSize 1
if (![String]::IsNullorEmpty($error[0]))
{
   logExit "Pre-validation" "Mailbox migration was not successful. Step: check Contacts OU. Error= $($error[0])."
}
else
{
   log "Pre-Validation" "ContactsOU = $($ContactsOU)"
}
# checks if Source Global Catalog is valid
$error.Clear()
$rc = get-recipient -DomainController $SourceGlobalCatalog -ErrorAction SilentlyContinue -ResultSize 1
if (![String]::IsNullorEmpty($error[0]))
{
   logExit "Pre-validation" "Mailbox migration was not successful. Step: check Source Global Catalog. Error= $($error[0])."
}
else
{
   log "Pre-Validation" "Source Global Catalog = $($SourceGlobalCatalog)"
}
# checks if Source Domain Controller is valid
$error.Clear()
$rc = get-recipient -DomainController $SourceDomainController -ErrorAction SilentlyContinue -ResultSize 1
if (![String]::IsNullorEmpty($error[0]))
{
   logExit "Pre-validation" "Mailbox migration was not successful. Step: check Source Domain Controller. Error= $($error[0])."
}
else
{
   log "Pre-Validation" "Source Domain Controller = $($SourceDomainController)"
}
# checks if Target Global Catalog is valid
$error.Clear()
$rc = get-recipient -DomainController $GlobalCatalog -ErrorAction SilentlyContinue -ResultSize 1 -Credential $TargetForestCredential
if (![String]::IsNullorEmpty($error[0]))
{
   logExit "Pre-validation" "Mailbox migration was not successful. Step: check Target Global Catalog. Error= $($error[0])."
}
else
{
   log "Pre-Validation" "Target Global Catalog = $($GlobalCatalog)"
}
# checks if Target Domain Controller is valid
$error.Clear()
$rc = get-recipient -DomainController $DomainController -ErrorAction SilentlyContinue -ResultSize 1 -Credential $TargetForestCredential
if (![String]::IsNullorEmpty($error[0]))
{
   logExit "Pre-validation" "Mailbox migration was not successful. Step: check Target Domain Controller. Error= $($error[0])."
}
else
{
   log "Pre-Validation" "Target Domain Controller = $($DomainController)"
}
# read users to be moved
$error.Clear()
$UserFile = import-csv -Path $UsersFile -OutVariable string -ErrorAction SilentlyContinue
if (![String]::IsNullorEmpty($error[0]))
{
   logExit "Pre-validation" "Mailbox migration was not successful. Step: Opening User list file. Error= $($error[0])."
}
$UserList = @()
# Filters Identity out of the csv and make sure we only try to move mailbox objects
foreach ($user in $UserFile)
{
   if (![String]::IsNullorEmpty($user))
   {
      $this_id = $user.Identity
      if (![String]::IsNullorEmpty($this_id))
      {
         $rc = get-recipient $this_id -ErrorAction SilentlyContinue
         if ($rc -eq $null)
         {
            log "Pre-validation" "Can not move user: $this_id . Please check whether this mailbox exists"
            echo "Can not move user: $this_id . Please check whether this mailbox exists"
         }
         else
         {
            # user exists. Check recipient type
            if ($rc.RecipientType -eq "UserMailbox")
            {
               $UserList+=$rc.alias
            }
            else
            {
               log "Pre-validation" "Can not move user: $this_id . Recipient Type: $($rc.RecipientType)"
               echo "Can not move user: $this_id . Recipient Type: $($rc.RecipientType)"
            }
         }
      }
      else
      {
          log "Pre-validation" "Can not move user: $this_id . Please check whether this mailbox exists"
          echo "Can not move user: $this_id . Please check whether this mailbox exists"
      }
   }
}
if ($UserList.count -lt 1)
{
   logExit "Pre-validation" "There are no mailboxes to be moved."
}

log "Pre-validation" "Going to move: $UserList"
# hashtables for source data
$sourceID =@{}
$sourceAlias =@{}
$sourceName =@{}
$sourceDisplayName =@{}
$sourceAddresses =@{}
$sourceFirstName =@{}
$sourceLastName =@{}
# store source data before move
$UserList | get-recipient | foreach {
  
   $sourceID[$_.Identity] = $_.Identity
   $sourceAlias[$_.Identity] = $_.Alias
   $sourceName[$_.Identity] = $_.Name
   $sourceDisplayName[$_.Identity] = $_.DisplayName
   [System.Collections.ArrayList]$sourceAddresses[$_.Identity] = $_.EmailAddresses
   #set extensionAttribute14 to 1 (block GALSync?)
   set-mailbox -Identity $_.Identity -CustomAttribute14 1
}
# store other source user attributes before move
$UserList | get-user | foreach  {
   $sourceFirstName[$_.Identity] = $_.FirstName
   $sourceLastName[$_.Identity] = $_.LastName
}
# move the mailbox and do cleanup for each mailbox moved
$UserList | move-mailbox -SourceForestGlobalCatalog $SourceGlobalCatalog -TargetDatabase $TargetDatabase -GlobalCatalog $GlobalCatalog –DomainController $DomainController –NTAccountOU $NTAccountOU -PreserveMailboxSizeLimit -IgnorePolicyMatch -ErrorAction SilentlyContinue -SourceMailboxCleanupOptions $SourceMailboxCleanupOptions -SourceForestCredential $SourceForestCredential -TargetForestCredential $TargetForestCredential -Confirm:$false | foreach {
   # cleaning temp variables
   $targetSMTP=$null      
   $TargetSMTPString=$null
   $tempPrimary=$null
   $tempx500=$null
   # Is there a better way to check if an error occured?
   if ($_.StatusCode -lt 0)
   {
      logExit "$($thisSourceAlias)" "Move-mailbox for User: $($_.Identity) was not successful. Error= $($_.StatusMessage). Migration Cleanup script can't continue."
   }
   # temp variables for the mailbox that was just moved
   $thisSourceID    = $sourceID[$_.Identity]
   $thisSourceAlias = $sourceAlias[$_.Identity]
   $thisSourceName  = $sourceName[$_.Identity]
   $thisSourceDisplayName = $sourceDisplayName[$_.Identity]
   $thisSourceAddresses   = $sourceAddresses[$_.Identity]
   $thisSourceFirstName = $sourceFirstName[$_.Identity]
   $thisSourceLastName  = $sourceLastName[$_.Identity]
   log "$($thisSourceAlias)" "Move-mailbox for User: $($_.Identity) was successful."
   log "$($thisSourceAlias)" "Source Mailbox Alias: $thisSourceAlias"
   log "$($thisSourceAlias)" "Source Mailbox Name:  $thisSourceName"
   log "$($thisSourceAlias)" "Source Mailbox DisplayName: $thisSourceDisplayName"
   log "$($thisSourceAlias)" "Source Mailbox Addresses:   $thisSourceAddresses"
   log "$($thisSourceAlias)" "Source Mailbox FirstName:   $thisSourceFirstName"
   log "$($thisSourceAlias)" "Source Mailbox LastName:    $thisSourceLastName"
   log "$($thisSourceAlias)" "Source Domain Controller:   $($_.SourceDomainController.toString())"
   # if delete source mailbox was used we try to mail enable the remaining source user
   if ($SourceMailboxCleanupOptions -eq "DeleteSourceMailbox")
   {
      # double check if user exists
      $error.Clear()
      $rc = get-user -Identity $($thissourceID) -DomainController $($_.SourceDomainController) -ErrorAction SilentlyContinue
      if ($rc -eq $null)
      {
         logExit "$($thisSourceAlias)" "Cleanup for User: $($thissourceID) was not successful. Step: get-user. Error= $($error[0])."
      }
  
      if ($rc.Identity.ToString() -eq $thisSourceID)
      {
         # user exists. Check recipient type
         if ($rc.RecipientType -eq "User")
         {
            # grab newly created mailbox
            $error.Clear()
            $targetUser = get-mailbox -Identity "$($thisSourceAlias)" -DomainController $DomainController -ErrorAction SilentlyContinue -Credential $TargetForestCredential
            if ($targetUser -eq $null)
            {
               logExit "$($thisSourceAlias)" "Cleanup for User: $($thissourceID) was not successful. Step: get-mailbox. Error= $($error[0])."
            }
            log "$($thisSourceAlias)" "Target Mailbox ID: $($targetUser.Identity)"
            log "$($thisSourceAlias)" "Target Mailbox EmailAddresses: $($targetUser.EmailAddresses)"
            # browse through target addresses to find out new primary                
            foreach ($temp in $targetUser.EmailAddresses)
            {
               if ( ($temp.isPrimaryAddress -eq $true) -and ($temp.Prefix -ilike "SMTP"))
               {
                   # Primary SMTP
                   $targetSMTP = [String]$temp.ToString()
                   $targetSMTPString = $temp.get_AddressString()
               }
            }

            if ([String]::IsNullorEmpty($targetSMTP) )
            {
               # checks if TargetSMTPDomain was passed
               if ([String]::IsNullorEmpty($TargetSMTPDomain) )
               {
                  logExit "$($thisSourceAlias)" "Cleanup for User: $($thissourceID) was not successful. Step: Get primary SMTP address. If the target server is an Exchange 2003 server please use the parameter -TargetSMTPDomain."
               }
               else
               {
                  $targetSMTP = $thissourceAlias+"@"+$TargetSMTPDomain
                  $targetSMTPString = $targetSMTP
               }
            
            }

            log "$($thisSourceAlias)" "Target Mailbox Primary SMTP: $($targetSMTP)"

            # Mail Enable user
            $error.Clear()
            $sourceMailEnabledUser = Enable-MailUser -Identity $thissourceID -Alias "$($thissourceAlias)" -ExternalEmailAddress $targetSMTP -DomainController $_.SourceDomainController -ErrorAction SilentlyContinue
            if ($sourceMailEnabledUser -eq $null)
            {
               logExit "$($thisSourceAlias)" "Cleanup for User: $($thissourceID) was not successful. Step: Enable-MailUser. Error= $($error[0])."
               echo "Cleanup for User: $($thissourceID) was not successful. Step: Enable-MailUser. Error= $($error[0])."
            }
            else
            {
               log "$($thisSourceAlias)" "User: $($thissourceID) has been mail enabled"
            }
            log "$($thisSourceAlias)" "Source Mailuser EmailAddresses: $($sourceMailEnabledUser.EmailAddresses)"
            # save all proxies to collection
            $targetProxies = new-object System.Collections.ArrayList
            $tmp1targetProxies = new-object System.Collections.ArrayList
            $tmp2targetProxies = new-object System.Collections.ArrayList
            # start by copying current addresses
            $targetProxies = $sourceMailEnabledUser.EmailAddresses
            # Add proxies from original source mailbox to mail enabled user proxy collection
            foreach ($temp in $thisSourceAddresses)
            {
            
                if ( ($temp.isPrimaryAddress -eq $true) )
                {
                   # Change all primaries to secondaries
                   $newProxy = $temp.ToSecondary()
                }
                else
                {
                   $newProxy = $temp
                }
                # checks if value already exists in collection
                if (!$targetProxies.Contains($newProxy))
                {
                   $rc = $targetProxies.Add($newProxy)
                }
                else
                {
                   #log "$($thisSourceAlias)" "Proxy: $newProxy already exists in collection"
                }
            }
            # Tries to Add target SMTP to proxy collection (it is necessary if address was calculated for a Ti target server)
            $tempPrimary = New-Object Microsoft.Exchange.Data.CustomProxyAddress "SMTP", $targetSMTPString, $true
            log "$($thisSourceAlias)" "Primary: $($tempPrimary) calculated"
            # checks if value already exists in collection
            if (!$targetProxies.Contains($tempPrimary))
            {
               # we need to insert this address as the first in the list, otherwise it will not be primary
               $rc = $tmp1targetProxies.Add($tempPrimary)          
               $rc = $tmp1targetProxies.AddRange($targetProxies)
               $targetProxies=$tmp1targetProxies
            }
            else
            {
               log "$($thisSourceAlias)" "Proxy: $($tempPrimary) already exists in collection"
               # Ensures Primary is first on list
               [Int]$PrimaryIndex = $targetProxies.IndexOf($tempPrimary)
               if (!$PrimaryIndex -eq 0)
               {
                  # Primary is not first, so we need to reorder array
                  # Splt Primary and other proxies add them to separate arrays
                  foreach ($proxy in $targetProxies)
                  {
                     if ( ($proxy.isPrimaryAddress -eq $true) -and ($proxy.Prefix -ilike "SMTP"))
                     {
                        $rc= $tmp1targetProxies.Add($proxy)
                     }
                     else
                     {
                        $rc= $tmp2targetProxies.Add($proxy)
                     }
                  }
                  # Join arrays
                  $targetProxies = $tmp1targetProxies
                  $rc = $targetProxies.AddRange($tmp2targetProxies)
               }
            }
            # Add target LegDN as X500 to mail enabled proxy collection
            $tempX500 = New-Object Microsoft.Exchange.Data.CustomProxyAddress "x500", $targetUser.legacyExchangeDN, $false
            # checks if value already exists in collection
            if (!$targetProxies.Contains($tempX500))
            {
                $rc= $targetProxies.Add($tempX500)        
                log "$($thisSourceAlias)" "Proxy: $($tempX500) added to the collection"
            }
            else
            {
                log "$($thisSourceAlias)" "Proxy: $($tempX500) already exists in collection"
            }        
      
            # stamp proxies to mail enabled user
            #$targetProxies.Count
            if ($targetProxies.Count -gt 0)
            {
               log "$($thisSourceAlias)" "Going to stamp EmailAddresses: $targetProxies to User: $($thissourceID)"

               $error.Clear()
               set-MailUser -Identity $thissourceID -EmailAddresses $targetProxies -ErrorAction SilentlyContinue -DomainController $_.SourceDomainController
               if (![String]::IsNullorEmpty($error[0]))
               {
                  logExit "$($thisSourceAlias)" "Cleanup for User: $($thissourceID) was not successful. Step: set-MailUser. Error= $($error[0])."
                  echo "Cleanup for User: $($thissourceID) was not successful. Step: set-MailUser. Error= $($error[0])."
               }
               else
               {
                  log "$($thisSourceAlias)" "Set-MailUser of EmailAddresses for $($thissourceID) was successful"
               }
            }
            $thisMailUser = get-MailUser -Identity $thissourceID -ErrorAction SilentlyContinue -DomainController $_.SourceDomainController
            log "$($thisSourceAlias)" "Source Mailuser ID: $($thisMailUser.Identity)"
            log "$($thisSourceAlias)" "Source Mailuser DisplayName: $($thisMailUser.DisplayName)"
            log "$($thisSourceAlias)" "Source Mailuser ExternalEmailAddress: $($thisMailUser.ExternalEmailAddress)"
            log "$($thisSourceAlias)" "Source Mailuser PrimarySMTP: $($thisMailUser.PrimarySmtpAddress)"
            log "$($thisSourceAlias)" "Source Mailuser EmailAddresses: $($thisMailUser.EmailAddresses)"
            log "$($thisSourceAlias)" "Migration and cleanup for user $($thisSourceAlias) was completed successfuly."
            echo "Migration and cleanup for user $($thisSourceAlias) was completed successfuly."
            trap
            {
                "Error ="+$_.Message
            }
         }
         else
         {
            logExit "$($thisSourceAlias)" "Can't mail enable this user because current Recipient type: $($rc.RecipientType)"
            echo "Can't mail enable user $($thisSourceAlias) because current Recipient type: $($rc.RecipientType)"
         }
      }
   }
   elseif ($SourceMailboxCleanupOptions -eq "DeleteSourceNTAccount")
   {
      # grab newly created mailbox
      $error.Clear()
      $targetUser = get-mailbox -Identity "$($thisSourceAlias)" -DomainController $DomainController -ErrorAction SilentlyContinue -Credential $TargetForestCredential
      if ($targetUser -eq $null)
      {
         logExit "$($thisSourceAlias)" "Cleanup for User: $($_.Identity) was not successful. Step: get-mailbox. Error= $($error[0])."
      }
      # browse through target addresses to find out new primary                
      foreach ($temp in $targetUser.EmailAddresses)
      {
         if ( ($temp.isPrimaryAddress -eq $true) -and ($temp.Prefix -ilike "SMTP"))
         {
             # Primary SMTP
             $targetSMTP = [String]$temp.ToString()
             $targetSMTPString = $temp.get_AddressString()
         }
      }

      if ([String]::IsNullorEmpty($targetSMTP) )
      {
         # checks if TargetSMTPDomain was passed
         if ([String]::IsNullorEmpty($TargetSMTPDomain) )
         {
            logExit "$($thisSourceAlias)" "Cleanup for User: $($_.Identity) was not successful. Step: Get primary SMTP address. If the target server is an Exchange 2003 server please use the parameter -TargetSMTPDomain."
         }
         else
         {
            $targetSMTP = $thissourceAlias+"@"+$TargetSMTPDomain
            $targetSMTPString = $targetSMTP
         }
      }
      log "$($thisSourceAlias)" "Target Mailbox SMTP: $($targetSMTP)"
      # Creates Contact
      $error.Clear()
      $sourceContact = New-MailContact -Name "$($thisSourceDisplayName)" -Alias "$($thissourceAlias)" -ExternalEmailAddress $targetSMTP -OrganizationalUnit $ContactsOU -DomainController $_.SourceDomainController -ErrorAction SilentlyContinue
      if ($sourceContact -eq $null)
      {
         logExit "$($thisSourceAlias)" "Cleanup for User: $($_.Identity) was not successful. Step: New-MailContact. Error= $($error[0])."
         echo "Cleanup for User: $($_.Identity) was not successful. Step: New-MailContact. Error= $($error[0])."
      }
      else
      {
         log "$($thisSourceAlias)" "Contact: $($sourceContact.Identity) has been created"
      }
      log "$($thisSourceAlias)" "Source Contact EmailAddresses: $($sourceContact.EmailAddresses)"
      # use target primary as external address for contact and save all target proxies to collection
      $targetProxies = new-object System.Collections.ArrayList
      $tmp1targetProxies = new-object System.Collections.ArrayList
      $tmp2targetProxies = new-object System.Collections.ArrayList
      # start by copying current addresses
      $targetProxies = $sourceContact.EmailAddresses
      # Add proxies from original source mailbox to mail enabled user proxy collection
      foreach ($temp in $thisSourceAddresses)
      {
            
         if ( ($temp.isPrimaryAddress -eq $true) )
         {
            # Change all primaries to secondaries
            $newProxy = $temp.ToSecondary()
         }
         else
         {
            $newProxy = $temp
         }
         # checks if value already exists in collection
         if (!$targetProxies.Contains($newProxy))
         {
            $rc = $targetProxies.Add($newProxy)
         }
         else
         {
            #log "$($thisSourceAlias)" "Proxy: $newProxy already exists in collection"
         }
      }
      # Tries to Add target SMTP to proxy collection (it is necessary if address was calculated for a Ti target server)
      $tempPrimary = New-Object Microsoft.Exchange.Data.CustomProxyAddress "SMTP", $targetSMTPString, $true

      # checks if value already exists in collection
      if (!$targetProxies.Contains($tempPrimary))
      {
         # we need to insert this address as the first in the list, otherwise it will not be primary
         $rc = $tmp1targetProxies.Add($tempPrimary)          
         $rc = $tmp1targetProxies.AddRange($targetProxies)
         $targetProxies=$tmp1targetProxies
                
      }
      else
      {
         log "$($thisSourceAlias)" "Proxy: $($tempPrimary) already exists in collection"
         # Ensures Primary is first on list
         [Int]$PrimaryIndex = $targetProxies.IndexOf($tempPrimary)
         if (!$PrimaryIndex -eq 0)
         {
            # Primary is not first, so we need to reorder array
            # Splt Primary and other proxies add them to separate arrays
            foreach ($proxy in $targetProxies)
            {
            
               if ( ($proxy.isPrimaryAddress -eq $true) -and ($proxy.Prefix -ilike "SMTP"))
               {
                  $rc = $tmp1targetProxies.Add($proxy)
               }
               else
               {
                  $rc = $tmp2targetProxies.Add($proxy)
               }
            }
            # Join arrays
            $targetProxies = $tmp1targetProxies
            $rc = $targetProxies.AddRange($tmp2targetProxies)
         }
      }
      # Add target LegDN as X500 to mail enabled proxy collection
      $tempX500 = New-Object Microsoft.Exchange.Data.CustomProxyAddress "x500", $targetUser.legacyExchangeDN, $false
      # checks if value already exists in collection
      if (!$targetProxies.Contains($tempX500))
      {
          $rc = $targetProxies.Add($tempX500)        
          log "$($thisSourceAlias)" "Proxy: $($tempX500) added to the collection"
      }
      else
      {
          log "$($thisSourceAlias)" "Proxy: $($tempX500) already exists in collection"
      }
      # stamp proxies to contact
      if ($targetProxies.Count -gt 0)
      {
         log "$($thisSourceAlias)" "Going to stamp EmailAddresses: $targetProxies to Contact: $($sourceContact.Identity)"
         $error.Clear()
         set-MailContact -Identity "$($sourceContact.Identity)" -EmailAddresses $targetProxies -ErrorAction SilentlyContinue -DomainController $_.SourceDomainController
         if (![String]::IsNullorEmpty($error[0]))
         {
            logExit "$($thisSourceAlias)" "Cleanup for User: $($_.Identity) was not successful. Step: set-MailContact. Error= $($error[0])."
            echo "Cleanup for User: $($_.Identity) was not successful. Step: set-MailContact. Error= $($error[0])."
         }
         else
         {
            log "$($thisSourceAlias)" "Set-MailContact of EmailAddresses for $($sourceContact.Identity) was successful"
         }
      }
      # Update other AD attributes for contact
      $error.Clear()
      set-contact -Identity "$($sourceContact.Identity)" -FirstName "$($thissourceFirstName)" -LastName "$($thissourceLastName)" -DisplayName "$($thissourceDisplayName)" -ErrorAction SilentlyContinue -DomainController $_.SourceDomainController
      if (![String]::IsNullorEmpty($error[0]))
      {
         logExit "$($thisSourceAlias)" "Cleanup for User: $($_.Identity) was not successful. Step: set-Contact. Error= $($error[0])."
         echo "Cleanup for User: $($_.Identity) was not successful. Step: set-Contact. Error= $($error[0])."
      }
      trap
      {
         "Error ="+$_.Message
      }
      $thisMailContact = get-MailContact -Identity "$($sourceContact.Identity)" -ErrorAction SilentlyContinue -DomainController $_.SourceDomainController
      log "$($thisSourceAlias)" "Source Contact ID: $($thisMailContact.Identity)"
      log "$($thisSourceAlias)" "Source Contact DisplayName: $($thisMailContact.DisplayName)"
      log "$($thisSourceAlias)" "Source Contact ExternalEmailAddress: $($thisMailContact.ExternalEmailAddress)"
      log "$($thisSourceAlias)" "Source Contact PrimarySMTP: $($thisMailContact.PrimarySmtpAddress)"
      log "$($thisSourceAlias)" "Source Contact EmailAddresses: $($thisMailContact.EmailAddresses)"
      log "$($thisSourceAlias)" "Migration and cleanup for user $($thisSourceAlias) was completed successfuly."
      echo "Migration and cleanup for user $($thisSourceAlias) was completed successfuly."
   }
   else
   {
      # no cleanup necessary
      logExit "$($thisSourceAlias)" "No cleanup necessary for Mailbox User: $thissourceID"
      echo "No cleanup necessary for Mailbox User: $thissourceID"
   }
}
$WarningPreference="Continue"
logExit "Terminating" "Finished Migration Script. Please check $($file_name) for details."
############################################################ Main Script Block END ################################################################

分享到
快速回复
限60 字节
 
上一个 下一个