Get all members from nested group and add to a new group

  • November 26, 2018

This probably takes a bit of explanation. My use case is the following: I wish to expose an internal Wiki outside the corporate network. To accomplish this I use an Azure AD Application Proxy.

I also wish to restrict who has access to the application proxy and enforce multifactor authentication. This is easily accomplished by setting “User assignment required” in properties and adding a Conditional Access-policy.

However. A really weird drawback in Azure AD is lack of support for nested groups.

A dirty workaround is to enumerate members of the existing AD Group used by our Wiki to determine if a user has access, even if their member deep down in several layers of nesting, and then add all user objects to a new group that will be synced to Azure AD and added to Users and Groups for the application proxy.

$ADGroupName = "NestedGroup"
$ADGroupWithUsersName = "NewGroup"
$ADPath = "OU=Groups, OU=ServiceName, OU=Services, DC=contoso, DC=com"
$ADGroupDescription = "All users with access to the service. Autogenerated and used for Azure AD App Proxy"

# Create Group for all users

try
{
    New-ADGroup -Name $ADGroupWithUsersName -Path $ADPath -GroupScope Universal -Description $ADGroupDescription
}
catch [Microsoft.ActiveDirectory.Management.ADException]{
    Switch ($_.Exception.Message)
    {
        "The specified group already exists"
        {
            Write-Host "Group $ADGroupWithUsersName has already been created"
        }
        default
        {
            Write-Host "Unhandled ADException: $_"
        }
    }
}
catch {
    Write-Error $_ 
}

$users = Get-ADGroupMember -Identity $ADGroupName -Recursive

foreach ($u in $users)
{
    Add-ADGroupMember -Identity $ADGroupWithUsersName -Members $u
}

It’s probably best to run this as a scheduled task with the same frequency as your sync from AD to Azure AD. That way you don’t have to remember adding users to the group or running the script when people join/leave