Senior Systems Engineer
Senior Systems Engineer

Reputation: 1141

Fixing simple Get-ADComputer : The server has returned the following error: invalid enumeration context

Why did the below simple AD cmdlets fail? I'm trying to get all Windows Server OS that is online in my AD domain, into variable.

$Servers = Get-ADComputer -Filter { Enabled -eq $True -and OperatingSystem -like "*Server*" } -Properties OperatingSystem -SearchBase "DC=DOMAIN,DC=com" | 
    Where-Object { Test-Connection $_.Name -Count 1 -Quiet } | 
        Select-Object -ExpandProperty Name

However, it is error:

Get-ADComputer : The server has returned the following error: invalid enumeration context.
+ $Servers = Get-ADComputer -Filter { Enabled -eq $True -and OperatingS ...
+            ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (:) [Get-ADComputer], ADException
    + FullyQualifiedErrorId : ActiveDirectoryServer:0,Microsoft.ActiveDirectory.Management.Commands.GetADComputer

How to make it works?

Upvotes: 0

Views: 4852

Answers (1)

Mathias R. Jessen
Mathias R. Jessen

Reputation: 174690

Get-ADComputer makes a paged query to Active Directory, and then starts outputting the results one-by-one.

If PowerShell takes too long between initially sending the query and then subsequently asking for the next page of the result set, the page cursor on the DC basically times out to free up resources and you get invalid enumeration context.

Instead of piping the output directly to Where-Object { Test-Connection ... }, which in turn "backs up" the pipeline every time we're waiting for a ping to timeout, make the Get-ADComputer call in a nested pipeline (enclose it it ()):

$Servers = (Get-ADComputer -Filter { Enabled -eq $True -and OperatingSystem -like "*Server*" } -Properties OperatingSystem -SearchBase "DC=DOMAIN,DC=com") | 
    Where-Object { Test-Connection $_.Name -Count 1 -Quiet } | 
        Select-Object -ExpandProperty Name

Upvotes: 2

Related Questions