Back to script library
Entra / Microsoft 365 · Groups

Create Entra ID dynamic administrative units

Creates dynamic administrative units scoped to 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 AdministrativeUnit.ReadWrite.All

Run it

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

Connect-MgGraph -NoWelcome -Scopes AdministrativeUnit.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
[array]$Departments = $Users.Department | Sort-Object -Unique
Write-Host ("Creating dynamic administrative units for the following departments: {0}" -f ($Departments -Join ", "))
# Retrieve current AUs because we should check them before creating another dynamic AU for
# a department if one already exists
[array]$CurrentAUs = Get-MgDirectoryAdministrativeUnit -All
ForEach ($Department in $Departments) {
$Description = ("Dynamic administrative unit created for the {0} department created {1}" -f $Department, (Get-Date))
$DisplayName = ("{0} dynamic administrative unit" -f $Department)
If ($DisplayName -in $CurrentAUs.DisplayName) {
Write-Host ("Administrative unit already exists for {0}" -f $DisplayName)
} Else {
# Create the new AU
$NewAUParameters = @{
displayName = $DisplayName
description = $Description
isMemberManagementRestricted = $false
}
$NewAdminUnit = (New-MgDirectoryAdministrativeUnit -BodyParameter $NewAUParameters)
}
# If the create worked, update the new AU to make it a dynamic AU with a membership rule
If ($NewAdminUnit) {
# Define the membership rule
$MembershipRule = '(user.department -eq "' + $Department + '" -and user.usertype -eq "member")'
# Create hash table with the parameters
$UpdateAUParameters = @{
membershipType = "Dynamic"
membershipRuleProcessingState = "On"
membershipRule = $MembershipRule
}
Try {
Update-MgDirectoryAdministrativeUnit -AdministrativeUnitId $NewAdminUnit.Id -BodyParameter $UpdateAUParameters -ErrorAction Stop
Write-Host ("Created dynamic administrative unit for the {0} department called {1}" -f $Department, $NewAdminUnit.DisplayName)
} Catch {
Write-Host ("Error updating {0} with dynamic properties" -f $NewAdminUnit.DisplayName )
}
}
} # End Foreach department
Attribution