【问题标题】:powershell retrieve members of group recursivelypowershell递归检索组的成员
【发布时间】:2025-12-07 13:50:01
【问题描述】:

我有一个非常大的审计项目,我希望实现自动化。

我需要获取属于组的每个用户的姓名、SamAccountName、职务和部门。问题是,该组内有组,而这些组内也有组。另一个问题是,大约 99% 的组的显示名称中都有星号(不是 SamAccountName)。

这是我目前拥有的代码,它工作正常,直到它收到一个名称中带有星号的组..(因此 .Replace("*","") 部分...。任何人都有任何想法如何解决这个问题?

function Get-NestedGroupMember {
[CmdletBinding()] 
param(
    [Parameter(Mandatory)] 
    [string]$Group 
)
$broke = @();
## Find all members  in the group specified 
$members = Get-ADGroupMember -Identity $Group 
foreach ($member in $members){
    ## If any member in  that group is another group just call this function again 
    if ($member.objectClass -eq 'group'){
        $memberGroup = $($member.Name).Replace("*", "")
        try{
            Get-NestedGroupMember -Group "$($memberGroup)"
        }catch{
            $broke += "$($memberGroup)`n"
        }
    }else{
        ## otherwise, just  output the non-group object (probably a user account)
        $member.Name  
    }
}
Write-Host "`nThe following groups could not be found automatically.`n`n$($broke)"
}

$getGroup = Read-Host -Prompt "Group name"

Get-NestedGroupMember $getGroup

【问题讨论】:

  • 而您没有使用-Recursive 参数,因为...

标签: powershell active-directory powershell-3.0


【解决方案1】:

正如 Bill_Stewart 所说,您正在尝试实现已经存在的功能。 Get-ADGroupMember 有一个 -Recursive 参数,它将搜索所有嵌套组并为您获取成员。然后,您可以将输出通过管道传递给一个选择并仅获取您关心的属性。

AD:
  TopGroup
    Betty
    Bob
    NestedGroup1
      Joe
      Frank
    NestedGroup2
      George
      Herman

使用-递归

Get-AdGroupMember TopGroup -Recursive | Select-Object SamAccountName
Betty
Bob
Joe
Frank
George
Herman

【讨论】: