Reputation: 1255
I'm currently trying to write a function that allows me to get a number of additional attributes for an Active Directory user. To get those attributes I'm using System.DirectoryServices.DirectorySearcher
and it does work for some attributes like postalCode
or physicalDeliveryOfficeName
but not for others like profilePath
and I'm puzzled why.
I'm using code that looks similar to the following:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.DirectoryServices;
namespace ADReaderTest
{
class Program
{
static void Main(string[] args)
{
string name = "doe";
string additionalAttributes = "postalCode,profilePath";
DirectoryEntry adConnection =
new DirectoryEntry("GC://DC=contoso,DC=local", "CONTOSO\\User", "Password");
DirectorySearcher adSearch = new DirectorySearcher(adConnection);
adSearch.PropertiesToLoad.Add("cn");
adSearch.PropertiesToLoad.Add("SamAccountName");
adSearch.PropertiesToLoad.Add("objectSID");
foreach(string attribute in additionalAttributes.Split(',')){
adSearch.PropertiesToLoad.Add(attribute);
}
adSearch.Filter = "(&(|((&objectCategory=person)(objectClass=user))(objectCategory=group))(cn=*" + name + "*))";
SearchResultCollection adSearchResult = adSearch.FindAll();
Console.WriteLine("There were " + adSearchResult.Count + " matches for *" + name + "*");
foreach(SearchResult user in adSearchResult)
{
Console.WriteLine("Listing Properties for " + user.Path);
foreach (string prop in user.Properties.PropertyNames) {
Console.WriteLine("Prop: " + prop);
for(int i = 0; i < user.Properties[prop].Count; i++){
Console.WriteLine("\t" + user.Properties[prop][i].ToString());
}
}
}
Console.ReadLine();
}
}
}
If I debug that code I can see that postalCode
and profilePath
are both added to the list of properties that should be loaded but in the result user
only has postalCode
from the additionalAttributes
string. Even if I add *
to the properties that should be loaded profilePath
is missing. So what could I try to do to find out why attributes are missing?
Other things I've tried:
Get-ADUser <user> -Properties *
with the number of properties returned this way. The result is that the cmdlet returns way more attributes (~2 times as many). As some of those are certainly computed (e.g. AccountExpirationDate
and AccoutnExpires
) I'm not sure if it's a good indicator.Upvotes: 2
Views: 3026
Reputation: 1255
If anyone else is running into the same problem you should make sure your path/connection string is the right one. In this case (as indicated by the GC://
) I'm binding to the global catalog and the global catalog doesn't contain all attributes. If you actually want to query LDAP use the LDAP://
provider...
Upvotes: 2