是否有可能找到公元本地计算机没有硬编码的域名?有可能、公元、域名、计算机

2023-09-08 12:42:26 作者:学渣又名抄霸

我使用C#来找到我的本地计算机的的objectGUID 通过查询Active Directory。要做到这一点,我目前使用的是 DirectorySearcher从,传递一个(硬codeD)路径为搜索根目录,然后按计算机名称筛选:

I'm using C# to find my local computer's objectGuid by querying Active Directory. To do this, I'm currently using a DirectorySearcher, passing it a (hardcoded) path as the search root, and then filtering by computer name:

string adRootPath = @"LDAP://OU=foo,DC=bar,DC=baz,DC=com";    
DirectoryEntry adRoot = new DirectoryEntry(adRootPath);

DirectorySearcher searcher = new DirectorySearcher(adRoot);
searcher.Filter = @"(&(objectCategory=Computer)(CN=" + Environment.MachineName + "))";

我不希望到c搜索根硬$ C $,并想知道是否有更好的办法。我想过只用一个空的搜索根,但我担心的计算机名称可能并不总是在不同的领域是独一无二的。

I don't want to hardcode the search root, and was wondering if there is a better way. I thought about just using an empty search root, but I was worried that computer names may not always be unique across different domains.

有没有更好的办法?

推荐答案

如果您使用的是.NET 3.5或更高版本,可以使用 PrincipalSearcher 和查询逐例如主要做你的搜索:

If you're on .NET 3.5 or newer, you can use a PrincipalSearcher and a "query-by-example" principal to do your searching:

// create your domain context
PrincipalContext ctx = new PrincipalContext(ContextType.Domain);

// define a "query-by-example" principal - here, we search for a ComputerPrincipal 
// and with the name of "MyPC"
ComputerPrincipal cp = new ComputerPrincipal(ctx);
cp.Name = "MyPC";

// create your principal searcher passing in the QBE principal    
PrincipalSearcher srch = new PrincipalSearcher(cp);

// find all matches
foreach(var found in srch.FindAll())
{
    // do whatever here - "found" is of type "Principal" - it could be user, group, computer.....          
}

如果您还没有 - 绝对阅读MSDN文章管理目录安全主体在.NET Framework 3.5 这表明很好如何使新功能的最佳使用 System.DirectoryServices.AccountManagement

If you haven't already - absolutely read the MSDN article Managing Directory Security Principals in the .NET Framework 3.5 which shows nicely how to make the best use of the new features in System.DirectoryServices.AccountManagement