PowerShell根据初始查询中的成员计数筛选AD组(也称为不使用-filter*)



PowerShell问题,适合精明的人。是否可以根据组大小筛选Get-ADGroup命令(也就是只返回大于x个成员的组(?我正在尝试以一种比以下更有效的方式进行过滤:Get-ADGroup -Filter *,然后运行成员计数检查,如在| where {$_.members.count -gt 10,000}或其他情况下。

但是我很难在初始过滤器上进行任何类型的成员计数检查,所以我不必返回单个域中的每个组对象,然后检查成员计数。这是因为我查询的AD实例有大量的AD组,需要很长时间才能先提取所有组,然后进行检查。

我尝试过下面的变体,但我猜最初的";成员";属性在您可以查询的属性集中不存在:

Get-ADGroup -Properties members -Filter {members -ge 10,000}

感谢您的帮助!

是否可以根据组大小筛选Get-ADGroup命令(也就是只返回大于x个成员的组(?

Active Directory支持的LDAP查询筛选器语法没有任何用于指定多值属性计数的功能。

您需要在目录中查询具有任何成员的组,然后计算客户端的结果集:

Get-ADGroup -LDAPFilter '(&(objectClass=group)(member=*))' -Properties member |Where-Object {
$_.member.Count -gt 10000
}

这就是如何通过多线程提高查询速度的方法,在本例中使用运行空间,其主要思想是获取域中的所有OU,并让每个运行空间同时查询特定的OU(与$threads中定义的查询数量一样多(。

这应该会大大提高脚本的速度,然而,这需要调整,如果同时运行太多线程,它很可能会失败。

$ErrorActionPreference = 'Stop'
# define the params that will be passed to the runspaces
$params = @{
LDAPFilter  = "(member=*)"
SearchScope = 'OneLevel'
Properties  = 'member'
}
# define the logic of the runspace
$scriptblock = {
param($params)
foreach($group in Get-ADGroup @params) {
if($group.Member.Count -gt 10000) {
$group
}
}
}
try {
# get all OUs
$ous = (Get-ADOrganizationalUnit -Filter *).DistinguishedName
# get all Domain Controllers available
# we don't want to make too many queries to the same DC!!
$dcs = (Get-ADDomainController -Filter *).Name
# define the number of threads that can run at the same time
# maybe you could use `$dcs.Count` as Threads
# this depends on your server's resources and your network
$threads = 10
$RunspacePool = [runspacefactory]::CreateRunspacePool(1, $threads)
$RunspacePool.Open()

$runspace = foreach($ou in $ous) {
$params['SearchBase'] = $ou
$params['Server'] = $dcs[$i++ % $dcs.Count]
$ps = [powershell]::Create()
$ps.AddScript($scriptblock).AddParameter('params', $params)
$ps.RunspacePool = $RunspacePool
[pscustomobject]@{
Instance = $ps
Task     = $ps.BeginInvoke()
}
}
# capture the output from each runspace here!
$result = foreach($r in $runspace) {
$r.Instance.EndInvoke($r.Task)
$r.Instance.foreach('Dispose')
}
}
catch {
Write-Warning $_.Exception.Message
}
finally {
$runspace.foreach('Clear')
$RunspacePool.foreach('Dispose')
}
$result | Format-Table

最新更新