Skip to content

Sync On-Prem AD to Microsoft 365

Sync On-Prem AD to Microsoft 365

This guide empowers you to automatically keep your on-premise Active Directory (AD) security groups in sync with your Microsoft 365 Groups and Teams. Leveraging the Sekers/M365-Teams-Membership-Sync PowerShell-based sync engine. It's perfect for organizations that manage their main user and group information on their local network (on-premise AD) but use Microsoft 365 and Teams for collaboration.

What This Guide Covers

  • Understanding the basics: What is this sync and why do you need it?
  • Setting up your environment: Get your system ready with the right modules and settings.
  • Creating a sync identity in Microsoft Entra ID: How to securely connect your script to Microsoft 365.
  • Configuring the sync script: Telling the script which groups to sync.
  • Running and automating the sync: Making it run automatically in the background.
  • Monitoring and troubleshooting: What to do if something goes wrong.

Key Features

  • Certificate-Based Microsoft Entra App Registration
    Secure, passwordless authentication to Microsoft Graph using a .pfx certificate.

  • Microsoft Graph API Integration
    Grants precise access to read/write Microsoft 365 Group and Team memberships.

  • PowerShell Automation
    Full group member sync logic (add/remove) using PowerShell and Task Scheduler.

  • Flexible Execution Modes

    • Dry-Run Mode: Preview changes before applying
    • Production Mode: Apply actual group membership updates live

Folder Structure

Place your files in a structured directory like this:

M365-Sync/
├── Config/
│ ├── config_general.json
│ ├── config_group_team_mapping.json
│ ├── config_remove_account_exclusions.json
│ ├── PrivateKeyCertificate.pfx
│ └── PrivateKeyCertificate.cer
├── Logging/
│ └── [auto-generated logs here]
├── M365 Teams Membership Sync.ps1
├── README.md

Note

  • Make sure the Logging/ folder exists before running the script.

Prerequisites

Here's what you need to have in place before beginning the setup.

Understanding Your Identity Setup

  • Microsoft Entra Connect Sync (or Cloud Sync): This guide assumes you already have your on-premise Active Directory users and groups syncing to Microsoft Entra ID (formerly Azure Active Directory). This is a crucial first step for any hybrid environment.

    • What is it? Microsoft Entra Connect Sync is a tool that connects your local Active Directory to Microsoft Entra ID in the cloud, ensuring your user accounts and groups are visible in Microsoft 365.
    • Is it set up? If you're unsure, you'll need to confirm that your organization's users and groups from your local server appear in the Microsoft Entra admin center (https://entra.microsoft.com).
    • If not: Setting up Microsoft Entra Connect Sync is beyond the scope of this guide. Please refer to Microsoft's official documentation for detailed steps on installing and configuring it.
  • Microsoft Entra ID P1 License (Optional):

    • Why? This license is required for features like Group Writeback and other advanced hybrid identity capabilities that allow changes to flow between on-prem and cloud.
    • Who needs it? Only administrators who manage the sync process need this license. It does not need to be assigned to every user who is being synced.

Tools You'll Need

  • PowerShell 5.1 or later: This is the scripting language the sync tool uses. It's usually pre-installed on Windows Server and modern Windows 10/11 computers.

    • How to check your version: Open PowerShell (search for "PowerShell" in the Start menu) and type: $PSVersionTable.PSVersion
    • Minimum required: Ensure the Major version is 5 or higher.

    • Required PowerShell Modules: The script relies on extra tools (called "modules") for specific tasks. You'll need to install them:

    Module Name What it Does
    Microsoft.Graph Allows the script to talk to Microsoft 365 (Groups, Teams, Users)
    PSFramework Helps with logging, configuration, and other script tasks
    Mailozaurr Used to send email notifications (like error alerts)
  • Installation Commands:

    1. Open PowerShell as an Administrator. (Search for "PowerShell", right-click, and select "Run as administrator").
    2. Run the following commands one by one:

      PowerShell
      Install-Module Microsoft.Graph -Scope CurrentUser -Force
      Install-Module PSFramework -Scope CurrentUser -Force
      Install-Module Mailozaurr -Scope CurrentUser -Force
      

    Installation Tips

    • If you see a prompt about a "NuGet provider" or "untrusted repository," type Y and press Enter to allow the installation.
    • If you encounter permission issues, ensure you are running PowerShell as Administrator.

