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

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.

 1$ADGroupName = "NestedGroup"
 2$ADGroupWithUsersName = "NewGroup"
 3$ADPath = "OU=Groups, OU=ServiceName, OU=Services, DC=contoso, DC=com"
 4$ADGroupDescription = "All users with access to the service. Autogenerated and used for Azure AD App Proxy"
 5
 6# Create Group for all users
 7try
 8{
 9    New-ADGroup -Name $ADGroupWithUsersName -Path $ADPath -GroupScope Universal -Description $ADGroupDescription
10}
11catch [Microsoft.ActiveDirectory.Management.ADException]{
12    Switch ($_.Exception.Message)
13    {
14        "The specified group already exists"
15        {
16            Write-Host "Group $ADGroupWithUsersName has already been created"
17        }
18        default
19        {
20            Write-Host "Unhandled ADException: $_"
21        }
22    }
23}
24catch {
25    Write-Error $_ 
26}
27
28$users = Get-ADGroupMember -Identity $ADGroupName -Recursive
29
30foreach ($u in $users)
31{
32    Add-ADGroupMember -Identity $ADGroupWithUsersName -Members $u
33}

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