Script for generating Azure AD dynamic groups

At a customer I needed to generate quite a few Azure AD dynamic groups, in order to create groups for each department, with users having a set of job titles. This is a good method to automatically assign application roles to a set of users based on their attributes, given that the attributes are managed by a sync from HR or similar. Here is how I did it.

Essentially, loop through an array of departments, generate a filter and create the group as follows.

PS: The script is actually perfectly safe to run in any tenant for test. It will create groups called “Dyn – Department 1” and “Dyn – Department 2”.

$departments = @(
    "Department 1"
    "Department 2"
)

$jobTitles = @(
    "Marketing title 1"
    "Marketing title 2"
    "Photographer"
)

$WhatIfPreference = $true
$VerbosePreference = "Continue"

$departments | ForEach-Object {
    # Generate DisplayName and Filter
    $DisplayName = "Dyn - {0}" -f $_
    $Filter = '(user.department -eq "{0}") -and (user.jobTitle -in ["{1}"])' -f $_, ($jobTitles -join '","')

    # Find existing any group
    $existingGroup = Get-AzureADMSGroup -Filter "displayName eq '$($DisplayName)'"
    if(!$existingGroup) {
        if(!$WhatIfPreference) {
            Write-Verbose "Creating $($DisplayName)"
            New-AzureADMSGroup -MembershipRule $Filter -DisplayName $DisplayName -SecurityEnabled:$true -MailEnabled:$false -MailNickname ([guid]::NewGuid().ToString()) -MembershipRuleProcessingState "On" -GroupTypes @("DynamicMembership") | Out-Null 
        } else {
            Write-Verbose "WHATIF: Creating $($DisplayName)"
        }
    } else {
        if($existingGroup.MembershipRule -cne $Filter) {
            if(!$WhatIfPreference) {
                Write-Verbose "Updating membershiprule for $($DisplayName)"
                Set-AzureADMSGroup -Id $existingGroup.Id -MembershipRule $Filter 
            } else {
            Write-Verbose "WHATIF: Creating $($DisplayName)"
            }
        }
    }    
} 

2 thoughts on “Script for generating Azure AD dynamic groups

  1. I always get the following when creating new dynamic group:

    New-AzureADMSGroup : A parameter cannot be found that matches parameter name ‘MembershipRule’.
    At line:1 char:20
    + New-AzureADMSGroup -MembershipRule “(user.department -contains “”Mark …
    + ~~~~~~~~~~~~~~~
    + CategoryInfo : InvalidArgument: (:) [New-AzureADMSGroup], ParameterBindingException
    + FullyQualifiedErrorId : NamedParameterNotFound,Microsoft.Open.MSGraphV10.PowerShell.NewMSGroup

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s