Step 1: Create a Secure Sync Identity in Microsoft Entra ID

To allow your PowerShell script to securely connect to and manage groups in Microsoft 365, you need to create an App Registration in Microsoft Entra ID. Think of this as giving your script its own secure ID and specific permissions to do its job.

What this App Will Do

This special application will operate behind the scenes (without a user logging in) and have specific permissions to:

  • Read and update Microsoft 365 Groups and Teams.
  • Add and remove members from groups.
  • Manage Exchange Online unified groups (the email side of Microsoft 365 groups).

How to Create the App Registration

  1. Go to the Microsoft Entra Admin Center: https://entra.microsoft.com
  2. In the left-hand menu, navigate to Identity > Applications > App registrations.
  3. Click + New registration.

    Fill in the details: * Name: Type M365 Teams Membership Sync (or a name that makes sense to you). * Supported account types: Select Single tenant (This means only accounts in your organization can use this app). * Redirect URI: Leave this blank. 4. Click Register.

Grant API Permissions (What the App Can Do)

Now, you need to tell this app what it's allowed to do.

  1. After creating the app, you'll be on its overview page. In the left-hand menu, click API permissions.
  2. Click + Add a permission.

  3. Select Microsoft Graph.

  4. Choose Application permissions. (This means the app acts on its own, not on behalf of a signed-in user).

  5. Select the following permissions by checking their boxes:

    Permission Name Why it's needed
    Directory.Read.All To read general directory information
    Directory.ReadWrite.All To read and update directory data
    Group.Read.All To see all Microsoft 365 groups
    Group.ReadWrite.All To update (add/remove members) all groups
    TeamMember.Read.All To see all members of Microsoft Teams
    TeamMember.ReadWrite.All To add and remove members from Teams
    User.Read.All To read user profiles (needed for membership sync)
  6. Click Add permissions.

  7. Repeat step 2 to add permissions for Exchange Online:

    • On the "Request API permissions" screen, select the "APIs my organization uses" tab.
    • Search for Exchange.
    • Select Office 365 Exchange Online.
    • Choose Application permissions.
    • Tick Exchange.ManageAsApp.
    • Click Add permissions.
  8. Grant Admin Consent: After adding all permissions, you'll see a banner or a button that says "Grant admin consent for your organization". Click this button! This authorizes the app to use these permissions across your entire Microsoft 365 environment.

You might need to confirm the consent.

Add a Certificate for Secure Authentication

