Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
443 views
in Technique[技术] by (71.8m points)

azure active directory - Get a GroupTree of all AzureAD groups in powershell

I want to get a treeview of all my azureAD groups in powershell. I didnt find any public code of this. Before i start writing it myself does anyone have some code for this?

So something that outputs something like this:

 Group1
 Group2
 Group3
    ChildOfGroup3
    2ndChildOfGroup3
       ChildOfChild
 Group4
    ChildofGroup4
question from:https://stackoverflow.com/questions/65936043/get-a-grouptree-of-all-azuread-groups-in-powershell

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

make sure you have these modules installed:

Install-Module -Name Microsoft.Graph.Intune
Install-Module -Name AzureAD

code:

Connect-MSGraph
Connect-AzureAD

# help functions
function get_parent_groups_from_group ($ObjectId){
    $parents = Get-AADGroupMemberOf -groupId $ObjectId
    return $parents
}
function get_child_groups_from_group($ObjectId){
    Get-AzureADGroupMember -ObjectId $ObjectId | ? {$_.ObjectType -eq "Group"}
}

# get all the root groups
$root_groups = Get-AzureADGroup | ? {-not (get_parent_groups_from_group -ObjectId $_.ObjectID)}


# populate the children with recursion
function Recursion($groups, $max_depth, $current_depth=0){
    if($current_depth -ge $max_depth){
        return $groups
    }
    foreach($group in $groups){
        write-host "$("`t" * $current_depth)$($group.displayname)"
        $group | Add-Member -MemberType NoteProperty -Name children -Value "" -Force
        $group.children = get_child_groups_from_group -ObjectId $group.ObjectId
        if($group.children){
            $group.children = Recursion -groups $group.children -current_depth ($current_depth + 1) -max_depth $max_depth
        }
    }
    return $groups
}
$result = Recursion -groups $root_groups -max_depth 10

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...