如何以编程方式找出 Windows 中哪台计算机是网域控制器?

我正在寻找一种方法,以确定什么名称/IP 地址的网域控制器是一个给定的域,客户端计算机连接到。

在我们公司,我们有很多用于测试的小型网络,其中大多数都有自己的小域名。例如,其中一个域名为“ TESTLAB”。我有一个属于 TESTLAB 域名的 Windows XP 工作站,我正在试图找出这个网域控制器的名称,这样我就可以去查看这个域名已经定义了哪些用户。在我们的实验室里有一个 Windows Server 2000和 Windows Server 2003的混合体(实际上可能有几个 NT 4服务器) ,所以找到一个两者都适用的解决方案是很好的。

在 Internet 上,似乎有各种各样的实用程序,比如 Windows Power Shell 或 nltest,但是这些都需要您下载并安装其他实用程序。我希望能找到一个不需要安装任何附加设备就能找到网域控制器的方法。

如果我想编写一个程序来查找当前域中的网域控制器或用户,我该怎么做呢?

243855 次浏览

In C#/.NET 3.5 you could write a little program to do:

using (PrincipalContext context = new PrincipalContext(ContextType.Domain))
{
string controller = context.ConnectedServer;
Console.WriteLine( "Domain Controller:" + controller );
}

This will list all the users in the current domain:

using (PrincipalContext context = new PrincipalContext(ContextType.Domain))
{
using (UserPrincipal searchPrincipal = new UserPrincipal(context))
{
using (PrincipalSearcher searcher = new PrincipalSearcher(searchPrincipal))
{
foreach (UserPrincipal principal in searcher.FindAll())
{
Console.WriteLine( principal.SamAccountName);
}
}
}
}

With the most simple programming language: DOS batch

echo %LOGONSERVER%

To retrieve the information when the DomainController exists in a Domain in which your machine doesn't belong, you need something more.

  DirectoryContext domainContext =  new DirectoryContext(DirectoryContextType.Domain, "targetDomainName", "validUserInDomain", "validUserPassword");


var domain = System.DirectoryServices.ActiveDirectory.Domain.GetDomain(domainContext);
var controller = domain.FindDomainController();

Run gpresult at a Windows command prompt. You'll get an abundance of information about the current domain, current user, user & computer security groups, group policy names, Active Directory Distinguished Name, and so on.

From command line query the logonserver env variable.

C:> SET L

LOGONSERVER='\'\DCNAME

In cmd on Windows, type the following commande:

nltest /dclist:{domainname}

It lists all domain controllers in particular domain

in Powershell: $env:logonserver