Instead of using a username and password, we'll use a digital certificate for the script to securely authenticate with Microsoft 365.

  1. Generate Your Certificate:

    • Open PowerShell as an Administrator.
    • Run the following commands to create a self-signed certificate (valid for 3 years) and save it to your M365-Sync/Config folder. Replace C:\Scripts\M365-Sync with your actual script folder path.
    • Choose a Strong Password for the .pfx file and remember it! Replace "YourVeryStrongPasswordHere123!" with your chosen password.
    PowerShell
    # Define your script folder path
    $ScriptPath = "C:\Scripts\M365-Sync" # <--- IMPORTANT: Update this to your actual folder!
    
    # Generate a new self-signed certificate
    $cert = New-SelfSignedCertificate -CertStoreLocation Cert:\CurrentUser\My `
      -Subject "CN=M365SyncCert" ` # You can change "M365SyncCert"
      -KeySpec KeyExchange `
      -KeyExportPolicy Exportable `
      -KeyLength 2048 `
      -HashAlgorithm sha256 `
      -NotAfter (Get-Date).AddYears(3)
    
    # Convert your chosen password to a secure string
    $pwd = ConvertTo-SecureString -String "YourVeryStrongPasswordHere123!" -AsPlainText -Force
    
    # Export the certificate with the private key (.pfx) - this stays on your server!
    Export-PfxCertificate -Cert "Cert:\CurrentUser\My\$($cert.Thumbprint)" `
      -FilePath "$ScriptPath\Config\PrivateKeyCertificate.pfx" `
      -Password $pwd
    
    # Export the public key (.cer) - this gets uploaded to Microsoft Entra ID!
    Export-Certificate -Cert "Cert:\CurrentUser\My\$($cert.Thumbprint)" `
      -FilePath "$ScriptPath\Config\PrivateKeyCertificate.cer"
    
    Write-Host "`nCertificate Thumbprint: $($cert.Thumbprint)`n"
    
    • Keep the PowerShell window open! You'll need the Thumbprint shown in the output.
  2. Upload the Public Key (.cer) to App Registration:

    • Go back to your App Registration in the Microsoft Entra Admin Center.
    • In the left-hand menu, click Certificates & secrets.
    • Under Certificates, click Upload certificate.
    • Browse to your M365-Sync/Config folder and select the .cer file (e.g., PrivateKeyCertificate.cer).
    • Click Add.
    • Copy the "Thumbprint" value displayed after uploading. It should match the one from your PowerShell script.

    • Encrypt the Certificate Password (for config_general.json):

    • Go back to your PowerShell window (the one you used to generate the certificate).
    • Run the following command:

      PowerShell
      Import-Module Microsoft.PowerShell.Security
      Read-Host -AsSecureString | ConvertFrom-SecureString
      
    • When prompted, paste the password you chose earlier for the .pfx file (e.g., "YourVeryStrongPasswordHere123!") and press Enter.

    • Copy the long, encrypted string output. This is your MgApp_EncryptedCertificatePassword and EXOApp_EncryptedCertificatePassword for the configuration file.

Save Your App Details

You'll need these details for the next step (configuring config_general.json). Keep them handy:

Field Where to Find It in Microsoft Entra Admin Center Where to Use in config_general.json
Application (client) ID From the App Registration Overview page, next to the app name. MgClientID & EXOApp_AppID
Directory (tenant) ID From the App Registration Overview page, next to the app name. MgTenantID
Thumbprint From the "Certificates & secrets" section after uploading the .cer file. MgApp_CertificateThumbprint & EXOApp_CertificateThumbprint
Cert Path (.pfx) The full path to your PrivateKeyCertificate.pfx file on your server. MgApp_CertificatePath & EXOApp_CertificatePath
Encrypted Cert Password The long string output from ConvertFrom-SecureString in PowerShell. MgApp_EncryptedCertificatePassword & EXOApp_EncryptedCertificatePassword

Step 2: Configure config_general.json

This file holds all the main settings for how your sync script behaves.

Open config_general.json in a text editor (like Notepad++, VS Code, or even Notepad).

Here's an example of what it looks like. We'll go through the important parts below:

JSON
{
  "General": {
    "ScriptName": "M365 Teams Membership Sync",
    "EmailonError": true,
    "RemoveExtraGroupMembers": true,
    "EnableGroupRecursion": true,
    "SupportExchangeGroups": true
  },
  "MSGraph": {
    "MgProfile": "v1.0",
    "MgPermissionType": "Application",
    "MgApp_AuthenticationType": "CertificateThumbprint",
    "MgClientID": "YOUR_APPLICATION_ID_HERE", # <--- UPDATE THIS
    "MgTenantID": "YOUR_TENANT_ID_HERE",     # <--- UPDATE THIS
    "MgApp_CertificatePath": "$PSScriptRoot\\Config\\PrivateKeyCertificate.pfx", # <--- UPDATE THIS (if path is different)
    "MgApp_EncryptedCertificatePassword": "YOUR_ENCRYPTED_CERT_PASSWORD_HERE", # <--- UPDATE THIS
    "MgApp_CertificateThumbprint": "YOUR_CERTIFICATE_THUMBPRINT_HERE" # <--- UPDATE THIS
  },
  "ExchangeOnline": {
    "EXOPermissionType": "Application",
    "EXODisconnectWhenDone": true,
    "EXOApp_Organization": "yourdomain.onmicrosoft.com", # <--- UPDATE THIS (e.g., yourcompany.onmicrosoft.com)
    "EXOApp_AppID": "YOUR_APPLICATION_ID_HERE", # <--- USE THE SAME AS MgClientID
    "EXOApp_AuthenticationType": "CertificateThumbprint",
    "EXOApp_CertificateThumbprint": "YOUR_CERTIFICATE_THUMBPRINT_HERE", # <--- USE THE SAME AS MgApp_CertificateThumbprint
    "EXOApp_CertificatePath": "$PSScriptRoot\\Config\\PrivateKeyCertificate.pfx", # <--- USE THE SAME AS MgApp_CertificatePath
    "EXOApp_EncryptedCertificatePassword": "YOUR_ENCRYPTED_CERT_PASSWORD_HERE", # <--- USE THE SAME AS MgApp_EncryptedCertificatePassword
    "EXOApp_Scope": "[https://outlook.office365.com/.default](https://outlook.office365.com/.default)"
  },
  "Logging": {
    "FilePath": "$PSScriptRoot\\Logging\\M365 Teams Membership Sync-%date%.csv",
    "LogRotatePath": "$PSScriptRoot\\Logging\\M365 Teams Membership Sync-*.csv",
    "LogRetentionTime": "365d",
    "Enabled": true
  },
  "Email": {
    "From": {
      "Name": "M365 Teams Membership Sync Script",
      "Email": "<[email protected]>" # <--- UPDATE THIS
    },
    "ReplyTo": "<[email protected]>", # <--- UPDATE THIS
    "To": "<[email protected]>", # <--- UPDATE THIS (who should receive alerts)
    "Username": "<[email protected]>", # <--- UPDATE THIS (sender mailbox)
    "Password": "YOUR_SMTP_PASSWORD", # <--- IMPORTANT: Use App Password or secure method if MFA is on
    "Priority": "High",
    "Smtpserver": "smtp.office365.com",
    "UseSsl": true,
    "Port": "587"
  }
}

Below are the essential fields required in your config_general.json file

MSGraph (Microsoft Graph Configuration)

  • "MgClientID": Paste the Application (client) ID you saved from Step 1.

  • "MgTenantID": Paste the Directory (tenant) ID you saved from Step 1.

  • "MgApp_CertificatePath": Verify this path. $PSScriptRoot automatically means "the folder where the script is located." So, if your PrivateKeyCertificate.pfx is in M365-Sync/Config/, this path should be correct.

  • "MgApp_EncryptedCertificatePassword": Paste the long encrypted string you got from PowerShell in Step 1.

  • "MgApp_CertificateThumbprint": Paste the Thumbprint you saved from Step 1.

ExchangeOnline (Exchange Online Configuration)

  • "EXOApp_Organization": Replace yourdomain.onmicrosoft.com with your actual Microsoft 365 tenant domain (e.g., yourcompany.onmicrosoft.com).

  • "EXOApp_AppID": Use the same Application ID as MgClientID.

  • "EXOApp_CertificateThumbprint": Use the same Thumbprint as MgApp_CertificateThumbprint.

  • "EXOApp_CertificatePath": Use the same path as MgApp_CertificatePath.

  • "EXOApp_EncryptedCertificatePassword": Use the same encrypted password as MgApp_EncryptedCertificatePassword.

Email (Email Notification Settings)

This section configures email alerts for errors or important updates.

Update [email protected] and [email protected] with your organization's actual email addresses.

  • "Password": This is the password for the Username mailbox.

Important

  • If the sending mailbox (e.g., [email protected]) has Multi-Factor Authentication (MFA) enabled, you might need to generate an App Password for this script instead of using the regular mailbox password.

  • Also, ensure SMTP AUTH is enabled for the sending mailbox in your Microsoft 365 admin settings.

  • If using Microsoft 365 for sending emails, the following settings are usually correct:

    • Smtpserver: smtp.office365.com
    • Port: 587

Step 3: Map Your Groups and Teams

This is where you tell the script exactly which on-premise Active Directory groups should sync their members to which Microsoft 365 Groups or Teams.

Open config_group_team_mapping.json in your text editor. It uses a list format.

JSON
[
  {
    "MapType": "Group",
    "M365_Group_DisplayName": "TFH - Information Technology",
    "M365_Group_ID": "9ef508bc-...",
    "Groups": [
      {
        "M365_Group_DisplayName": "TFH - Information Technology (on-prem)",
        "M365_Group_ID": "cd747093-...",
        "Role": "Member"
      }
    ]
  },
  {
    "MapType": "Team",
    "M365_Team_DisplayName": "TFH - Information Technology",
    "M365_Team_ID": "9ef508bc-...",
    "Groups": [
      {
        "M365_Group_DisplayName": "TFH - Information Technology (on-prem)",
        "M365_Group_ID": "cd747093-...",
        "Role": "Member"
      }
    ]
  }
]

You'll need the unique ID for each Microsoft 365 Group or Team you want to sync to.

  1. Open PowerShell (you can use your regular user account, not necessarily Administrator for this part).

  2. Connect to Microsoft Graph:

PowerShell
Connect-MgGraph -Scopes "Group.Read.All"

Note

Follow any prompts to sign in with a Microsoft 365 admin account.

  1. To list all Microsoft 365 Groups and Teams and their IDs:
PowerShell
# List all Microsoft 365 Groups (includes Teams)
Get-MgGroup -Filter "groupTypes/any(c:c eq 'Unified')" | Select-Object DisplayName, Id, Description | Format-Table -AutoSize

# List only Teams
Get-MgGroup -Filter "resourceProvisioningOptions/Any(x:x eq 'Team')" | Select-Object DisplayName, Id, Description | Format-Table -AutoSize

Note

Copy the Id values for the Microsoft 365 Groups or Teams you want to sync and paste them into your config_group_team_mapping.json file.

  1. Enter the exact DisplayName of your on-premise Active Directory Security Group under AD_Security_Group_Name.

Step 4: Exclude System Accounts from Removal

Some members, like service accounts (e.g., [email protected]), should never be removed from a group, even if they're not in your on-premise AD sync group. This file protects them.

Open config_remove_account_exclusions.json in your text editor.

JSON
[
  {
    "UserPrincipalName": "[email protected]", # The user's login name
    "Id": "95fbe757-..." # The user's unique ID in Microsoft Entra ID
  }
  # Add more entries here for any other accounts you want to exclude
]

How to Find a User's ID (for exclusions)

  1. Go to the Microsoft Entra Admin Center: https://entra.microsoft.com

  2. Navigate to Identity > Users > All users.

  3. Search for the user (e.g., robot.it).

  4. Click on the user's name to open their profile.

  5. Copy the Object ID (which is the user's unique ID) from their profile. This is the Id you'll put in the JSON file.

Dry-run mode is your safety net. It simulates the sync process without making any actual changes to your Microsoft 365 Groups or Teams. This lets you check your configurations, see what would happen, and identify any errors before affecting live data.

Security Warning: Unsigned Script

This script is not digitally signed. If your system enforces execution policy restrictions, use the following method to temporarily bypass the policy for the session.

  1. Open PowerShell as an Administrator.
  2. Run the following commands:

    PowerShell
    # Temporarily allow scripts to run for this PowerShell session
    Set-ExecutionPolicy -Scope Process -ExecutionPolicy Bypass
    
    # Run the script in dry-run mode
    & "C:\Scripts\Teams Membership Sync\M365 Teams Membership Sync.ps1" `
      -Configuration "C:\Scripts\Teams Membership Sync\Config\config_general.json" `
      -DryRun $true
    

What to Expect in Dry-Run Mode

  • You'll see messages in the PowerShell console indicating what would happen (e.g., "Would add user X to group Y," "Would remove user Z from group A"). No actual changes are made.
  • A detailed .csv log file will be generated in your Logging/ folder, showing the simulated actions. Check this log carefully!
  • If you've configured email alerts, any errors found during the dry run will still trigger an email.

Step 6: Run in Production Mode (Go Live!)

Once you're confident that the dry-run showed the correct behavior and no unexpected changes, you can run the script in live mode to apply the updates to your Microsoft 365 environment.

  1. Open PowerShell as an Administrator.
  2. Run the following commands:

    PowerShell
    # Temporarily bypass execution policy for this session
    Set-ExecutionPolicy -Scope Process -ExecutionPolicy Bypass
    
    # Run the script normally (live sync)
    & "C:\Scripts\Teams Membership Sync\M365 Teams Membership Sync.ps1" `
      -Configuration "C:\Scripts\Teams Membership Sync\Config\config_general.json"
    

