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.pfxcertificate. -
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
Majorversion is5or 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.GraphAllows the script to talk to Microsoft 365 (Groups, Teams, Users) PSFrameworkHelps with logging, configuration, and other script tasks MailozaurrUsed to send email notifications (like error alerts) - How to check your version: Open PowerShell (search for "PowerShell" in the Start menu) and type:
-
Installation Commands:
- Open PowerShell as an Administrator. (Search for "PowerShell", right-click, and select "Run as administrator").
-
Run the following commands one by one:
Installation Tips
- If you see a prompt about a "NuGet provider" or "untrusted repository," type
Yand pressEnterto 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¶
- Go to the Microsoft Entra Admin Center: https://entra.microsoft.com
- In the left-hand menu, navigate to Identity > Applications > App registrations.
-
Click
+ New registration.Fill in the details: * Name: Type
M365 Teams Membership Sync(or a name that makes sense to you). * Supported account types: SelectSingle 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.
- After creating the app, you'll be on its overview page. In the left-hand menu, click API permissions.
-
Click
+ Add a permission. -
Select Microsoft Graph.
-
Choose Application permissions. (This means the app acts on its own, not on behalf of a signed-in user).
-
Select the following permissions by checking their boxes:
Permission Name Why it's needed Directory.Read.AllTo read general directory information Directory.ReadWrite.AllTo read and update directory data Group.Read.AllTo see all Microsoft 365 groups Group.ReadWrite.AllTo update (add/remove members) all groups TeamMember.Read.AllTo see all members of Microsoft Teams TeamMember.ReadWrite.AllTo add and remove members from Teams User.Read.AllTo read user profiles (needed for membership sync) -
Click Add permissions.
-
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.
-
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.
-
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/Configfolder. ReplaceC:\Scripts\M365-Syncwith your actual script folder path. - Choose a Strong Password for the
.pfxfile 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
Thumbprintshown in the output.
-
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/Configfolder and select the.cerfile (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:
-
When prompted, paste the password you chose earlier for the
.pfxfile (e.g., "YourVeryStrongPasswordHere123!") and pressEnter. - Copy the long, encrypted string output. This is your
MgApp_EncryptedCertificatePasswordandEXOApp_EncryptedCertificatePasswordfor 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:
{
"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.$PSScriptRootautomatically means "the folder where the script is located." So, if yourPrivateKeyCertificate.pfxis inM365-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": Replaceyourdomain.onmicrosoft.comwith your actual Microsoft 365 tenant domain (e.g.,yourcompany.onmicrosoft.com). -
"EXOApp_AppID": Use the same Application ID asMgClientID. -
"EXOApp_CertificateThumbprint": Use the same Thumbprint asMgApp_CertificateThumbprint. -
"EXOApp_CertificatePath": Use the same path asMgApp_CertificatePath. -
"EXOApp_EncryptedCertificatePassword": Use the same encrypted password asMgApp_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 theUsernamemailbox.
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
- Smtpserver:
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.
[
{
"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.
-
Open PowerShell (you can use your regular user account, not necessarily Administrator for this part).
-
Connect to Microsoft Graph:
Note
Follow any prompts to sign in with a Microsoft 365 admin account.
- To list all Microsoft 365 Groups and Teams and their IDs:
# 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.
- Enter the exact
DisplayNameof your on-premise Active Directory Security Group underAD_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.
[
{
"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)¶
-
Go to the Microsoft Entra Admin Center: https://entra.microsoft.com
-
Navigate to Identity > Users > All users.
-
Search for the user (e.g.,
robot.it). -
Click on the user's name to open their profile.
-
Copy the
Object ID(which is the user's unique ID) from their profile. This is theIdyou'll put in the JSON file.
Step 5: Run in Dry-Run Mode (Highly Recommended First!)¶
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.
- Open PowerShell as an Administrator.
-
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.
- Open PowerShell as an Administrator.
-
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
.csvfile in yourLogging/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.
- Open Task Scheduler.
- Click Create Basic Task.
- Name the task (e.g.,
M365 Teams Sync Hourly). - Under Trigger:
- Select:
Daily - Click Advanced settings
- Set Repeat task every:
1 hour - Set for a duration of:
1 day
- Select:
-
Under Action:
- Program/script:
- Add arguments:
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:
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
.csvlog 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
.pfxfile 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.