ShareFlow
All articles

Tutorial

Sync a distribution list with a security group

Automatically copy the members of a distribution list into a security group or Microsoft 365 group, with a commented Microsoft Graph PowerShell script.

Valentin Laurent13 min read
Share

In many organizations, the distribution list is the only list of people that is truly up to date: "Finance Team", "All Managers", "Kenya Office". It has been maintained for years, often by HR or the service desk. The problem is that it is only meant for sending email: it should not grant access to a SharePoint site, and it cannot feed a Teams team. Here is a Microsoft Graph PowerShell script that copies its members into a security group or a Microsoft 365 group, including the members of nested lists, with a dry run and safety guards.

Why sync instead of reusing the list

Three limits make a distribution list unusable as-is for managing access:

  • It is not built to grant permissions. A distribution list is for sending messages. For a SharePoint site, you need a security group or a Microsoft 365 group (see which type of group should manage SharePoint access).
  • A Microsoft 365 group only contains users. You cannot nest a list or another group in it: if your "Finance Team" list contains the "Accounting" sub-list, its members have to be expanded one by one.
  • Microsoft Graph cannot change a distribution list, nor a mail-enabled security group. Only security groups and Microsoft 365 groups can be changed through the API.

And the native solution has just gone away: the memberOf operator for Entra ID dynamic groups, which let you build a group from the members of other groups, stayed in preview. Microsoft ended it on November 3, 2026: groups that use it no longer update. Other dynamic rules (by department, by location…) are still available with an Entra ID P1 license, as long as user attributes are reliable, which is rarely the case.

What Graph can do with each type of group

Group typeRead its members (including nested)Change its members through Graph
Distribution listYesNo
Mail-enabled security groupYesNo
Security groupYesYes
Microsoft 365 groupYesYes (users only)

This table drives how the script works: any group as the source, a security group or Microsoft 365 group as the target.

Prerequisites

1. PowerShell 7.4 or later

# Installs the latest stable PowerShell 7
winget install --id Microsoft.PowerShell --source winget

Then open PowerShell 7 (pwsh), not Windows PowerShell 5.1.

2. Only the Microsoft Graph modules you need, not the whole SDK

The full Microsoft.Graph module weighs several hundred megabytes. The script only needs two sub-modules:

# Authentication and groups: that is all the script uses
Install-Module Microsoft.Graph.Authentication, Microsoft.Graph.Groups -Scope CurrentUser

3. Permissions

The script asks for two delegated Microsoft Graph permissions:

  • Group.Read.All, to find the groups and read their members;
  • GroupMember.ReadWrite.All, to add and remove members.

They require admin consent the first time. The account running the script must also be allowed to change the target groups: be an owner of those groups, or hold a role such as Groups Administrator.

What the script does

For each "source → target" pair:

  1. It finds both groups by ID, email address or exact name, and refuses if it finds none or several.
  2. It checks that the target can be changed: a security or Microsoft 365 group, otherwise it stops with a clear message.
  3. It reads all the users of the source, expanding nested lists and groups.
  4. It reads the direct members of the target, and works out who to add and who to remove.
  5. Without -Apply, it stops there and exports the plan to a CSV: this is the dry run.
  6. With -Apply, it applies the changes, unless a safety guard blocks the pair.

The two safety guards:

  • an empty source never empties the target. A source with no users is almost always a mistake (wrong group, incomplete read), not an intent;
  • too many removals at once block the pair: more than 5 people and more than 20% of the target. You check the dry run, then run again with -Force if it is intended.

I tested it with PowerShell 7.6 and Microsoft Graph PowerShell 2.41.2: a distribution list containing a sub-list, synced to a security group and a Microsoft 365 group, with additions, removals, an empty source and a distribution list as a target.

The full script

Copy it into a Sync-GroupMembership.ps1 file, or download it directly.

#Requires -Version 7.4
#Requires -Modules Microsoft.Graph.Authentication, Microsoft.Graph.Groups

<#
.SYNOPSIS
    Copies the members of a distribution list (or any group) into a security
    group or a Microsoft 365 group, expanding nested groups.

.DESCRIPTION
    For each "source -> target" pair:
      1. the script reads ALL the users of the source, including those of
         nested lists and groups (transitive members);
      2. it reads the users who are direct members of the target;
      3. it works out who to add and who to remove so the target matches;
      4. without -Apply, it stops there and exports the plan to a CSV (dry run);
      5. with -Apply, it applies the additions and removals, unless a safety
         guard blocks the pair (empty source, too many removals at once).

    Pairs come either from the -Source and -Target parameters (a single pair),
    or from a CSV file (-ConfigPath) with the columns Source;Target.
    A source or target can be given by its ID, its email address or its exact
    display name.