Info

Again, update C:\Scripts\M365-Sync to your actual script folder path.

What Happens in Production Mode

  • The script will add or remove members from your mapped Microsoft 365 Groups/Teams based on your configuration files.
  • All changes will be recorded in a detailed .csv file in your Logging/ folder.
  • Any errors or completion summaries can be emailed to you if you configured SMTP settings in config_general.json.

Step 7: Automate with Task Scheduler

To keep your groups consistently synced, you'll want the script to run automatically on a schedule (e.g., every hour). Windows Task Scheduler is perfect for this.

  1. Open Task Scheduler.
  2. Click Create Basic Task.
  3. Name the task (e.g., M365 Teams Sync Hourly).
  4. Under Trigger:
    • Select: Daily
    • Click Advanced settings
    • Set Repeat task every: 1 hour
    • Set for a duration of: 1 day
  5. Under Action:

    • Program/script:
    C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe
    
    • Add arguments:
    -NoLogo -NoProfile -ExecutionPolicy Bypass -File "C:\Scripts\Teams Membership Sync\M365 Teams Membership Sync.ps1" -Configuration "C:\Scripts\Teams Membership Sync\Config\config_general.json"
    

Note

The log file rotates automatically based on LogRetentionTime (e.g., 365 days). You don’t need to manage this manually.

