如何编写递归导出含嵌套关系的AD组及成员层级清单的PowerShell脚本
AD嵌套组及成员导出PowerShell脚本方案
前置依赖
- 需提前安装ActiveDirectory模块(可通过Windows RSAT工具部署)
- 运行脚本的账号需具备AD域只读访问权限
- 需提前安装
ImportExcel模块用于导出Excel,执行Install-Module ImportExcel -Scope CurrentUser即可完成安装
实现逻辑
通过递归函数遍历每一个组的成员,遇到组类型的成员自动下钻查询,同时记录当前层级用于生成缩进,最终导出到Excel时不同层级对应不同的缩进量,完全匹配要求的层级展示效果。
完整脚本
# 加载所需模块 Import-Module ActiveDirectory Import-Module ImportExcel # 定义导出文件路径,可自行修改 $exportPath = "C:\AD_Group_Members_Hierarchy.xlsx" # 初始化结果存储数组 $results = @() # 递归获取组成员函数 function Get-ADGroupMemberRecursive { param ( [Parameter(Mandatory=$true)] [string]$GroupDN, [Parameter(Mandatory=$true)] [int]$Level, [Parameter(Mandatory=$true)] [string]$ParentGroup ) # 获取当前组成员,自动跳过无权限访问的对象 $members = Get-ADGroupMember -Identity $GroupDN -Recursive:$false -ErrorAction SilentlyContinue foreach ($member in $members) { # 构造每行数据对象 $row = [PSCustomObject]@{ "层级" = $Level "父组名称" = $ParentGroup "对象名称" = $member.Name "对象类型" = $member.ObjectClass "SamAccountName" = $member.SamAccountName "用户显示名称" = if ($member.ObjectClass -eq "user") { (Get-ADUser $member -Properties DisplayName).DisplayName } else { $null } "层级展示列" = (" " * ($Level * 8)) + "- $($member.Name)" } $global:results += $row # 成员为组时继续递归查询 if ($member.ObjectClass -eq "group") { Get-ADGroupMemberRecursive -GroupDN $member.DistinguishedName -Level ($Level + 1) -ParentGroup $member.Name } } } # 获取所有域内安全组,如需包含通讯组可将Filter改为 * $allTopGroups = Get-ADGroup -Filter {GroupCategory -eq "Security"} -ErrorAction SilentlyContinue # 遍历所有顶级组启动递归 foreach ($topGroup in $allTopGroups) { # 先写入顶级组本身的记录 $topRow = [PSCustomObject]@{ "层级" = 0 "父组名称" = "顶级组" "对象名称" = $topGroup.Name "对象类型" = "group" "SamAccountName" = $topGroup.SamAccountName "用户显示名称" = $null "层级展示列" = "Top Level Group - $($topGroup.Name)" } $results += $topRow # 递归查询该组成员 Get-ADGroupMemberRecursive -GroupDN $topGroup.DistinguishedName -Level 1 -ParentGroup $topGroup.Name } # 导出到Excel,自动冻结首行、表头加粗 $results | Export-Excel -Path $exportPath -WorksheetName "AD组层级结构" -AutoSize -FreezeTopRow -BoldTopRow Write-Host "导出完成,文件路径:$exportPath"
自定义调整说明
- 若要修改每层缩进量,调整
" " * ($Level * 8)中的数字即可,比如改为4就是每层缩进4个空格 - 不需要用户显示名称字段可删除对应逻辑,可大幅提升脚本运行速度
- 只需导出特定OU下的组时,可给
Get-ADGroup加上-SearchBase参数指定OU的可分辨名称
内容的提问来源于stack exchange,提问作者AaronO
相关产品推荐
相关产品推荐

