首页 > 解决方案 > C# 活动目录搜索

问题描述

我有这个 powershell 函数,我想把它变成一个 C# 函数。我怎样才能把它放到 C# 中?

Get-ADComputer -filter {Name -Like 'myComp'} -property * | select DistinguishedName

标签: c#powershellactive-directory

解决方案


你应该能够很容易地做到这一点。添加对System.DirectoryServices.AccountManagement然后使用此代码的引用:

using (PrincipalContext ctx = new PrincipalContext(ContextType.Domain, 'YourDomain'))
{
    ComputerPrincipal computer = ComputerPrincipal.FindByIdentity (ctx, "name");

    if (computer != null)
    {
        // do whatever you need to do with your computer principal
        string distinguishedName = computer.DistinguishedName;
    }

}

更新:如果你不知道你的域名........ - 你也可以使用:

using (PrincipalContext ctx = new PrincipalContext(ContextType.Domain))

在这种情况下,将为您所在的当前域创建主体上下文。


推荐阅读