How can I find out in what organizational units the computer is located? (Active Directory C #)

I want to find the most specific OU on which my computer belongs to C #. I have a code that will receive the information I need, but it does not feel reliable and requires complex analysis. Are there any better alternatives? Thoughts? Any help is appreciated!

Indeed, I want this to be tantamount to a command line command:

dsquery computer -name COMP-HERE

But I need it in C #, which seems problematic.

DirectorySearcher d = new DirectorySearcher("CN=COMP-HERE");
d.PropertiesToLoad.Add("adspath");
SearchResultCollection results = d.FindAll();
foreach (SearchResult searchResult in results) {
    foreach (string propertyKey in searchResult.Properties.PropertyNames) {
        ResultPropertyValueCollection valueCollection = searchResult.Properties[propertyKey];
        foreach (Object propertyValue in valueCollection) {
            Console.WriteLine(
            "{0}:{1}",
            propertyKey,
            propertyValue.ToString());
        }
    }
}
Console.ReadLine();
+5
source share
3 answers

Here's a solution using PrincipalContextand ComputerPrincipalin the namespaceSystem.DirectoryServices.AccountManagement

string machineOU;
using (var context = new PrincipalContext(ContextType.Domain))
using (var comp = ComputerPrincipal.FindByIdentity(context, Environment.MachineName))
{
    machineOU = String.Join(",", comp.DistinguishedName.Split(',')
                                                       .SkipWhile(s => !s.StartsWith("OU="))
                                                       .ToArray());
}

Linq , OU=..., ., OU.

System.DirectoryServices.AccountManagement ( ) .

PrincipalContext - , , . (PrincipalType.Machine), Active Directory (PrincipalType.Domain) Active Directory (PrincipalType.ApplicationDirectory).

new PrincipalContext(ContextType.Domain) PrincipalContext, Active Directory.

, FindBy...() ( UserPrincipal, ComputerPrincipal GroupPrincipal), AD, .

+2

google . , , , :

Active Directory

0

,

IEnumerable<string> machineOU;
using (var context = new PrincipalContext(ContextType.Domain))
using (var comp = ComputerPrincipal.FindByIdentity(context, Environment.MachineName))
{
  machineOU = comp.DistinguishedName.Split(',').Where(s => s.StartsWith("OU="));
}
0

All Articles