I want to read Parent-GUID attribute from ActiveDirectory.
I have tried below code to read all attributes of AD object from ActiveDirectory.
Code
var dirEntry = new DirectoryEntry(directoryEntryPath);
var directorySearcher = new DirectorySearcher(dirEntry, filter)
{
CacheResults = false,
Tombstone = true,
};
var searchResult = directorySearcher.FindAll(); // get mutiple AD Objects
foreach (SearchResult search in searchResult)
{
foreach (DictionaryEntry prop in search.Properties) // here I get all attributes values But not able to find parent-GUID attribute
{
}
}
Using above code I am able to get all properties of AD Object but I am not able to get value of Parent-GUID attribute.
According to https://learn.microsoft.com/en-us/windows/desktop/adschema/a-parentguid this is a constructed attribute. This means it won't be included in search results. The docs also imply it's there to support DirSync which tells me that it might not be available outside of a DirSync search.
Do you mean something like that?:
string path = "CN=someone,OU=yourOrganizationalUnit,DC=example,DC=com";
DirectoryEntry root = new DirectoryEntry(path);
root.Parent.Guid.ToString(); // this will display you the GUID from the parent of your path
Hope this is what you meant!
Cheers,
ov4rlrd
var searchResult = directorySearcher.FindAll();
foreach(SearchResult search in searchResult)
{
DirectoryEntry de = search.GetDirectoryEntry();
Guid ParentGUID = new Guid((byte[])de.Parent.Properties["objectGUID"][0]);
...
}
Related
I can successfully get a complete list of all AD Attributes with the following code (including things like extensionAttribute1 - 15)
// get whatever attributes are available
List<string> allAttributes = new List<string>();
var context = new DirectoryContext(DirectoryContextType.Forest, "mydomain.com");
using (var schema = System.DirectoryServices.ActiveDirectory.ActiveDirectorySchema.GetSchema(context)) {
var userClass = schema.FindClass("user");
foreach (ActiveDirectorySchemaProperty property in userClass.GetAllProperties()) {
allAttributes.Add(property.Name);
}
}
However, when I retrieve a user account with the following code, most of these attributes (especially the extensionAttributes) are not present:
SearchResultCollection results;
DirectoryEntry de = new DirectoryEntry("LDAP://RootDSE");
DirectorySearcher ds = new DirectorySearcher("LDAP://" + de.Properties["defaultNamingContext"][0].ToString());
ds.Filter = "(&(objectCategory=User)(objectClass=person))";
results = ds.FindAll();
foreach (SearchResult sr in results) {
Console.WriteLine(sr.Properties["extensionAttribute1"][0].ToString()); // == null
}
What am I doing wrong?
most of these attributes (especially the extensionAttributes) are not present
That is normal. Attributes are only returned if they have a value. If an attribute does not have a value, it is not returned at all.
I'm trying to get Home Directory attribute value from active directory..
I used the following code:
public static void GetExchangeServerByWwidLdap(string wwid)
{
var exchange = string.Empty;
using (var ds = new DirectorySearcher())
{
ds.SearchRoot = new DirectoryEntry("GC:something");
ds.SearchScope = SearchScope.Subtree;
//construct search filter
string filter = "(&(objectclass=user)(objectcategory=person)";
filter += "(employeeid=" + wwid + "))";
ds.Filter = filter;
string[] requiredProperties = new string[] { "homeDirectory", "homemta" };
foreach (String property in requiredProperties)
ds.PropertiesToLoad.Add(property);
SearchResult result = ds.FindOne();
}
}
When I check result object data, I'm seeing only 2 values: "homemta" and "adspath".
Where is the "homeDirectory" value?
I entered AD website and searched the same values for same users - through the website I can see the all the data I searched for so I assuming that I have code issue somewhere.
What am I doing wrong?
You're trying to retrieve homeDirectory from global catalog.
It’s not there.
You can e.g. bind to the user by ADsPath property (i.e. “LDAP://…” string), then query the homeDirectory attribute of that user.
Or, if you only have a single domain, you can search within that domain instead of searching the GC. In this case you'll be able to retrieve all the properties you want.
I'm getting all users from all groups in LDAP using the follwoing code
using (SearchResultCollection results = searcher.FindAll())
{
foreach (SearchResult result in results)
{
ResultPropertyValueCollection userValueCollection =
result.Properties["member"];
foreach (var cn in userValueCollection)
{
System.Console.WriteLine(cn.ToString());
}
}
}
The out put is the following:
CN=068IGHf,OU=Personal,OU=Generic,OU=Privileged CN=064IMHf,OU=Technical,OU=Generic,OU=Privileged CN=060IGHJ,OU=Functional,OU=Generic,OU=Privileged CN=061UGHf,OU=Tester,OU=Generic,OU=Privileged
Q1: How can i get the type information of each user example: Personal, Technical, Functional
from the output?
Q2: How can i only get the userName only example: 068IGHF?
Don't use User.ToString() and then expect to be able to parse the resulting string.
The User object has methods and attributes of its own. Use them.
For example to get the common name:
DirectoryEntry user = new DirectoryEntry(result.Properties["member"]);
group.Users.Add(user.Properties.Item["cn"][0]);
How i get the list of active directory user attributes(not of particular user i.e.all attributes) e.g.cn,mail etc. using c#?
If you're on .NET 3.5 and up, you need to check out the classes in System.DirectoryServices.ActiveDirectory for this. You need to look at classes like ActiveDirectorySchema and ActiveDirectorySchemaClass.
You can get hold of the current AD schema by using:
ActiveDirectorySchema currSchema = ActiveDirectorySchema.GetCurrentSchema();
When you have the current schema, you can inspect the various class definitions, e.g.:
ActiveDirectorySchemaClass userSchema = currSchema.FindClass("person");
Once you have that object, you can inspect and enumerate its properties, things like:
MandatoryProperties
OptionalProperties
and so on to get an insight into the AD schema.
DirectoryEntry dir = new DirectoryEntry();
dir.Path = "LDAP://YourActiveDirServername ";
DirectorySearcher sea = new DirectorySearcher(dir);
sea.Filter = "(sAMAccountName=Uname)";
SearchResult seares = sea.FindOne();
StringBuilder str = new StringBuilder();
System.DirectoryServices.ResultPropertyCollection prop = seares.Properties;
ICollection coll = prop.PropertyNames;
IEnumerator enu = coll.GetEnumerator();
while (enu.MoveNext())
{
str.Append(enu.Current + " = " + seares.Properties[enu.Current.ToString()][0] + "\n");
}
Also, take a look at: http://www.codeproject.com/KB/system/everythingInAD.aspx
You could use WMI:
ObjectGetOptions objectGetOptions = new ObjectGetOptions(null, System.TimeSpan.MaxValue, true);
ManagementClass managementClass = new ManagementClass("root\\directory\\LDAP", "ads_user", objectGetOptions);
foreach (PropertyData dataObject in managementClass.Properties)
{
Console.WriteLine(dataObject.Name);
}
While ADExplorer does not list all the available attributes, I have found it a great tool for seeing what goes where.
You can download it from http://technet.microsoft.com/en-us/sysinternals/bb963907.aspx
UserPropertyList = new List<string>();
ActiveDirectorySchema currSchema = ActiveDirectorySchema.GetCurrentSchema();
ICollection Collection = currSchema.FindAllProperties();
IEnumerator Enumerator = Collection.GetEnumerator();
while (Enumerator.MoveNext())
{
UserPropertyList.Add(Enumerator.Current.ToString());
}
The above code will add all search attributes of Active Directory to the UserPropertyList...
Expanding on marc_s's answer here. Here is a complete code example that prints the common name and the actual attribute name.
ActiveDirectorySchema schema = ActiveDirectorySchema.GetCurrentSchema();
ActiveDirectorySchemaClass person = schema.FindClass("user");
foreach( ActiveDirectorySchemaProperty property in person.GetAllProperties() )
{
Console.WriteLine("{0} = {1}", property.CommonName, property.Name);
}
Example output.
Common-Name = cn
Instance-Type = instanceType
NT-Security-Descriptor = nTSecurityDescriptor
Object-Category = objectCategory
Object-Class = objectClass
Object-Sid = objectSid
SAM-Account-Name = sAMAccountName
Account-Expires = accountExpires
...
I'm trying to get a list of users from the Active Directory, who have a specified manager.
I used the following LDAP filter without success:
(manager=CN=Misterboss_n*)
However, it returns no result. Users have the following value in the manager attribute:
"CN=Misterboss_n,OU=xyz user,DC=xyz,DC=local"
What am I doing wrong? If I replace the above filter with something like this:
(givenName=John*)
it works okay (returns all users whose given name is John).
Wider context:
public List<ADUserDetail> GetAllEmployeesUnderMisterboss()
{
List<ADUserDetail> userlist = new List<ADUserDetail>();
string filter = "";
_directoryEntry = null;
DirectorySearcher directorySearch = new DirectorySearcher(SearchRoot);
directorySearch.Asynchronous = true;
directorySearch.CacheResults = true;
filter = "(manager=CN=Misterboss_n*)";
directorySearch.Filter = filter;
SearchResultCollection userCollection = directorySearch.FindAll();
foreach (SearchResult users in userCollection)
{
DirectoryEntry userEntry = new DirectoryEntry(users.Path, LDAPUser, LDAPPassword);
ADUserDetail userInfo = ADUserDetail.GetUser(userEntry);
userlist.Add(userInfo);
}
return userlist;
}
Thanks for the help!
I don't think there is a start-of-field search available for DN-typed properties. You will have to use the full DN of the manager. If you don't know the full DN, find the manager's LDAP object first and use its distinguishedName property.
Be sure to escape the DN value properly before building your filter - not every character that is valid in a DN is also valid in an LDAP filter expression:
* as \2a
( as \28
) as \29
\ as \5c
NUL as \00
/ as \2f
For code samples, see this related thread where I answered a very similar question: Getting all direct Reports from Active Directory