Small Script to Grant Azure AD Roles to Groups

Today it is not possible to grant roles in Azure AD to groups and is not likely to support dynamic groups anytime soon. I created a little script that grants a role to all users in a group. It checks and only adds the role to users in the group who don’t already have it (by using the PowerShell Compare-Object command). Simply call the function passing name of the role to grant and the group whose members should be assigned the role. Note I do not remove the role if someone is removed from the group. That would be easy to do however it would remove anyone not in the group which may not be what you want since you may assign roles in other ways and not just via a single group membership.

For example:

Add-RoleToGroup “global reader” “group name”

Function Add-RoleToGroup
    param (
    #$roleName = "global reader"
    #$groupName = "group name"

    Write-Output "Granting $RoleName to $GroupName"

    $errorFound = $false

    #Note that only roles that are enabled, i.e. have at least one person in them will be found using this command so ensure at least one person is in the desired group
    $roleObject = Get-AzureADDirectoryRole | Where-Object {$_.displayName -eq $roleName}
    if($null -eq $roleObject)
        write-output "Cannot find role $roleName, it may be it is not enabled. Ensure the group already has at least one person in it"
        $errorFound = $true
    $groupObject = Get-AzureADGroup -SearchString "$groupName"
    if($null -eq $groupObject)
        write-output "Cannot find group $groupName"
        $errorFound = $true

        $groupMembers = Get-AzureADGroupMember -ObjectId $groupObject.ObjectId -All $true #| Select-Object -ExpandProperty UserPrincipalName
        $roleMembers = Get-AzureADDirectoryRoleMember -ObjectId $roleObject.ObjectId #| Select-Object -ExpandProperty UserPrincipalName

        $userDifferences = Compare-Object $groupMembers $roleMembers

        foreach($UserDifference in $UserDifferences)
            # if need to add
            if($UserDifference.SideIndicator -eq "<=")
                Write-Output "Adding $($UserDifference.InputObject.userprincipalname) to role"
                    {Add-AzureADDirectoryRoleMember -ObjectId $roleObject.ObjectId -RefObjectId $UserDifference.InputObject.ObjectId}
                catch { "Error adding role"}


Leave a Reply

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

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

Google photo

You are commenting using your Google 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

%d bloggers like this: