将LDAP / AD脚本从VBS重构为C#

时间:2011-08-23 07:52:17

标签: c# vbscript active-directory ado

我需要重构一个处理从VBS到C#的LDAP,ADODB和ActiveDirectory的VBS。我被卡住的部分是连接(刚开始并且已经卡住了......很棒)。这是原始来源

Set objRootDSE = GetObject("LDAP://RootDSE")
strConfig = objRootDSE.Get("configurationNamingContext")
strDNSDomain = objRootDSE.Get("defaultNamingContext")

Set adoCommand = CreateObject("ADODB.Command")
Set adoConnection = CreateObject("ADODB.Connection")
adoConnection.Provider = "ADsDSOObject"

adoConnection.Open "Active Directory Provider"
adoCommand.ActiveConnection = adoConnection

strQuery = "<LDAP://dm1.com.local/OU=CN,OU=Users,OU=CMS Organizational,OU=CMS_Users_and_Groups,DC=cms,DC=local>;(&(objectCategory=person)(objectClass=user)(!useraccountcontrol:1.2.840.113556.1.4.803:=2));distinguishedName,lastLogon,whenCreated;subtree"

adoCommand.CommandText = strQuery
adoCommand.Properties("Page Size") = 100
adoCommand.Properties("Timeout") = 60
adoCommand.Properties("Cache Results") = False

Set adoRecordset = adoCommand.Execute

C#看起来像这样

DirectoryEntry dse = new DirectoryEntry("LDAP://RootDSE");
string config = dse.Properties["configurationNamingContext"].Value.ToString();
string domain = dse.Properties["defaultNamingContext"].Value.ToString();
Connection connection = new Connection();
connection.Provider = "ADsDSOObject";
connection.Open("ADsDSOObject", "", "", 0);

object records, parameters = "";

ADODB.Command command = new Command();
command.ActiveConnection = connection;
command.CommandText = "<LDAP://dm1.com.local/OU=CN,OU=Users,OU=CMS Organizational,OU=CMS_Users_and_Groups,DC=cms,DC=local>;(&(objectCategory=person)(objectClass=user)(!useraccountcontrol:1.2.840.113556.1.4.803:=2));distinguishedName,lastLogon,whenCreated;subtree";
command.Execute(out records, ref parameters, 0);

它给了我错误

Interface not supported (Provider)
 at ADODB.CommandClass.Execute(Object& RecordsAffected, Object& Parameters, Int32 Options)
at Adug.Program.Main(String[] args) in E:\...\Program.cs:line 66

2 个答案:

答案 0 :(得分:4)

我没有通过ADO查询LDAP的经验,但我已成功使用以下代码(此处简化),它使用了DirectorySearcher

DirectoryEntry directoryEntry = new DirectoryEntry(
      config.DirectoryConnectionString, 
      config.ActiveDirectoryUserName, 
      config.GetPassword(), 
      AuthenticationTypes.Secure);
DirectorySearcher ds = new DirectorySearcher(directoryEntry);

ds.PropertiesToLoad.Add("cn");
ds.PropertiesToLoad.Add("sAMAccountName");
ds.PropertiesToLoad.Add("mail");
ds.PropertiesToLoad.Add("displayName");

ds.Filter = "(objectClass=user)";

foreach (SearchResult result in ds.FindAll())
{
    string displayName = String.Empty;
    DirectoryEntry entry = result.GetDirectoryEntry();
    if (entry.Properties.Contains("displayName"))
            if (entry.Properties["displayName"].Count > 0)
                displayName  = entry.Properties["displayName"][0].ToString();
}

答案 1 :(得分:0)

使用System.DirectoryServices命名空间是在.NET中访问Active Directory的首选方法。 Daniel B 的回答应该让你朝着正确的方向前进。