在大型组织 AD 中递归列出用户

在大型组织 AD 中递归列出用户

我有一个脚本,可以递归列出组成员。问题是有超过 5K 个,所以我无法使用 Get-ADGroupMember,而且我还需要仅获取已启用的用户。尽管有微软文档,UAC 并不只显示已启用的用户。我有这个,但它没有过滤已启用的用户。

Function Get-MyLargeGroup {
[cmdletbinding()]
Param(
[Parameter(Position=0,ValueFromPipeline,ValueFromPipelineByPropertyName)]
[ValidateNotNullorEmpty()]
[string]$Name)

Begin {
    Write-Verbose "Starting $($MyInvocation.MyCommand)"
} #begin

Process {
Write-Verbose "Retrieving members from $Name"
$mygroup = Get-ADGroup -Identity $Name -Properties Members

foreach ($member in $mygroup.members) {
  $object = $member | Get-ADObject -Properties samaccountname,enabled
  if ($object.ObjectClass -eq 'Group') {
    Write-Verbose "Found nested group $($object.distinguishedname)"
    #recursively run this command for the nested group
    & $MyInvocation.MyCommand -name $object.Name
  } 
  else {
   Select-Object -InputObject $object -property ObjectClass,Name,SamAccountname,DistinguishedName,enabled
  }
} #foreach
} #process

End {
    Write-Verbose "Ending $($MyInvocation.MyCommand)"
} #end

} #end function

答案1

除非我不清楚 Get-ADUser 是否存在一些非常古老的限制,否则使用它进行返回超过 5k 个用户的查询应该没有问题。我刚刚在运行 PowerShell 4 的 2008 R2 机器上对其进行了测试,我的 Get-ADUser 查询仅使用 -Filter * 和 -SearchBase 参数就返回了近 7k 个用户。我也不清楚您为什么认为 UAC 与能够过滤已启用的用户有关。

无论如何,您实际上不需要递归脚本来完成此任务。您可以使用 LDAP 过滤器,它将返回名为的组成员的完整嵌套列表LDAP_MATCHING_RULE_IN_CHAIN

# first, get the DN of the group
$groupDN = (Get-ADGroup $Name).DistinguishedName

# now use it to get the nested members
Get-ADUser -LDAPFilter "(memberOf:1.2.840.113556.1.4.1941:=$groupDN)" -Property SamAccountname,Enabled | select ObjectClass,Name,SamAccountname,DistinguishedName,enabled

# alternatively, you can filter out the disabled users in the same query
Get-ADUser -LDAPFilter "(&(memberOf:1.2.840.113556.1.4.1941:=$groupDN)(!(userAccountControl:1.2.840.113556.1.4.803:=2)))" -Property SamAccountname,Enabled | select ObjectClass,Name,SamAccountname,DistinguishedName,enabled

答案2

您的脚本对已启用的用户不起作用的原因是“enabled”不是 Get-ADObject cmdlet 的有效属性。它对 Get-ADUser 和 Get-ADComputer 有效。使用 Get-ADObject,您需要解码 userAccountControl 属性的值

Get-ADGroupMember 上的 5,000 条记录限制是由域控制器上运行的 AD Web 服务设置的限制。您可以修改 ADWS 参数以允许返回更大的结果。

您可以使用以下 PowerShell 返回超过 5,000 名组成员,而无需修改 ADWS 参数:

(Get-ADGroup -Identity "SomeGroupName" -Properties Members).members

您需要使用 Get-ADObject cmdlet 循环遍历这些结果来查询其他对象信息。

相关内容