UPDATED: Exchange 2010 – Move mailbox to new AD account

PowerShell logoAt work we are getting ready to create new user accounts for everyone and move their mailbox from the current AD account to the new account. The reason for this is a bit lengthy, but a big reason is people have been granted permissions based on their AD account rather than by group membership. So by switching AD accounts we can clean things up a bit. Currently the format of our usernames is first initial last name (example: John Doe is JDoe), and we will be changing to a first name dot last name format (example: John.Doe).

When we make this change we want to make sure the mailbox and all of the smtp addresses associated with it get moved from the current AD account and added to the new AD account. Because it is very critical that we don’t have problems I will be doing this one account at a time. So I came up with the following script to help out with the process. It asks for both usernames (this could be done with a CSV file), gets the smtp addresses from the current account, disables the mailbox, cleans the database, reconnects the mailbox to the new account, and finally adds the previous smtp addresses to the account.

UPDATE – Aug. 12, 2013

I wanted to come back and update this post a bit.  I’ve added more to the script to make it easier and so that I have less things to do manually.  I added the following to the script:

– Compares group membership between the old AD account and new AD account and then it adds the groups from the old account to the new own.
– Expires the old AD account (it updates the description and sets it to expire at the end of the previous day).
– Removes whatever is in the Company field of the old AD account (we have some other scripts that use this field and we don’t want the old accounts to show up).
– Removes the all of the Exchange distribution lists from the old AD account.
– Moves the telephone number, room number, and fax number from the old AD account and adds them to the new AD account.
– Sets the initial password on the new AD account.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
import-module activedirectory
 
# Step 1 - Enter old id and new id.
$oldid = read-host 'Enter current username'
$newid = read-host 'Enter new username'
$getDisplayname = get-aduser -identity $oldid -properties "displayname"
$displayName = $getDisplayname.displayname
 
# Step 2 - Retrieves the group membership for both accounts 
write-host "Step 2 - Getting group membership for the old AD account and the new AD account."
$sourcemember = get-aduser -filter {samaccountname -eq $oldid} -property memberof | select memberof 
$destmember = get-aduser -filter {samaccountname -eq $newid} -property memberof | select memberof 
 
# Step 2a - Checks if accounts have group membership, if no group membership is found for either account script will exit 
write-host "Step 2a - Making sure the accounts have groups associated."
if ($sourcemember -eq $null) {"Source user not found";return} 
if ($destmember -eq $null) {"Destination user not found";return} 
 
# Step 2b - Checks for differences, if no differences are found script will prompt and exit 
write-host "Step 2b - Comparing the group membership of both accounts."
if (-not (compare-object $destmember.memberof $sourcemember.memberof | where-object {$_.sideindicator -eq '=>'})) {write-host "No difference between $oldid & $newid groupmembership found. $newid will not be added to any additional groups.";return} 
 
# Routine that changes group membership and displays output to prompt 
compare-object $destmember.memberof $sourcemember.memberof | where-object {$_.sideindicator -eq '=>'} | 
    select -expand inputobject | foreach {write-host "$newid will be added to:"([regex]::split($_,'^CN=|,OU=.+$'))[1]} 
 
# If no confirmation parameter is set no confirmation is required, otherwise script will prompt for confirmation 
if ($noconfirm)    { 
    compare-object $destmember.memberof $sourcemember.memberof | where-object {$_.sideindicator -eq '=>'} |  
        select -expand inputobject | foreach {add-adgroupmember "$_" $newid} 
} 
 
else { 
    do{ 
        $UserInput = Read-Host "Are you sure you wish to add $newid to these groups?`n[Y]es, [N]o or e[X]it" 
        if (("Y","yes","n","no","X","exit") -notcontains $UserInput) { 
            $UserInput = $null 
            Write-Warning "Please input correct value" 
        } 
        if (("X","exit","N","no") -contains $UserInput) { 
            Write-Host "No changes made, exiting..." 
            exit 
        }      
        if (("Y","yes") -contains $UserInput) { 
            compare-object $destmember.memberof $sourcemember.memberof | where-object {$_.sideindicator -eq '=>'} |  
                select -expand inputobject | foreach {add-adgroupmember "$_" $newid} 
        } 
    } 
    until ($UserInput -ne $null) 
}
 
# Step 3 - Getting the database name from the old AD account.
write-host "Step 3 - Get Exchange mailbox database name from old AD account."
$db = Get-ADUser -Identity $oldid -Properties homemdb
$dbname = Get-MailboxDatabase -Identity $db.homemdb
 
