#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