Logging, Monitoring & Troubleshooting

Log File Location

All sync activities are recorded in a detailed CSV file:

Logging/M365 Teams Membership Sync-YYYY-MM-DD.csv

This .csv file contains detailed information about each group/team sync operation, including actions taken, errors, and results.

💠 Monitoring & Troubleshooting

  • Errors and warnings will be emailed to: [email protected] (if email is configured).
  • Always check the .csv log for the status of each sync, including any failed or skipped entries.
  • Excluded accounts (defined in config_remove_account_exclusions.json) will not be removed, even if they’re not in the source group.
  • Certificate expiry will result in authentication errors, ensure you rotate the .pfx file before it expires.

Tip

Consider scheduling a separate task to alert you 30 days before certificate expiration.


Final Thoughts

Managing group memberships across hybrid environments can easily become messy, repetitive, and error-prone. This guide helps you establish a reliable, secure sync between your on-premises Active Directory and Microsoft 365 Groups or Teams using a script-driven, certificate-based solution.

By following the setup in this guide, you gain full control over how memberships are managed and synchronized. The script does the heavy lifting: it checks for discrepancies, applies changes automatically, and logs every action in detail. You also get the flexibility to:

  • Simulate changes using dry-run mode
  • Schedule regular updates with Task Scheduler
  • Monitor everything through structured logs and email alerts

Once implemented, the sync process runs quietly in the background, ensuring your Microsoft 365 environment accurately reflects your AD structure. It reduces admin overhead, improves security, and eliminates the risk of manual mistakes, while staying transparent and easy to audit.

This setup is not just a convenience. It is a long-term strategy for maintaining consistency, security, and accountability in your Microsoft 365 deployment.