How to Sync an Existing Office365 Tenant into a New Active Directory Domain Using PowerShell

If you are in a situation where you currently use Office365 with lots of users and you now need to implement an on-premises active directory domain its not all that straight forward. The sync software is not quite able to take care of this for us yet but it is getting there with it’s AD write back features.

If you haven’t already then check out my post on how to perform this task manually by creating all of the accounts in the new AD.

Knowing how to manually create local AD objects which will successfully sync with Office365 is essential for any half decent Office 365 administrator. Having a PowerShell script which does it all for you is great also!

Download the script here

In our test lab I have an existing Office 365 tenant which has several user accounts, contacts and resources.

Here we have an info group with multiple members.

and here we have several equipment and room resources

So we have lots of accounts in our 365 tenant and likely you will have many more than this, possibly hundreds. You aren’t going to create them all by hand right!?

Your task is to configure your local network with a new domain into which you are going to sync your Office365 accounts and configure all of your PC’s to be part of the domain. You want users to login to the PC’s using the same usernames and passwords they already use to access resources in 365.

Next you install and configure a new domain controller into your network and create a brand new domain.

Download the PowerShell script to the server and open the PowerShell ISE tool as administrator

Open the script file and run the script or run the script directly from an administrator PowerShell window.

Before running the script there are two things to note:

  1. User accounts that get created in the local AD will have the password set to “Password123..” but you can change this in the script before running it. You will have to let all users know this beforehand or manually update the passwords. This password will sync back to Office 365 as soon as you configure Azure AD Connect to maintain a permanent sync.
  2. By default the script will create all accounts in the default user container. You can override this by manually creating a new OU in the AD and updating the $usersContainer variable in the script.

If all looks ok then run the script.

Hopefully you will see no errors produced by the script and if you refresh your AD you will see all of the user accounts, contacts and groups have been created. Each object is set to the correct logon name and has their email addresses set.

The script will also add all custom logon domains you have configured in Office365. Open up Active Directory Domains and Trusts on your DC, right click the root node and go to properties. You should see one or more Alternative UPN suffixes listed.

After performing a manual check of the accounts and once you are happy the users have logged into their PC’s and reset their passwords you are then ready to install AD Connect to enable a permanent sync between your Office 365 tenant and your new domain.


You will rarely be in a situation where you have a large Office 365 tenant and you have a need to install a brand new on-premises active directory domain but if you do then this script should save you a few hours!

Author: Ian@SlashAdmin