.PARAMETER Source
    Reference group: distribution list, security group or Microsoft 365 group.

.PARAMETER Target
    Group to update: security group or Microsoft 365 group.
    Mail-enabled security groups and distribution lists cannot be changed
    through Microsoft Graph.

.PARAMETER ConfigPath
    CSV file (; separator) with one line per pair: Source;Target

.PARAMETER Apply
    Actually applies the changes. Without this switch: dry run.

.PARAMETER MaxRemovePercent
    Safety guard: if a pair would remove more than this percentage of the
    target's members (and more than 5 people), it is blocked. 20% by default.

.PARAMETER Force
    Ignores the removal safety guard. Use it after reading the dry run.

.PARAMETER ReportFolder
    Folder for the CSV reports. Default: your Documents folder.

.PARAMETER UseDeviceCode
    Sign in with a code (page https://login.microsoft.com/device), useful when
    the sign-in window does not open (embedded terminal, server with no browser).

.PARAMETER TenantId
    For an unattended scheduled run: tenant ID.

.PARAMETER ClientId
    For a scheduled run: ID of the Entra ID application.

.PARAMETER CertificateThumbprint
    For a scheduled run: thumbprint of the application's certificate,
    installed in the certificate store of the machine running the script.

.EXAMPLE
    # Dry run for a single pair
    .\Sync-GroupMembership-en.ps1 -Source "finance-team@contoso.com" -Target "SG-Finance-SharePoint"

.EXAMPLE
    # Actually apply every pair from a file
    .\Sync-GroupMembership-en.ps1 -ConfigPath ".\pairs.csv" -Apply
#>

[CmdletBinding(DefaultParameterSetName = "Pair")]
param(
    [Parameter(Mandatory, ParameterSetName = "Pair")] [string] $Source,
    [Parameter(Mandatory, ParameterSetName = "Pair")] [string] $Target,
    [Parameter(Mandatory, ParameterSetName = "File")] [string] $ConfigPath,
    [switch] $Apply,
    [ValidateRange(1, 100)] [int] $MaxRemovePercent = 20,
    [switch] $Force,
    [string] $ReportFolder = (Join-Path $HOME "Documents"),
    [switch] $UseDeviceCode,
    [string] $TenantId,
    [string] $ClientId,
    [string] $CertificateThumbprint
)

$ErrorActionPreference = "Stop"
$stamp = Get-Date -Format "yyyyMMdd-HHmmss"

# --------------------------------------------------------------------------
# 1. Connect to Microsoft Graph
# --------------------------------------------------------------------------
if ($CertificateThumbprint) {
    # Scheduled run: the application signs in with its certificate, with no
    # user. It needs the application permissions GroupMember.ReadWrite.All
    # and Group.Read.All.
    Connect-MgGraph -TenantId $TenantId -ClientId $ClientId -CertificateThumbprint $CertificateThumbprint -NoWelcome
}
else {
    # Manual run: you sign in with your own account.
    # Group.Read.All to read the groups, GroupMember.ReadWrite.All to change members.
    # -UseDeviceCode: sign in with a code, useful if the sign-in window does not show up.
    Connect-MgGraph -Scopes "Group.Read.All", "GroupMember.ReadWrite.All" -NoWelcome -UseDeviceCode:$UseDeviceCode
}

# --------------------------------------------------------------------------
# 2. Helper functions
# --------------------------------------------------------------------------

# Finds a group from its ID, email address or exact display name.
# Fails if no group or several groups match.
function Resolve-Group([string] $Ref) {
    $props = "id,displayName,mail,mailEnabled,securityEnabled,groupTypes"
    $guid = [guid]::Empty
    if ([guid]::TryParse($Ref, [ref] $guid)) {
        return Get-MgGroup -GroupId $Ref -Property $props -ErrorAction Stop
    }
    $escaped = $Ref.Replace("'", "''")
    $filter = if ($Ref -like "*@*") { "mail eq '$escaped'" } else { "displayName eq '$escaped'" }
    $found = @(Get-MgGroup -Filter $filter -Property $props -All -ErrorAction Stop)
    if ($found.Count -ne 1) { throw "Group '$Ref': $($found.Count) result(s), exactly 1 is required." }
    return $found[0]
}

# Returns a readable group type.
function Get-GroupKind($Group) {
    if ($Group.GroupTypes -contains "Unified")              { return "Microsoft 365" }
    if ($Group.SecurityEnabled -and -not $Group.MailEnabled) { return "Security" }
    if ($Group.SecurityEnabled -and $Group.MailEnabled)      { return "Mail-enabled security" }
    return "Distribution list"
}

# Returns the users of a group, as a dictionary Id -> UPN.
# -Transitive: expands nested groups (for the source).
# Without -Transitive: direct members only (for the target).
function Get-UserMembers([string] $GroupId, [switch] $Transitive) {
    $members = if ($Transitive) {
        Get-MgGroupTransitiveMember -GroupId $GroupId -All -ErrorAction Stop
    } else {
        Get-MgGroupMember -GroupId $GroupId -All -ErrorAction Stop
    }
    $users = @{}
    foreach ($m in $members) {
        # Keep users only: no contacts, devices or groups.
        if ($m.AdditionalProperties["@odata.type"] -eq "#microsoft.graph.user") {
            $users[$m.Id] = $m.AdditionalProperties["userPrincipalName"]
        }
    }
    return $users
}

# --------------------------------------------------------------------------
# 3. Pairs to process
# --------------------------------------------------------------------------
$pairs = if ($PSCmdlet.ParameterSetName -eq "File") {
    Import-Csv -Path $ConfigPath -Delimiter ";" | Where-Object { $_.Source -and $_.Target }
} else {
    , [pscustomobject]@{ Source = $Source; Target = $Target }
}

$report = [System.Collections.Generic.List[object]]::new()

# Adds a line to the report.
function Add-Report($Pair, $Action, $Upn, $Status, $Message = "") {
    $report.Add([pscustomobject]@{
        Source = $Pair.Source; Target = $Pair.Target; Action = $Action
        Member = $Upn; Status = $Status; Message = $Message
    })
}

# --------------------------------------------------------------------------
# 4. Process each pair
# --------------------------------------------------------------------------
foreach ($pair in $pairs) {
    Write-Host ""
    Write-Host "=== $($pair.Source)  ->  $($pair.Target)" -ForegroundColor Cyan

    try {
        $src = Resolve-Group $pair.Source
        $tgt = Resolve-Group $pair.Target
    }
    catch {
        Write-Warning $_.Exception.Message
        Add-Report $pair "Pair" "" "Error" $_.Exception.Message
        continue
    }

    # Graph can only change security groups and Microsoft 365 groups.
    $kind = Get-GroupKind $tgt
    if ($kind -notin "Security", "Microsoft 365") {
        $msg = "The target is a '$kind' group: Microsoft Graph cannot change its members."
        Write-Warning $msg
        Add-Report $pair "Pair" "" "Error" $msg
        continue
    }

    $srcUsers = Get-UserMembers $src.Id -Transitive
    $tgtUsers = Get-UserMembers $tgt.Id

    # Safety guard 1: an empty source would empty the target. That is almost
    # always a sign of a mistake (wrong group, incomplete read), not an intent.
    if ($srcUsers.Count -eq 0) {
        $msg = "The source has no users: pair skipped so the target is not emptied."
        Write-Warning $msg
        Add-Report $pair "Pair" "" "Blocked" $msg
        continue
    }

    # The diff: who is missing from the target, and who is no longer in the source.
    $toAdd    = @($srcUsers.Keys | Where-Object { -not $tgtUsers.ContainsKey($_) })
    $toRemove = @($tgtUsers.Keys | Where-Object { -not $srcUsers.ContainsKey($_) })

    Write-Host ("Source ({0}): {1} user(s). Target ({2}): {3}. To add: {4}, to remove: {5}." -f `
        (Get-GroupKind $src), $srcUsers.Count, $kind, $tgtUsers.Count, $toAdd.Count, $toRemove.Count)

    # Safety guard 2: too many removals at once.
    $removePercent = if ($tgtUsers.Count) { 100 * $toRemove.Count / $tgtUsers.Count } else { 0 }
    $blocked = (-not $Force) -and ($toRemove.Count -gt 5) -and ($removePercent -gt $MaxRemovePercent)
    if ($blocked) {
        $msg = "{0} removals ({1:N0}% of the target): above the {2}% threshold. Check, then run again with -Force." -f `
            $toRemove.Count, $removePercent, $MaxRemovePercent
        Write-Warning $msg
        Add-Report $pair "Pair" "" "Blocked" $msg
    }

    # Additions, then removals. In a dry run, only the plan is recorded.
    foreach ($id in $toAdd) {
        $upn = $srcUsers[$id]
        if (-not $Apply -or $blocked) { Add-Report $pair "Add" $upn "Planned"; continue }
        try {
            New-MgGroupMember -GroupId $tgt.Id -DirectoryObjectId $id -ErrorAction Stop
            Add-Report $pair "Add" $upn "OK"
        }
        catch { Add-Report $pair "Add" $upn "Error" $_.Exception.Message }
    }
    foreach ($id in $toRemove) {
        $upn = $tgtUsers[$id]
        if (-not $Apply -or $blocked) { Add-Report $pair "Remove" $upn "Planned"; continue }
        try {
            Remove-MgGroupMemberByRef -GroupId $tgt.Id -DirectoryObjectId $id -ErrorAction Stop
            Add-Report $pair "Remove" $upn "OK"
        }
        catch { Add-Report $pair "Remove" $upn "Error" $_.Exception.Message }
    }
}

# --------------------------------------------------------------------------
# 5. Report
# --------------------------------------------------------------------------
if (-not (Test-Path $ReportFolder)) { New-Item -ItemType Directory -Path $ReportFolder | Out-Null }
$mode = if ($Apply) { "apply" } else { "dryrun" }
$reportPath = Join-Path $ReportFolder "Group-sync-$mode-$stamp.csv"
$report | Export-Csv -Path $reportPath -NoTypeInformation -Encoding UTF8

Write-Host ""
if (-not $Apply) {
    Write-Host "Dry run: no change applied. Run again with -Apply after checking the report." -ForegroundColor Yellow
}
$errors = @($report | Where-Object Status -in "Error", "Blocked").Count
Write-Host ("Done. {0} line(s) in the report, including {1} error(s) or block(s)." -f $report.Count, $errors) `
    -ForegroundColor $(if ($errors) { "Yellow" } else { "Green" })
Write-Host "Report: $reportPath"

Disconnect-MgGraph | Out-Null

Run it

For a single pair, first as a dry run:

.\Sync-GroupMembership.ps1 -Source "finance-team@contoso.com" -Target "SG-Finance-SharePoint"

Read the Group-sync-dryrun-….csv file in your Documents folder, then apply:

.\Sync-GroupMembership.ps1 -Source "finance-team@contoso.com" -Target "SG-Finance-SharePoint" -Apply

For several pairs, prepare a pairs.csv file, one line per sync. The same source can feed several targets:

Source;Target
finance-team@contoso.com;SG-Finance-SharePoint
finance-team@contoso.com;Finance (Teams team)
all-managers@contoso.com;SG-Managers-Intranet
.\Sync-GroupMembership.ps1 -ConfigPath ".\pairs.csv"           # dry run
.\Sync-GroupMembership.ps1 -ConfigPath ".\pairs.csv" -Apply    # apply

Schedule it

A sync is only useful if it runs on its own, for example every night. For that, no user account or password in the script:

  1. Create an application in Microsoft Entra ID, with the Microsoft Graph application permissions Group.Read.All and GroupMember.ReadWrite.All, and admin consent.
  2. Give it a certificate rather than a client secret: the certificate is installed on the machine running the script, and its private key never leaves that machine.
  3. Schedule the script (Windows Task Scheduler, Azure Automation…) with the -TenantId, -ClientId and -CertificateThumbprint parameters, plus -ConfigPath and -Apply.
  4. Watch the reports: a "Blocked" or "Error" line should trigger a check.

Pitfalls to know about

  • The delay between Exchange and Entra ID. A change made to a distribution list in Exchange takes a moment to show up in Entra ID. In my test, one minute was enough, but don't run the sync right after changing a list.
  • Only users are copied. External contacts in a distribution list cannot be members of a Microsoft 365 group: the script skips them.
  • The target must be fed by the script only. Someone added by hand to the target will be removed at the next sync if they are not in the source. For an exception, add them to the distribution list, not to the group.
  • Removing someone cuts off access. Removing someone from a Microsoft 365 group also removes them from the associated Teams team and SharePoint site. That is the point, but it is also why removals are protected by a safety guard.
  • Owners are not managed. The script only touches members. The owners of a Microsoft 365 group are managed separately.

What I recommend you do

  1. List the distribution lists used for access, in your sites' permissions and in your Teams teams.
  2. Create a security or Microsoft 365 group to match each one, and sync it with this script rather than filling it by hand.
  3. Always start with the dry run, and have the list owner review it.
  4. Schedule the sync with a certificate, never with an account and password stored in the script.
  5. If you used the memberOf operator, your dynamic groups have been frozen since November 3, 2026: now is the time to replace them.

Automation with Microsoft Graph and PowerShell is part of the training I run for administrators, Run SharePoint at tenant scale. And if you want to bring order to your groups, that is the kind of project I support through consulting.

Sources

Share this article

Know a colleague or client who deals with this? Send them the article in one click.

Read next

Comments

Loading comments…

Leave a comment

Comments are reviewed before they are published. Only your first name and last-name initial are shown.