Get-ADUser 错误:枚举上下文无效

Use*_*Net 3 powershell active-directory

前几天我发布了这个问题 从分组对象中提取电子邮件

$OuUser = @{}

$OuUser = Get-AdUser -Properties * -Filter * -SearchBase "domain"   

$Duplicates = $OuUser | Select samaccountname, mail,UserPrincipalName |
    Group-Object Mail | Where{$_.Count -gt 1}

$Duplicates | Select Name,Count,@{l='Accounts';e={($_.Group|Select -Expand samaccountname) -join ';'}} | 
    Export-CSV E:\Damo\Duplicates.csv -NoTypeInfo
Run Code Online (Sandbox Code Playgroud)

该代码在一个域上工作正常,并针对 OU 中的一小组用户对其进行测试。

在我想测试的域上进行测试时,其中有很多用户,此代码失败。OU 中包含非电子邮件格式的电子邮件地址。它指向 Get-ADUser 的错误。

Get-ADUser : The server has returned the following error: invalid enumeration c
ontext.
At C:\scripts\CountEmailsDup.ps1:4 char:21
+ $OuUser = Get-AdUser <<<<  -Properties * -Filter * -SearchBase 'ou=external,o
u=user accounts,dc=bizdir,dc=nzpost,dc=co,dc=nz' -SearchScope OneLevel
    + CategoryInfo          : NotSpecified: (:) [Get-ADUser], ADException
    + FullyQualifiedErrorId : The server has returned the following error: inv
   alid enumeration context.,Microsoft.ActiveDirectory.Management.Commands.Ge
  tADUser
Run Code Online (Sandbox Code Playgroud)

我不明白为什么我会在一个域上出现此错误,而在另一个域上却没有。

Mat*_*att 5

您在这里遇到的最大问题是您从Get-ADUser. 根据您的评论,您正在吸引超过 900,000 个帐户。最重要的是,您正在提取这些用户的所有属性。那里有一丝疯狂。

虽然我不是很清楚你的错误意味着什么,但我知道每个得到它的人都会返回很多用户,而你显然是。第一步,以减轻,这是使用-ResultPageSizeGet-ADUser。您的里程可能会有所不同,但您需要试验要返回的记录数。500-1000 通常是一个好的开始。

我永远不会使用,-Properties *除非我为一个用户拉动并想查看所有内容。我强烈怀疑您是否在函数中使用了所有这些属性。为了效率,把自己限制在你需要的东西上。您显然需要指定Mail.

由于您是根据mail属性进行处理的,因此另一件事是将结果限制为仅具有填充邮件属性的结果。事情夫妇,你可以做的过滤器,例如“ ”,“...... ‘(由维斯珀评论)或’ @ ”根据你的评论

有一些带有 123 和 . 在它们中,所以我将不得不使用 length -gt 3 或其他东西来跳过它们。

对此不确定,我没有样本数据来测试理论,但使用管道也应该有所帮助,而不是保存结果只是为了在管道中使用它们。

Get-AdUser -Properties mail -Filter 'mail -like "*@*"' -SearchBase "domain" -ResultPageSize 1000 | 
    Group-Object Mail | 
    Where{$_.Count -gt 1} |
    Select Name,Count,@{l='Accounts';e={($_.Group|Select -Expand samaccountname) -join ';'}} | 
    Export-CSV E:\Damo\Duplicates.csv -NoTypeInfo
Run Code Online (Sandbox Code Playgroud)

  • 谢谢你。这里还有一些很棒的分析:https://social.technet.microsoft.com/wiki/contents/articles/32418.active-directory-troubleshooting-server-has-returned-the-following-error-invalid-enumeration-context .aspx。从他们的输出来看,一个非常简单的解决方案可能是向“SORT-OBJECT”添加一个管道,因为这将确保所有数据在传递之前都从管道中提取/您可以将其滑入而不添加变量。 (2认同)