首页 > 解决方案 > 在 powershell 中获取所有 AzureAD 组的 GroupTree

问题描述

我想在 powershell 中获取我所有 azureAD 组的树视图。我没有找到任何公开的代码。在我自己开始编写之前,是否有人为此提供了一些代码?

所以输出类似这样的东西:

 Group1
 Group2
 Group3
    ChildOfGroup3
    2ndChildOfGroup3
       ChildOfChild
 Group4
    ChildofGroup4

标签: powershellazure-active-directory

解决方案


确保您已安装这些模块:

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

代码:

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

推荐阅读