Find computers in active directory

13,180

The attribute name is 'location'. As with all AD properties, you won't see it on a search result object if it doesn't have a value. I've fiddled with your code so that it would just work on my machine.

If you're only retrieving data and not planning to make any changes you don't need to call GetDirectoryEntry (which will impose another round-trip to the servers). Note the slight difference in syntax:

var rootDSE = new DirectoryEntry("LDAP://RootDSE");
var defaultNamingContext = rootDSE.Properties["defaultNamingContext"].Value.ToString();
var domainRootADsPath = String.Format("LDAP://{0}", defaultNamingContext);
var searchRoot = new DirectoryEntry(domainRootADsPath);

var filter = "(&(objectCategory=computer)(name=" + computerName + "))";
var directorySearch = new DirectorySearcher(searchRoot, filter);
var directorySearchResult = directorySearch.FindOne();

if (null != directorySearchResult)
{
    Console.WriteLine(directorySearchResult.Properties["cn"][0].ToString());
    if (directorySearchResult.Properties["location"].Count > 0)
    {
        Console.WriteLine(directorySearchResult.Properties["location"][0].ToString());
    }

    //It's not necessary to run GetDirectoryEntry unless you want to make a change
    DirectoryEntry deComp = directorySearchResult.GetDirectoryEntry();
    Console.WriteLine(deComp.Properties["cn"].Value.ToString());
    if (deComp.Properties["location"].Value != null)
    {
        Console.WriteLine(deComp.Properties["location"].Value.ToString());
    }
}
Share:
13,180
NoBullMan
Author by

NoBullMan

Updated on June 04, 2022

Comments

  • NoBullMan
    NoBullMan almost 2 years

    When I manually search for a computer using dsa.msc and open its properties, there is a "Location" tab. It might or might not have a value in it. When I try to get this information using directory services of .Net, I do not see a "location" property. I printed out all available properties and don't see it. Is it just not available or am I missing something? This is partial code:

    string sADPath = "LDAP://blah.blah.com";
    DirectoryEntry de = new DirectoryEntry(sADPath);
    
    string sFilter = "(&(objectCategory=computer)(name=" + sComputerName + "))";
    DirectorySearcher DirectorySearch = new DirectorySearcher(de, sFilter);
    SearchResult DirectorySearchResult = DirectorySearch.FindOne();
    
    if (null != DirectorySearchResult)
    {
        DirectoryEntry deComp = DirectorySearchResult.GetDirectoryEntry();
        oComputer.CN = deComp.Properties["cn"].Value.ToString();
        ....
    }
    

    Edit:

    I misunderstood the requirment! It is not the "physical" location of the computer I need but where in the AD hierarchy it is. It seems that a computer that is supposed to be in "abc.org --> A --> B" is not there but is located in "abc.org --> A --> C --> D". What I need is to be able to find the path "abc.org --> A --> C --> D" given a computer name.