PowerShell中获取用户所属所有群组(含嵌套群组)ID列表的实现方法问询
PowerShell中获取用户所属所有群组(含嵌套群组)ID列表的实现方法问询
看起来你是想拿到某个用户的全部群组归属,包括直接加入的群组,以及这些群组又加入的上层群组(不管嵌套层级有多深),最终得到所有这些群组的ID列表,但卡在了递归枚举群组这一步对吧?
我给你两种常见场景下的解决方案,分别对应本地Active Directory和Azure AD环境:
一、本地Active Directory环境
首先确保你已经安装并导入了AD模块:
Import-Module ActiveDirectory
然后可以写一个递归函数来自动遍历所有嵌套群组:
function Get-NestedGroupMembership { param( [Parameter(Mandatory=$true)] [string]$UserIdentity, # 可以是用户名、用户ID或DistinguishedName [string[]]$GroupsFound = @() # 用来存储已找到的群组,避免重复 ) # 获取用户直接所属的所有群组 $directGroups = Get-ADUser -Identity $UserIdentity -Properties MemberOf | Select-Object -ExpandProperty MemberOf foreach ($group in $directGroups) { # 如果这个群组还没被记录,就加入列表 if ($group -notin $GroupsFound) { $GroupsFound += $group # 递归查询这个群组所属的上层群组 $GroupsFound = Get-NestedGroupMembership -UserIdentity $group -GroupsFound $GroupsFound } } # 返回所有群组的ObjectGUID(如果需要其他ID格式,比如SamAccountName,替换成对应属性即可) return Get-ADGroup -Identity $GroupsFound | Select-Object -ExpandProperty ObjectGUID }
使用方法:
# 替换成目标用户的标识(比如用户名、用户SID) $targetUser = "PanagiotisK" $allGroupIds = Get-NestedGroupMembership -UserIdentity $targetUser # 输出结果 $allGroupIds
二、Azure AD环境
如果是Azure AD的用户,推荐使用Microsoft Graph模块来实现(AzureAD模块已逐步淘汰):
首先安装并连接到Graph:
# 安装模块(如果没装过) Install-Module Microsoft.Graph.Users, Microsoft.Graph.Groups -Force -AllowClobber # 连接到Graph,需要相应权限 Connect-MgGraph -Scopes "User.Read.All", "Group.Read.All"
然后编写递归函数:
function Get-AzureADNestedGroupMembership { param( [Parameter(Mandatory=$true)] [string]$UserId, # 可以是用户邮箱、用户ID [string[]]$GroupsFound = @() ) # 获取当前对象(用户/群组)的直接所属群组 $directGroups = Get-MgMemberOf -UserId $UserId | Where-Object {$_.AdditionalProperties.'@odata.type' -eq '#microsoft.graph.group'} foreach ($group in $directGroups) { $groupId = $group.Id if ($groupId -notin $GroupsFound) { $GroupsFound += $groupId # 递归查询该群组的上层群组 $GroupsFound = Get-AzureADNestedGroupMembership -UserId $groupId -GroupsFound $GroupsFound } } return $GroupsFound }
使用方法:
$targetUser = "panagiotis@contoso.com" $allAzureGroupIds = Get-AzureADNestedGroupMembership -UserId $targetUser $allAzureGroupIds
这个思路的核心就是递归遍历+去重,每找到一个新群组,就继续查询它的父群组,直到没有更多上层群组为止,同时用数组记录已找到的群组,避免重复添加和死循环。你可以把这个逻辑整合到你已有的代码里~
备注:内容来源于stack exchange,提问作者Panagiotis Kontogiannis
相关产品推荐
相关产品推荐

