Back to script library
Entra / Microsoft 365 · Groups

Create Entra ID dynamic groups

Creates dynamic Microsoft 365 groups for each department found on licensed member users.

Connect & set up

Run these once per session. All scopes are read-only unless the script makes changes.

Connect-MgGraph -NoWelcome -Scopes Directory.ReadWrite.All

Run it

The main script. Copy it, or download the .ps1 and run it from your console.

Connect-MgGraph -NoWelcome -Scopes Directory.ReadWrite.All
Write-Host "Finding user accounts to analyze departments..."
[array]$Users = Get-MgUser -All -Filter "assignedLicenses/`$count ne 0 and userType eq 'Member'" `
-ConsistencyLevel eventual -CountVariable UsersFound -Property Id, UserPrincipalName, Department, DisplayName
# Get list of departments
[array]$Departments = $Users.Department | Sort-Object -Unique
# Define any exclusions we don't want to create groups for
[array]$DepartmentExclusions = "EMAIL", "Shared Mailbox"
$Departments = $Departments | Where-Object {$_ -notin $DepartmentExclusions}
# Retrieve current groups because we should check them before creating another dynamic group for
# a department if one already exists
[array]$Groups = Get-MgGroup -Filter "groupTypes/any(c:c eq 'dynamicMembership') and groupTypes/any(x:x eq 'unified')" -All
Write-Host ("Checking dynamic Microsoft 365 groups for the following departments: {0}" -f ($Departments -Join ", "))
ForEach ($Dept in $Departments) {
$NewGroup = $Null; $NewTeam = $Null
Write-Host ("Checking groups for department {0}" -f $Dept)
$Description = ("Dynamic Microsoft 365 group created for the {0} department on {1}" -f $Dept, (Get-Date))
$DisplayName = ("{0} Dynamic group" -f $Dept)
$MailNickName = ("Dynamic.{0}.Group" -f ($Dept -replace " ",""))
$MembershipRule = '(User.Department -eq "' + $Dept +'")'
If ($DisplayName -in $Groups.DisplayName) {
Write-Host ("Group already exists for {0}" -f $Dept) -ForegroundColor Red
} Else {
# Create the new dynamic Microsoft 365 Group
$NewGroup = New-MgGroup -DisplayName $DisplayName -Description $Description -MailEnabled:$True -SecurityEnabled:$False `
-MailNickname $MailNickName -GroupTypes "DynamicMembership", "Unified" -MembershipRule $MembershipRule -MembershipRuleProcessingState "On"
}
# If the create worked, team-enable the new group
If ($NewGroup) {
Write-Host ("Team-enabling {0}..." -f $NewGroup.DisplayName) -ForegroundColor Yellow
# We sleep to allow background synchronization to happen
Start-Sleep -Seconds 15
$GroupUri = "https://graph.microsoft.com/v1.0/groups('" + $NewGroup.Id + "')"
$NewTeamParams = @{
"template@odata.bind"="https://graph.microsoft.com/v1.0/teamsTemplates('standard')"
"group@odata.bind"="$($GroupUri)"
}
$NewTeam = New-MgTeam -BodyParameter $NewTeamParams
If ($NewTeam) {
Write-Host ("Successfully team-enabled the {0}" -f $NewGroup.DisplayName)
}
}
} # End Foreach department
Attribution