Sync Office 365 / AzureAD down to ADDS
Table of Contents
I recently found myself needing to build out an on premise Active Directory environment and populate it from objects found in Office 365 (AzureAD). The local Active Directory would then be configured as the identity source and would sync up to AzureAD using Azure AD Connect. Unfortunately, Azure AD Connect is currently a one way sync from your on premise Active Directory Domain Services environment to AzureAD and wont sync objects down. AADConnect does have the ability to match our AzureAD objects to their corresponding Active Directory objects but, if an attribute like City, Phone Number, Department, Title, etc. is present in your existing AzureAD and not in ADDS, the attribute may remain in AzureAD but not replicate down to ADDS. So we will want to copy over as many attributes from AzureAD to our local Active Directory as possible in preparation for the Azure AD Connect sync. We will also want to recreate groups (distribution, mail-enabled security, security) in Active Directory and also replicate their membership and owners.
I tried searching ways Microsoft recommended to accomplish a downward sync from AzureAD but was met with a feedback forum, and an article from Microsoft explaining all the steps involved with this specific situation. In the end to accomplish the downward sync I was looking for, I created a PowerShell function. You can skip all the function details and just go straight to the download at the end of the article.
Function Features
Automatic Domain Move Objects
I added the ability to auto move objects like users, based on their UPN domain. If I call the switch parameter, “DomainMoveUsersToOU” the function will parse the UPN, extract just the domain name and find an Active Directory OU with the same name. So if my user’s UPN was [email protected] it would see “TheLazyAdministrator” and see if there was an OU with that name, if true, it will place my user (or contact or group) in that OU.
Object Matching
Luckily Azure AD Connect is able to match your AzureAD objects to your on-premise objects. “When you install Azure AD Connect and you start synchronizing, the Azure AD sync service (in Azure AD) does a check on every new object and try to find an existing object to match. There are three attributes used for this process: userPrincipalName, proxyAddresses, and sourceAnchor/immutableID. A match on userPrincipalName and proxyAddresses is known as a soft match. A match on sourceAnchor is known as hard match. For the proxyAddresses attribute only the value with SMTP:, that is the primary email address, is used for the evaluation.”1
Attribute Write-Back and Conflict Resolution
The next item we would want to consider are the syncing of other attributes and find out which source would take precedence if an attribute it populated in AzureAD and ADDS. According to Microsoft, “if Azure AD finds an object where the attribute values are the same for an object coming from Connect and that it is already present in Azure AD, then the object in Azure AD is taken over by Connect. The previously cloud-managed object is flagged as on-premises managed. All attributes in Azure AD with a value in on-premises AD are overwritten with the on-premises value. The exception is when an attribute has a NULL value on-premises. In this case, the value in Azure AD remains, but you can still only change it on-premises to something else.”1. This means that ADDS will always be the master in an ADConnect configuration. If the attribute is populated in AzureAD and empty in ADDS, the attribute will remain in AzureAD but will not be written down to ADDS. So we will want to copy over as many attributes from AzureAD to ADDS as possible.
Existing Object Detection
The PowerShell function will always look in your current Active Directory environment for the object it is going to create prior to creating it. This is benficial so if you run it more than once it will not keep making duplicate objects or causing errors when attempting to create AD Objects that are already present.
Move All Sync Objects to a Specific OU
The function contains a parameter to specify a single OU that all of your sync objects will be moved to after creation. If for example you were syncing you Azure AD Users, you can call the, “UsersOU” parameter which you can input the OU Distnguished Name and all Users will be moved to that OU. This is the same with Contacts, and Groups.
Auto Add UPN Suffixes
The PowerShell function will look up your domains in Office 365 prior to doing anything and auto create the domains as valid active directory UPN suffixes. This is crucial because each domain in Office 365 can be a user’s UserPrincipalName, Email Address, etc. and if the domain is not a UPN suffix in Active Directory it will be unable to create the AD Object at all.
Sync Switch Parameters
Each sync “object group” is configured as a switch parameter. If you want to just sync users you would run “Sync-O365toADDS -SyncUsers”, and if you wanted to sync users and Distribution Groups you would run Sync-O365toADDS -SyncUsers -SyncDistributionGroups”. You can sync Users, Contacts, Distribution Groups, Mail-Enabled Security Groups, and Security Groups.
Attributes Synced to ADDS
Currently the following attributes are copied from your AzureAD objects to your Active Directory object:
Users
- First Name
- Last Name
- Display Name
- User Principal Name
- Email Address
- Proxy Addresses
- SMTP
- SPO
- SIP
- EUM
- Office
- Title
- Department
- City
- Office Phone (telephone number)
Contacts
- Display Name
- External Email
- Proxy Addresses
- First Name
- Last Name
Distribution Groups
- Name
- Display Name
- Primary SmtpAddress
- Proxyaddresses
- Description
- Members
- Group Owner (Managed By)
Mail-Enabled Security Groups
- Name
- Display Name
- Primary SmtpAddress
- Description
- Members
- Group Owner (Managed By)
Security Groups
- Name
- Display Name
- Primary SmtpAddress
- Description
- Members
- Group Owner (Managed By)
Screenshots of Function Running
Below are some screenshot of the function running in a test environment.
Users
Here we see the console output when creating users from AzureAD to local AD. It checks to
In Active Directory Users and Computers I can see my users and groups with a UPN / email address of “TheLazyAdministrator.com” are automatically placed in my TheLazyAdministrator OU.
Groups
My groups are automatically created and my membership is already populated. The membership will match the membership in AzureAD.
Group manager / owner is also replicated, along with the group Office and City attributes.
Domains
The function get all domains in your tenant and adds them as valid UPN Suffixes in your Active Directory enviornment
Module Check
The function will check for the MSOnline module as well as the AzureAD module. If it’s not present it will automatically download and install. It will also check to see if you are connected to MSOnline or AzureAD before attempting to connect again.
Download
You can download the function, track bugs and follow the project on GitHub.
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 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 |
<# .NOTES =========================================================================== Created on: 11/15/2018 11:56 AM Created by: Bradley Wyatt Filename: Sync-Office365ToADDS.ps1 =========================================================================== .REQUIREMENTS MSONLINE Module (Install-Module MSOnline) *Will install it automatically if not present .DESCRIPTION The PowerShell function will connect to your Office 365 / AzureAD and can re-create your Users, Groups, and Contacts in Active Directory. This is extremly helpful if you are looking to change your identity source from Office 365 (AzureAD) to Active Directory and then have Active Directory sync up to Office 365. This will also re-create Distribution, Security, and Mail-Enabled Security Groups and also populate the membership and owner (managed by). Distribution and Mail-Enabled security groups will SMTP match when you configure AADConnect. Attributes: If Azure AD finds an object where the attribute values are the same for an object coming from Connect (Active Directory) and that it is already present in Azure AD, then the object in Azure AD is taken over by Connect. The previously cloud-managed object is flagged as on-premises managed. All attributes in Azure AD with a value in on-premises AD are overwritten with the on-premises value. The exception is when an attribute has a NULL value on-premises. In this case, the value in Azure AD remains, but you can still only change it on-premises to something else. USER ATTRIBUTES IT WILL COPY OVER - First Name - Last Name - Display Name - User Principal Name - Email Address - Proxy Addresses - SMTP - SPO - SIP - EUM - Office - Title - Department - City - Office Phone (telephone number) MAIL CONTACT ATTRIBUTES IT WILL COPY OVER - Display Name - External Email - Proxy Addresses - First Name - Last Name DISTRIBUTION GROUP ATTRIBUTES IT WILL COPY OVER - Name - Display Name - Primary SmtpAddress - Proxyaddresses - Description - Members - Group Owner (Managed By) MAIL-ENABLED SECURITY GROUP ATTRIBUTES IT WILL COPY OVER - Name - Display Name - Primary SmtpAddress - Description - Members - Group Owner (Managed By) SECURITY GROUP ATTRIBUTES IT WILL COPY OVER - Name - Display Name - Primary SmtpAddress - Description - Members - Group Owner (Managed By) .PARAMETER SyncUsers [switch] Syncs Office 365 Users to ADDS .PARAMETER UsersOU [string] Optional. Can specify which OU to create the users in .PARAMETER PasswordForAllUsers [string] Required if you use the SyncUsers switch. Specifies the password that will be set for all users that are created. Converts the plain text string to secure.string PARAMETER DomainMoveUsersToOU [switch] Optional. Will move users to an OU that matches the domain name in their UPN. If the UPN is thelazyadministrator.com it will find an OU with the name "thelazyadministrator" and move the user there. If the OU is not present it will keep the user in the default Users OU .PARAMETER SyncContacts [switch] Syncs Office 365 Mail Contacts to ADDS .PARAMETER ContactsOU [string] Optional. Can specify which OU to create the mail contacts in .PARAMETER SyncDistributionGroups [switch] Syncs Office 365 Distribution Groups to ADDS .PARAMETER DistributionGroupsOU [string] Optional. Can specify which OU to create the Distribution Groups in .PARAMETER SyncMailEnabledSecurityGroups [switch] Syncs Office 365 Mail Enabled Security Groups to ADDS .PARAMETER MailEnabledSecurityGroupsOU [string] Optional. Can specify which OU to create the Mail-Enabled Security Groups in .PARAMETER SyncSecurityGroups [switch] Syncs Office 365 Security Groups to ADDS .PARAMETER DistributionGroupsOU [string] Optional. Can specify which OU to create the Security Groups in .EXAMPLE Sync-Office365ToADDS -SyncUsers -PaswordForAllUsers "Temp123!" .EXAMPLE Sync-Office365ToADDS -SyncContacts -SyncDistributionGroups .EXAMPLE Sync-Office365ToADDS -SyncSecurityGroups -SecurityGroupsOU "OU=Users,OU=bwya77,DC=lazyadmin,DC=com" .EXAMPLE Sync-Office365ToADDS -SyncUsers -PaswordForAllUsers "Temp123" "OU=Users,OU=Chicago,DC=lazyadmin,DC=com" #> function Sync-Office365ToADDS { [CmdletBinding()] Param ( [switch]$SyncUsers, [string]$UsersOU, [switch]$DomainMoveUsersToOU, [string]$PasswordForAllUsers, [switch]$SyncContacts, [string]$ContactsOU, [switch]$DomainMoveContactsToOU, [switch]$SyncDistributionGroups, [string]$DistributionGroupsOU, [switch]$DomainMoveDistributionGroupsToOU, [switch]$SyncMailEnabledSecurityGroups, [string]$MailEnabledSecurityGroupsOU, [switch]$DomainMoveMailEnabledSecurityGroupsToOU, [switch]$SyncSecurityGroups, [string]$SecurityGroupsOU ) function Connect-O365 { $UserCredential = Get-Credential $Session = New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri "https://ps.outlook.com/powershell/" -Credential $UserCredential -Authentication Basic -AllowRedirection Import-PSSession $Session Connect-MsolService -Credential $UserCredential } If (($SyncUsers -eq $True) -and (($PasswordForAllUsers).Length -lt 1)) { Do { $PasswordForAllUsers = Read-Host -Prompt "Please enter a password that will be set for all users synced from Office 365. This password will be converted to secure.string" } Until (($PasswordForAllUsers).Length -gt 0) } Write-Host "Checking to see if already connected to AzureAD" $AzureConnect = Get-AzureADTenantDetail -ErrorAction SilentlyContinue If ($AzureConnect -eq $null) { Write-Host "Checking to see if AzureAD Module is present" -ForegroundColor Green $AzureADCheck = get-module -ListAvailable | Where-object { $_.name -like "*azuread*" } If ($Null -eq $AzureADCheck) { Write-Warning "AzureAd module is not present, attempting to install it" Install-Module AzureAd -Force } Write-Host "Importing AzureAd Module" Import-Module AzureAd Write-Host "Connecting to AzureAd" Connect-AzureAD } $MSOnlineConnect = Get-MsolCompanyInformation -ErrorAction SilentlyContinue If ($MSOnlineConnect -eq $null) { Write-Host "Checking to see if MSOnline Module is present" -ForegroundColor Green $MSOnlineCheck = get-module -ListAvailable | Where-object { $_.name -like "*msonline*" } If ($Null -eq $MSOnlineCheck) { Write-Warning "MSOnline module is not present, attempting to install it" Install-Module Msonline -Force } Write-Host "Importing MSOnline Module" Import-Module MSOnline Write-Host "Connecting to MSOnline" -ForegroundColor DarkMagenta Connect-O365 } Write-Host "###############################" -ForegroundColor Green Write-Host "# DOMAINS #" -ForegroundColor Green Write-Host "###############################" -ForegroundColor Green #Get all domains in Office 365 tenant, do not grab the onmicrosoft domain. Add all the Domains as valid UPN suffixes in AD $Domains = Get-MsolDomain | Where-Object { $_.Name -notlike "*.onmicrosoft.com*" } | Select-Object -ExpandProperty Name foreach ($Domain in $Domains) { Write-Host "Adding $Domain as a valid UPN suffix" #If the UPN suffix is already present it will not error or cause issues Get-ADForest | Set-ADForest -UPNSuffixes @{ add = "$Domain" } } If ($SyncUsers -eq $true) { Write-Host "###############################" -ForegroundColor Green Write-Host "# USERS #" -ForegroundColor Green Write-Host "###############################" -ForegroundColor Green $Password = ConvertTo-SecureString $Passwordforallusers -AsPlainText -Force #Get all of the Office 365 Users #Conditional to remove the account AADConnect will use. You will see this account synced if Office 365 was previously synced to Office 365. This account will be created automatically when you use express settings in the AADConnect wizard $Users = Get-Msoluser -All | Where-Object { $_.DisplayName -notlike "On-Premises Directory Synchronization Service Account" } foreach ($User in $Users) { Write-Host "Working on the user, '$($User.DisplayName)'" -ForegroundColor Green Write-Host "Storing the user in a var" $ADUser = Get-ADUser -Filter * | Where-Object { $_.Name -eq $user.DisplayName } -ErrorAction SilentlyContinue Write-Host "Checking to see if $($user.displayname) is already present in Active Directory" If ($Null -ne $ADUser) { write-host "$($user.displayname) is present in Active Directory, Skipping!" } Else { write-host "$($user.displayname) is not present in Active Directory" Write-Host "Working on $($User.DisplayName)..." -ForegroundColor Yellow #Var for priamry e-mail address $PrimEMail = Get-MSOLUser -UserPrincipalName $user.UserPrincipalName | Select-Object -ExpandProperty ProxyAddresses | Where-Object { $_ -cmatch '^SMTP:' } #Var for all the alias e-mail addresses $AliasEMails = Get-MSOLUser -UserPrincipalName $user.UserPrincipalName | Select-Object -ExpandProperty ProxyAddresses | Where-Object { $_ -cmatch 'smtp:' } #Var for all the SPO e-mail addresses $SPOs = Get-Mailbox -identity $user.UserPrincipalName | Select-Object -ExpandProperty EmailAddresses | Where-Object { $_ -cmatch '^SPO:' } #Var for all the EUM e-mail addresses $CEUMs = Get-Mailbox -identity $user.UserPrincipalName | Select-Object -ExpandProperty EmailAddresses | Where-Object { $_ -cmatch '^EUM:' } #Var for all the lowercase eum e-mail addresses $LEUMs = Get-Mailbox -identity $user.UserPrincipalName | Select-Object -ExpandProperty EmailAddresses | Where-Object { $_ -cmatch 'eum:' } #Var for all the SIP e-mail addresses $SIPs = Get-Mailbox -identity $user.UserPrincipalName | Select-Object -ExpandProperty EmailAddresses | Where-Object { $_ -cmatch '^SIP:' } $SamAccountName = $user.UserPrincipalName.split("@") | Select-Object -First 1 Write-Host "Creating the user, '$($User.DisplayName)' as an Active Directory user... " If ($Null -ne $PrimEMail) { New-ADUser -Name $User.DisplayName -GivenName $user.Firstname -Surname $user.LastName -userprincipalName $user.UserPrincipalName -EmailAddress $PrimEMail.replace("SMTP:", "") -Enabled $true -AccountPassword $Password -ChangePasswordAtLogon $true -SamAccountName $SamAccountName -DisplayName $User.DisplayName -Office $User.Office -Title $User.Title -Department $User.Department -City $User.City -OfficePhone $User.PhoneNumber } Else { New-ADUser -Name $User.DisplayName -GivenName $user.Firstname -Surname $user.LastName -userprincipalName $user.UserPrincipalName -Enabled $true -AccountPassword $Password -ChangePasswordAtLogon $true -SamAccountName $SamAccountName -DisplayName $User.DisplayName -Office $User.Office -Title $User.title -Department $User.Department -City $User.City -OfficePhone $User.PhoneNumber } $ADUser = Get-ADUser -Filter * | Where-Object { $_.Name -eq $user.DisplayName } -ErrorAction SilentlyContinue #Add all the proxy e-mail address to the user foreach ($AliasEMail in $AliasEMails) { Write-Host "Adding the alias $AliasEMail for user, '$($User.DisplayName)'" $ADUser | Set-ADUser -Add @{ Proxyaddresses = "$AliasEMail" } } #Add all the proxy SPO addresses to the user foreach ($SPO in $SPOs) { Write-Host "Adding the SPO address $SPO for user, '$($User.DisplayName)'" $ADUser | Set-ADUser -Add @{ Proxyaddresses = "$SPO" } } #Add all the proxy EUM addresses to the user foreach ($CEUM in $CEUMs) { Write-Host "Adding the EUM address, '$CEUM' for user, '$($User.DisplayName)'" $ADUser | Set-ADUser -Add @{ Proxyaddresses = "$CEUM" } } #Add all the proxy EUM addresses to the user foreach ($LEUM in $LEUMs) { Write-Host "Adding the EUM address, '$LEUM' for user, '$($User.DisplayName)'" $ADUser | Set-ADUser -Add @{ Proxyaddresses = "$LEUM" } } #Add all the proxy SIP addresses to the user foreach ($SIP in $SIPs) { Write-Host "Adding the SIP address, '$SIP' for user, '$($User.DisplayName)'" $ADUser | Set-ADUser -Add @{ Proxyaddresses = "$SIP" } } #Set the primary e-mail address Write-Host "Adding the primary email address $PrimEMail for $($User.DisplayName)" $ADUser | Set-ADUser -Add @{ Proxyaddresses = "$PrimEMail" } } If ($UsersOU -like "*OU*") { Write-Host "Moving the user, '$($User.DisplayName)' to the OU at $UsersOU" Move-ADObject -Identity $ADUser.ObjectGuid -TargetPath $UsersOU } If ($DomainMoveUsersToOU -eq $true) { #Grab users UPN Domain Write-Host "Finding the UPN Domain for the user, '$($User.DisplayName)'" $UserUPNDomain = ((($User).UserPrincipalName).Split("@") | Select-Object -Last 1).Split(".") | Select-Object -First 1 Write-Host "The domain is $UserUPNDomain" Write-Host "Finding an OU that contains $UserUPNDomain" $DynOU = (Get-ADOrganizationalUnit -Filter * | Where-Object { $_.Name -like "*$UserUPNDomain*" } -ErrorAction SilentlyContinue).DistinguishedName If ($null -eq $DynOU) { Write-Host "No OU was found to move $($User.DisplayName) to. User will be at the default user creation OU" } Else { Write-Host "Moving $($User.DisplayName) to $DynOU" Move-ADObject -Identity $ADUser.ObjectGuid -TargetPath $DynOU } } $ADUser = $null } } If ($SyncContacts -eq $true) { Write-Host "###############################" -ForegroundColor Green Write-Host "# CONTACTS #" -ForegroundColor Green Write-Host "###############################" -ForegroundColor Green #Mail Contacts $MailContacts = Get-MailContact Foreach ($MailContact in $MailContacts) { $mailcontactexternalemail = ($mailcontact.ExternalEmailAddress).split("SMTP:") | Select-Object -Last 1 $Mailcontactfirstname = ($MailContact.displayname).split() | Select-Object -First 1 $Mailcontactlastname = ($MailContact.displayname).split() | Select-Object -Last 1 Write-Host "Working on the contact , '$($MailContact.displayname)'" -ForegroundColor Green $EContactUser = Get-ADObject -LDAPFilter "objectClass=Contact" | Where-Object { $_.Name -eq $mailcontact.DisplayName } -ErrorAction SilentlyContinue If ($Null -ne $EContactUser) { write-host "$($MailContact.displayname) is present in Active Directory, Skipping!" } Else { Write-Host "$($MailContact.displayname) not found in Active Directory, creating..." Write-Host "Creating mail contact, '$($Mailcontact.DisplayName)'" -ForegroundColor Yellow New-ADObject -name $mailcontact.displayname -DisplayName $mailcontact.displayname -type contact -OtherAttributes @{ 'mail' = $mailcontactexternalemail; 'givenName' = $Mailcontactfirstname; 'sn' = $Mailcontactlastname; 'Proxyaddresses' = $mailcontactexternalemail } } $EContactUser = Get-ADObject -LDAPFilter "objectClass=Contact" | Where-Object { $_.Name -eq $mailcontact.DisplayName } -ErrorAction SilentlyContinue If ($ContactsOU -like "*OU*") { Write-Host "Moving the contact, '$($MailContact.displayname)' to $ContactsOU" Move-ADObject $EContactUser.ObjectGuid -TargetPath $ContactsOU } If ($DomainMoveContactsToOU -eq $true) { #Grab contacts domain based on external email address Write-Host "Finding the External Email Address Domain for the contact, '$($Mailcontact.DisplayName)'" $ContactsDomain = (($mailcontactexternalemail).Split("@") | Select-Object -Last 1).Split(".") | Select-Object -First 1 Write-Host "The domain is $ContactsDomain" Write-Host "Finding an OU that contains $ContactsDomain" $DynOU = (Get-ADOrganizationalUnit -Filter * | Where-Object { $_.Name -like "*$ContactsDomain*" } -ErrorAction SilentlyContinue).DistinguishedName If ($null -eq $DynOU) { Write-Host "No OU was found to move $($Mailcontact.DisplayName) to. Contact will be at the default OU or at the forest root level" } Else { Write-Host "Moving $($Mailcontact.DisplayName) to $DynOU" Move-ADObject $EContactUser.ObjectGuid -TargetPath $DynOU } } $EContactUser = $null } } If ($SyncDistributionGroups -eq $true) { Write-Host "###############################" -ForegroundColor Green Write-Host "# DISTRIBUTION GROUPS #" -ForegroundColor Green Write-Host "###############################" -ForegroundColor Green #Distribution Groups $Groups = Get-DistributionGroup | Where-Object { $_.GroupType -eq "Universal" } foreach ($Group in $Groups) { Write-Host "Working on the Distribution Group, '$($Group.DisplayName)'" -ForegroundColor Green Write-Host "Checking to see if the Distribution Group, '$($Group.DisplayName) is already present in Active Directory'" Try { Get-ADGroup -Identity $Group.DisplayName -ErrorAction SilentlyContinue } Catch { Write-Host "The Distribution Group, '$($Group.DisplayName) is not present in Active Directory'" -ForegroundColor Yellow $GroupSAMAccountName = ($Group.DisplayName).Trim(" ") Write-Host "Creating the Distribution group, '$($group.DisplayName)'" If ($DistributionGroupsOU -like "*OU*") { New-ADGroup -Name $Group.DisplayName -SamAccountName $GroupSAMAccountName -GroupCategory "Distribution" -GroupScope Global -DisplayName $Group.DisplayName -Path $DistributionGroupsOU -OtherAttributes @{ 'mail' = $group.PrimarySmtpAddress } -Description $Group.Description } Else { New-ADGroup -Name $Group.DisplayName -SamAccountName $GroupSAMAccountName -GroupCategory "Distribution" -GroupScope Global -DisplayName $Group.DisplayName -OtherAttributes @{ 'mail' = $group.PrimarySmtpAddress } -Description $Group.Description } } Write-Host "Getting members for Distribution group, '$($Group.DisplayName)'" $Members = Get-DistributionGroupMember -Identity $Group.Name If ($Null -eq $Members) { write-host "$($Group.displayname) Has no members to add, Skipping!" } Else { foreach ($Member in $Members) { Write-Host "Adding $($Member.Name) to the group, '$($Group.Name)'" $AddMember = Get-ADObject -Filter * | Where-Object { $_.Name -eq $member.DisplayName } If ($AddMember -eq $null) { Write-Warning "$($Member.Name) was not found in Active Directory and could not be added as a member to $($Group.DisplayName)" } Else { Set-ADGroup -identity $Group.DisplayName -add @{ 'member' = $AddMember.DistinguishedName } } } } Write-Host "Getting Owner of the Distribution Group, '$($Group.DisplayName)'" $GroupOwner = Get-MsolGroup -ObjectId $Group.ExternalDirectoryObjectId | Select-Object @{ n = "ManagedBy"; e = { (Get-MsolUser -ObjectId (Get-MsolGroup -ObjectId $_.ObjectId).ManagedBy).UserPrincipalName } } | Select-Object -ExpandProperty ManagedBy Write-Host "The Owner is $GroupOwner" If ($null -eq $GroupOwner) { Write-Warning "The Distribution Group, '$($Group.DisplayName)' did not return an Owner" } Else { Write-Host "Finding $GroupOwner in Active Directory" $AddOwner = Get-ADUser -Filter * | Where-Object { $_.userprincipalname -eq "$GroupOwner" } If ($null -eq $AddOwner) { Write-Warning "$GroupOwner was not found in Active Directory and could not be added as an Owner for the group, '$($yGroup.DisplayName)'" } Else { Write-Host "The user, '$GroupOwner' was found in Active Directory. Adding as owner to the Distribution Group, '$($Group.DisplayName)'" Set-ADGroup -identity $Group.DisplayName -ManagedBy $AddOwner.DistinguishedName } } $AliasEMailGroups = $Group.EmailAddresses foreach ($AliasEMailGroup in $AliasEMailGroups) { Write-Host "Adding the alias $AliasEMailGroup for Distribution Group, '$($Group.DisplayName)'" Set-ADGroup -identity $Group.DisplayName -Add @{ Proxyaddresses = "$AliasEMailGroup" } } If ($DomainMoveDistributionGroupsToOU -eq $true) { #Grab Distribution Group domain based on external email address Write-Host "Finding the External Email Address Domain for the Distribution Group, '$($Group.DisplayName)'" $DistroGroupDomain = (($group.PrimarySmtpAddress).Split("@") | Select-Object -Last 1).Split(".") | Select-Object -First 1 Write-Host "The domain is $DistroGroupDomain" Write-Host "Finding an OU that contains $DistroGroupDomain" $DynOU = (Get-ADOrganizationalUnit -Filter * | Where-Object { $_.Name -like "*$DistroGroupDomain*" } -ErrorAction SilentlyContinue).DistinguishedName If ($null -eq $DynOU) { Write-Host "No OU was found to move $($Group.DisplayName) to. Contact will be at the default Users OU" } Else { Write-Host "Moving $($Group.DisplayName) to $DynOU" Get-ADGroup -identity $Group.DisplayName | Move-ADObject -TargetPath $DynOU } } $GroupPresent = $null } } If ($SyncMailEnabledSecurityGroups -eq $true) { Write-Host "################################" -ForegroundColor Green Write-Host "# MAIL-ENABLED SECURITY GROUPS #" -ForegroundColor Green Write-Host "################################" -ForegroundColor Green #Mail Enabled Security Groups $MailEnabledSecurityGroups = Get-DistributionGroup | Where-Object { $_.GroupType -like "*SecurityEnabled*" } foreach ($MailEnabledSecurityGroup in $MailEnabledSecurityGroups) { Write-Host "Working on the mail-enabled security group, '$($MailEnabledSecurityGroup.DisplayName)'" -ForegroundColor Green Write-Host "Checking to see if the Mail-Enabled Security Group, '$($MailEnabledSecurityGroup.DisplayName) is already present in Active Directory'" Try { Get-ADGroup -Identity $MailEnabledSecurityGroup.DisplayName } Catch { Write-Host "The Mail-Enabled Security Group, '$($MailEnabledSecurityGroup.DisplayName) is not present in Active Directory'" -ForegroundColor Yellow $GroupSAMAccountName = ($MailEnabledSecurityGroup.DisplayName).Trim(" ") Write-Host "Creating the Mail-Enabled Security group, '$($MailEnabledSecurityGroup.DisplayName)'" If ($MailEnabledSecurityGroupsOU -like "*OU*") { New-ADGroup -Name $MailEnabledSecurityGroup.DisplayName -SamAccountName $GroupSAMAccountName -GroupCategory "Security" -GroupScope Global -DisplayName $MailEnabledSecurityGroup.DisplayName -Path $MailEnabledSecurityGroupsOU -OtherAttributes @{ 'mail' = $MailEnabledSecurityGroup.PrimarySmtpAddress } -Description $MailEnabledSecurityGroup.Description } Else { New-ADGroup -Name $MailEnabledSecurityGroup.DisplayName -SamAccountName $GroupSAMAccountName -GroupCategory "Security" -GroupScope Global -DisplayName $MailEnabledSecurityGroup.DisplayName -OtherAttributes @{ 'mail' = $MailEnabledSecurityGroup.PrimarySmtpAddress } -Description $MailEnabledSecurityGroup.Description } } Write-Host "Getting members for the Mail-Enabled Security group, '$($MailEnabledSecurityGroup.DisplayName)'" $Members = Get-DistributionGroupMember -Identity $MailEnabledSecurityGroup.Name foreach ($Member in $Members) { Write-Host "Adding $($Member.Name) to the group, '$($MailEnabledSecurityGroup.Name)'" $AddMember = Get-ADObject -Filter * | Where-Object { $_.Name -eq $member.DisplayName } If ($AddMember -eq $null) { Write-Warning "$($Member.Name) was not found in Active Directory and could not be added as a member to $($MailEnabledSecurityGroup.DisplayName)" } Else { Set-ADGroup -identity $MailEnabledSecurityGroup.DisplayName -add @{ 'member' = $AddMember.DistinguishedName } } } Write-Host "Getting Owner of Mail-Enabled Security Group, '$($MailEnabledSecurityGroup.DisplayName)'" $MailEnabledSecurityGroupOwner = Get-MsolGroup -ObjectId $MailEnabledSecurityGroup.ExternalDirectoryObjectId | Select-Object @{ n = "ManagedBy"; e = { (Get-MsolUser -ObjectId (Get-MsolGroup -ObjectId $_.ObjectId).ManagedBy).UserPrincipalName } } | Select-Object -ExpandProperty ManagedBy Write-Host "The Owner is $MailEnabledSecurityGroupOwner" If ($null -eq $MailEnabledSecurityGroupOwner) { Write-Warning "The Mail-Enabled Security Group, '$($MailEnabledSecurityGroup.DisplayName)' did not return an Owner" } Else { Write-Host "Finding $MailEnabledSecurityGroupOwner in Active Directory" $AddOwner = Get-ADUser -Filter * | Where-Object { $_.userprincipalname -eq "$MailEnabledSecurityGroupOwner" } If ($null -eq $AddOwner) { Write-Warning "$MailEnabledSecurityGroupOwner was not found in Active Directory and could not be added as an Owner for the Mail-Enabled Security Group, '$($MailEnabledSecurityGroup.DisplayName)'" } Else { Write-Host "The user, '$MailEnabledSecurityGroupOwner' was found in Active Directory. Adding as owner to the Mail-Enabled Security Group, '$($MailEnabledSecurityGroup.DisplayName)'" Set-ADGroup -identity $MailEnabledSecurityGroup.DisplayName -ManagedBy $AddOwner.DistinguishedName } } If ($DomainMoveMailEnabledSecurityGroupsToOU -eq $true) { #Grab Mail Enabled Security Group domain based on external email address Write-Host "Finding the External Email Address Domain for the Mail Enabled Security Group, '$($MailEnabledSecurityGroup.DisplayName)'" $MailEnabledSecurityGroupDomain = (($MailEnabledSecurityGroup.PrimarySmtpAddress).Split("@") | Select-Object -Last 1).Split(".") | Select-Object -First 1 Write-Host "The domain is $MailEnabledSecurityGroupDomain" Write-Host "Finding an OU that contains $MailEnabledSecurityGroupDomain" $DynOU = (Get-ADOrganizationalUnit -Filter * | Where-Object { $_.Name -like "*$MailEnabledSecurityGroupDomain*" } -ErrorAction SilentlyContinue).DistinguishedName If ($null -eq $DynOU) { Write-Host "No OU was found to move $($MailEnabledSecurityGroup.DisplayName) to. Contact will be at the default Users OU" } Else { Write-Host "Moving $($MailEnabledSecurityGroup.DisplayName) to $DynOU" Get-ADGroup -identity $MailEnabledSecurityGroup.DisplayName | Move-ADObject -TargetPath $DynOU } } $GroupPresent = $null } } If ($SyncSecurityGroups -eq $true) { Write-Host "################################" -ForegroundColor Green Write-Host "# SECURITY GROUPS #" -ForegroundColor Green Write-Host "################################" -ForegroundColor Green #Mail Enabled Security Groups #I have a lot of conditionals in there. These groups are default AD groups that may have been synced to Office 365 if someone configured it with the express settings. Using these conditionals I am exluding these groups because they already exisit or will exisit when you set up AADConnect $SecurityGroups = Get-MsolGroup | Where-Object { ($_.GroupType -eq "Security") -and ($_.DisplayName -notlike "ADSyncOperators") -and ($_.DisplayName -notlike "ADSyncBrowse") -and ($_.DisplayName -notlike "ADSyncOperators") -and ($_.DisplayName -notlike "ADSyncPasswordSet") -and ($_.DisplayName -notlike "ADSyncAdmins") -and ($_.DisplayName -notlike "DnsAdmins") -and ($_.DisplayName -notlike "DnsUpdateProxy") } foreach ($SecurityGroup in $SecurityGroups) { Write-Host "Working on the Security Group, '$($SecurityGroup.DisplayName)'" Write-Host "Checking to see if the Mail-Enabled Security Group, '$($SecurityGroup.DisplayName) is already present in Active Directory'" Try { Get-ADGroup -Identity $SecurityGroup.DisplayName } Catch { Write-Host "The Security Group, '$($SecurityGroup.DisplayName) is not present in Active Directory'" -ForegroundColor Yellow $GroupSAMAccountName = ($SecurityGroup.DisplayName).Trim(" ") Write-Host "Creating the Security group, '$($SecurityGroup.DisplayName)'" If ($UsersOU -like "*OU*") { New-ADGroup -Name $SecurityGroup.DisplayName -SamAccountName $GroupSAMAccountName -GroupCategory "Security" -GroupScope Global -DisplayName $SecurityGroup.DisplayName -Path $SecurityGroupsOU -Description $SecurityGroup.Description } Else { New-ADGroup -Name $SecurityGroup.DisplayName -SamAccountName $GroupSAMAccountName -GroupCategory "Security" -GroupScope Global -DisplayName $SecurityGroup.DisplayName -Description $SecurityGroup.Description } } Write-Host "Getting members for the Security group, '$($SecurityGroup.DisplayName)'" $Members = Get-MsolGroupMember -GroupObjectId $SecurityGroup.ObjectID foreach ($Member in $Members) { Write-Host "Adding $($Member.DisplayName) to the group, '$($SecurityGroup.DisplayName)'" $AddMember = Get-ADObject -Filter * | Where-Object { $_.Name -eq $member.DisplayName } If ($AddMember -eq $null) { Write-Warning "$($Member.Name) was not found in Active Directory and could not be added as a member to $($SecurityGroup.DisplayName)" } Else { Set-ADGroup -identity $SecurityGroup.DisplayName -add @{ 'member' = $AddMember.DistinguishedName } } } Write-Host "Getting Owner of Security Group, '$($SecurityGroup.DisplayName)'" $SecurityGroupOwner = Get-AzureADGroupOwner -ObjectId $SecurityGroup.ObjectID | Select-Object -ExpandProperty UserPrincipalName Write-Host "The Owner is $SecurityGroupOwner" If ($null -eq $SecurityGroupOwner) { Write-Warning "The Security Group, '$($SecurityGroup.DisplayName)' did not return an Owner" } Else { Write-Host "Finding $SecurityGroupOwner in Active Directory" $AddOwner = Get-ADUser -Filter * | Where-Object { $_.userprincipalname -eq "$SecurityGroupOwner" } If ($null -eq $AddOwner) { Write-Warning "$SecurityGroupOwner was not found in Active Directory and could not be added as an Owner for the Security Group, '$($SecurityGroup.DisplayName)'" } Else { Write-Host "The user, '$SecurityGroupOwner' was found in Active Directory. Adding as owner to the Security Group, '$($SecurityGroup.DisplayName)'" Set-ADGroup -identity $SecurityGroup.DisplayName -ManagedBy $AddOwner.DistinguishedName } } } } } |
Sources:
1: https://docs.microsoft.com/en-us/azure/active-directory/hybrid/how-to-connect-install-existing-tenant

My name is Bradley Wyatt; I am currently a Technology Specialist at Porcaro Stolarek Mete Partners which is headquartered in Chicago, Illinois. At PSM we provide solutions which are custom designed around the specific needs of each client. If you are looking for a career change or would like to learn more about PSM’s offerings, please feel free to e-mail me.
5 thoughts on “Sync Office 365 / AzureAD down to ADDS”
I cant get it to work. Nothing happens when i run the script. What do i do wrong ?
Its a function so are you loading into memory? What is your command you are trying to run? Are you running it on an AD server?
What command should be run?. I’ve tried . .\scriptname.ps1 nothing happens.
are you running .\scriptname.ps1? Its an example of dot sourcing a script
I tried
.\scriptname.ps1
. .\scriptname.ps1 -argument
Nothing happens. Ran from PS on new domain controller. I can manually connect to Azure and 365 with powershell from this server. Ran from an elevated command prompt.