# Step 4 - Getting the email addresses from the old AD account.
write-host "Step 4 - Getting email addresses from old AD account."
$primarySMTP = Get-Mailbox -Identity $oldid | Select-Object PrimarySmtpAddress
$primarySMTPaddr = $primarySMTP.primarysmtpaddress
$otherSMTP = Get-Mailbox -Identity $oldid | Select-Object @{Name=“EmailAddresses”;Expression={$_.EmailAddresses |Where-Object {$_.PrefixString -ceq “smtp”} | ForEach-Object {$_.SmtpAddress}}}
 
# Step 4a - Setting output variables for primary SMTP Address.
write-host "Step 4a - Setting output variables for primary SMTP Address."
$output1 = $primarySMTPaddr
 
# Step 5 - Disable mailbox from account
write-host "Step 5 - Disabling mailbox"
disable-mailbox $oldid@domain.com -confirm:$false
start-sleep -seconds 10
 
# Step 6 - Clean database
write-host "Step 6 - Cleaning the database"
clean-mailboxdatabase "$dbname"
 
# Step 7 - Reconnect mailbox to new AD Account
write-host "Step 7 - Reconnecting mailbox to new AD account"
start-sleep -seconds 30
connect-mailbox -identity "$displayName" -database "$dbname" -user "domain$newid" -Alias "$newid" -RetentionPolicy "Deleted Items Retention Policy"
 
# Step 8 - Add email addresses
write-host "Step 8 - Adding email aliases"
start-sleep -seconds 20
$alias = @()
set-mailbox -identity $newid -emailaddresses @{add="$output1"}
foreach ($alias in $otherSMTP.emailaddresses) {
  set-mailbox -identity $newid -emailaddresses @{add="$alias"}
  }
 
# Step 9 - Expire old AD Account
write-host "Step 9 - Expiring old AD account."
$ExpyDate = (get-date).ToString(“MM/dd/yyyy HH:mm:ss”)
Set-ADAccountExpiration $oldid -DateTime:$ExpyDate
 
# Step 10 - Append to old AD Account descriptions
write-host "Step 10 - Append description to old AD account."
$ExpDescrip = "Migrated: " + ((get-date).ToString(“MM/dd/yyyy”) + " - ")
$OldDescrip=(get-aduser -identity $oldid -property Description).description
Set-ADUser $oldid -Description:($ExpDescrip + " " + $OldDescrip)
 
# Step 11 - Remove company
write-host "Step 11 - Removing My Company from the Organization field."
Set-ADUser -identity $oldid -Company $null
 
# Step 12 - Remove Exchange DLs
write-host "Step 12 - Remove old AD account from Exchange DLs."
$memberof=(get-aduser -identity $oldid -property memberof).memberof
foreach($eachMember in $memberof) {
    if($eachMember -like "*ExchangeDLs*")
        {     
        $groupShortName=$eachMember.split(",")[0].split("=")[1]
        remove-adgroupmember -Identity $groupShortName -Member $oldid -confirm:$false
        $result1="User {0} is removed from {1} distribution list." -f $oldid,$groupShortName
        write-host $result1
        }
    if($eachMember -like "*RightFax*")
        {     
        $groupShortName2=$eachMember.split(",")[0].split("=")[1]
        remove-adgroupmember -Identity $groupShortName2 -Member $oldid -confirm:$false
        $result2="User {0} is removed from {1} group." -f $oldid,$groupShortName2
        write-host $result2
        }             
}
 
# Step 13 - Move fax number from old AD account to new AD account.
write-host "Moving fax number from old AD account to new AD account."
$getFaxNumber = get-aduser -identity $oldid -properties "facsimileTelephoneNumber"
$FaxNumber = $getFaxNumber.facsimileTelephoneNumber
Set-ADUser -identity $newid -Fax $FaxNumber
Set-ADUser -identity $oldid -Fax $null
 
# Step 14 - Add phone number and room number to new AD account.
write-host "Step 14 - Adding phone number and room number to new AD account."
$getPhoneNumber = get-aduser -identity $oldid -properties "officePhone"
$phoneNumber = $getPhoneNumber.officePhone
Set-ADUser -identity $newid -officePhone $phoneNumber
$getOfficeNumber = get-aduser -identity $oldid -properties "office"
$officeNumber = $getOfficeNumber.office
Set-ADUser -identity $newid -office $officeNumber
 
# Step 15 - Set password on new AD account.
write-host "Step 15 - Setting password on new AD account to Indiana."
$password = "P@ssw0rd"
Set-ADAccountPassword $newid -Reset -NewPassword(ConvertTo-SecureString -AsPlainText $password -Force)
Set-ADUser -Identity $newid -ChangePasswordAtLogon 1

I hope this helps someone out.
Eric


PDF pageEmail pagePrint page

Be First to Comment

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.