Share This Post On
468 ad


  1. Hi! Would this script insure 100% match between O365 user and local (new) AD user?.
    We had previuosly used script to link O365 user with existing AD users.

    Disable Azure AD connect sync.

    $guid = (Get-ADUser -Identity samaccountname).ObjectGuid
    $immutableID = [System.Convert]::ToBase64String($guid.tobytearray())
    Set-MSOLuser -UserPrincipalName mail@domain.name -ImmutableID $immutableID

    Enable Azure AD connect sync.

    And another thing! Is possible to make O365 users password take presedence over local AD password?
    Maybe use “password writeback” feature in AD connect

    Post a Reply
    • Hi Michael,

      It looks good but I wouldn’t bother personally. If users are setup correctly then it will work, I’ve never had an issue myself.

      So long as the username + UPN, mail and proxy address attributes are set correctly then AD Connect will match the accounts.

      As far as I know you cant make 365 take precedence but yes AD write back will sync changes from 365 to AD. Just be aware of any security implications that may have for you because any cloud based admin account that gets hacked could reset passwords in your AD and potentially gain access to other resources you publish to the internet. Obviously using 2FA on all accounts would help with this.

      Post a Reply
      • Hi Ian,

        i have run this script and works great for part of it.. however
        it is stopping at 100 users and i need to generate the extra 600 i have to get in is there a limitation of how many it can import or create?

        Post a Reply
        • Hi Josh,

          Try updating the last three lines of the script with these instead. Must admit I didn’t test with many users but thanks for reporting the issue!

          Please let me know if your project is successful and if I helped 🙂

          #Add users to local AD
          Get-AzureADUser -All $True | Add-LocalADObject

          #Add contacts to local AD
          Get-AzureADContact -All $True | Add-LocalADObject

          #Add groups to local AD
          Get-AzureADGroup -All $True | Add-LocalADObject

          Post a Reply
      • Hi, Thank you for your post. I followed your steps. Successfully added all azure ad objects to our new onpremises ad. After checking configuring things. We installed aad connect for sync services. After that we got mail says that there is 38 sync error, AttributeValueMustBeUnique” sync error. And other kind of sync error. Plz help me to understand what is actual reason for this, solution to fix this error

        Post a Reply
  2. Thanks! Using password write back setting in Ad connect might work, but think I would have to disable password sync until i’m sure password is the same in AD and in O365.
    By the way! Do you know of a script that does the exact oposite? That is created O365 users with local AD as source. I know AD sync would do that, but for this particuklar project, it’s not possible to use AD connect yet.

    Post a Reply
  3. Hello. I’m trying to use the script but it fails. Where should I run this script? On the 365 server or my local server?

    Post a Reply
    • Hi Christos,

      Post any errors it generates here and ill try and help but you either:

      1. Are not entering global administrator credentials.
      2. Have not set the upn suffix.
      3. Are not running it on a DC logged in as a domain admin.

      Post a Reply
  4. Hi Christos

    Thank you for your script.

    How would i exclude a certain group of users from being imported?
    I’m thinking of external users that have access to Sharepoint Online, whom i don’t need to administrate in the on premises DC (and the added #EXT# in the username results in errors when importing).

    Post a Reply
  5. My company was recently acquired and they had the great idea of using Binary Tree to sync our local domain to their local domain, then use AD Sync to sync users up to Office 365. The intent was to someday migrate to their domain. Now that’s not going to happen. When need to somehow move the ADconnect process back in our local domain and sync with their O365 Tenant. is this even possible?

    Post a Reply
  6. Hi The script is good can any one tell me is there a script that can pull the office365 alias address down to local ad

    Post a Reply
  7. Hi,

    The script works good for users, but for groups its creating the group as a Distribution list and not adding the owner.

    can we get a script to first check what type of group(security\Distribution) it is and create the appropriate on in the local AD with owner and members.

    Post a Reply
  8. We are looking for a way to do the opposite. From AD on premise to O365. It does not seems to be a smooth ride to do this. Any tips?

    Post a Reply
  9. your script work A1 !! tks

    Post a Reply
  10. After running the script and adding the users to local AD then configuring AD connect. Will the users be connected to their original mailboxes or will they need to be re attached

    Post a Reply
    • Hi Peter,

      It will be their original mailboxes yes. So if their outlook connects to a 365 mailbox and you sync the accounts into a new local AD then nothing really changes. Obviously if you join the PC’s to the new local AD that will create a new profile on the PC for that person but outlook will still connect to 365 yes.

      What happens is that the local AD account then becomes the master for any changes you make (depending on how you setup AD Connect). So adding new aliases to accounts would be done from the local AD etc.

      Post a Reply
  11. Silly Question. I want to roll this out slowly but I want to import all the users into the newly built domain. I am not joining all the workstation to the domain all at once. But i do want to create all the accounts. My overall question or concern is if i run this script and the local ad password is set to what ever I choose. Will that change the users o365 password if they have not been giving their ID yet? I hope that question makes sense.

    Post a Reply
    • nevermind, the answer is no i can run this head of time since ad-connect isnt even installed lol sorry for the silly question

      Post a Reply
  12. Hi,

    First of all, thanks for your great work.

    Once I have all my users loaded in my Local Active Directory. The next step is syncing with AD Connect. Is it possible to sync a few users to test it? If the answer is yes,would you delete the rest of the Office 365 accounts that are not synchronized?

    Thanks in advanced.

    Post a Reply
    • Use AD connect then yes you can setup a group in your local ad. put the users you want to sync into that then tell AD connect to only sync those users.

      Post a Reply
      • Ok, all right. If I put these test users in a group, when I sync, Will the other O365 users be deleted? I am afraid that all my O365 users will be deleted.

        Post a Reply
  13. Hi,

    I have all my office365 users in my local Active Directory. First, i want to test a few users and sync with office365. If I try this, will the other Office 365 email accounts be deleted?

    Thanks in advanced,

    Post a Reply
  14. Hello, i tried this method and also the manual method, but there’s no way, it will always create new objects in azure ad because it says that there are already users existing with the same email address.

    I dont know what to do anymore.

    Post a Reply


  1. Syncing Existing Office 365 Users to newly created AD Domain – Scattered Tech - […] I added the script from Slash admin to my toolbox. below is copy of the script in case the…

Submit a Comment

Your email address will not be published.