I'm trying to run the following cmdlet and save its output into my $query variable.
$query = Get-ADObject -Server $ldapServer -Credential $account -LDAPFilter "(&(objectCategory=Person)(objectClass=User)(!userAccountControl:1.2.840.113556.1.4.803:=2))" -SearchBase $ldapDN -Properties "GivenName", "Mail"
The LDAP query runs pretty well, (about 10 seconds on a 6000+ LDAP database). The returned resultset contains about 150 user objects. The strange thing happens when trying to itterate over the $query variable like so:
$query
Or:
foreach($object in $query){$object}
The iteration is incredibly slow (about 10-30 seconds per object)
Everything works fine and fast when the query is not saved to a variable, like running the command:
Get-ADObject -Server $ldapServer -Credential $account -LDAPFilter "(&(objectCategory=Person)(objectClass=User)(!userAccountControl:1.2.840.113556.1.4.803:=2))" -SearchBase $ldapDN -Properties "GivenName", "Mail"
Also when using a formatting cmdlet like so:
$query = Get-ADObject -Server $ldapServer -Credential $account -LDAPFilter "(&(objectCategory=Person)(objectClass=User)(!userAccountControl:1.2.840.113556.1.4.803:=2))" -SearchBase $ldapDN -Properties "GivenName", "Mail" | ft
However, I need the 'objects' for itteration. So Saving the text output doesn't help me here.
Even more confusing, is when itterated over once by just calling '$query', the following calls to the once printed objects are processed fast in all further calls.
Also, when the '-Properties' parameter is excluded from the 'Get-ADObject' cmdlet, the result saved to the $query varible is also processed quickly! The '-Properties' parameter appears to cause it to slow down, (so I guess it has nothing to do with memory limits, considering I have sufficient free memory).
Does anybody know:
Why this happens?
Why it happens only when using -properties?
How to solve the problem / some workaround (I can't use the 'DirectorySearcher' class, since it's not possible to specify a user to run the 'LDAP' query for that class, and calling 'runas' is not an option).
try with select-object
that convert $query
in a pscustomobject
$query = Get-ADObject -Server $ldapServer -Credential $account `
-LDAPFilter "(&(objectCategory=Person)(objectClass=User)(!userAccountControl:1.2.840.113556.1.4.803:=2))" -SearchBase $ldapDN `
-Properties "GivenName", "Mail" | select givenname, mail