开发者

Get machine name from Active Directory

I have performed an "LDAP://" query to get a list of computers within a specified OU, my issue is not being able to collect just the computer "name" or even "cn".

        DirectoryEntry toShutdown = new DirectoryEntry("LDAP://" + comboBox1.Text.ToString());
        DirectorySearcher machineSearch = new DirectorySearcher(toShutdown);
        //machineSearch.Filter = "(objectCatergory=computer)";
        machineSearch.Filter = "(objectClass=computer)";
        machineSearch.SearchScope = SearchScope.Subtree;
        machineSearch.PropertiesToLoad.Add("name");
        SearchResultCollect开发者_运维问答ion allMachinesCollected = machineSearch.FindAll();
        Methods myMethods = new Methods();
        string pcName;
        foreach (SearchResult oneMachine in allMachinesCollected)
        {
            //pcName = oneMachine.Properties.PropertyNames.ToString();
            pcName = oneMachine.Properties["name"].ToString();
            MessageBox.Show(pcName);
        }

Help much appreciated.


If you can upgrade to .NET 3.5, I would definitely recommend doing so.

With .NET 3.5, you get a new System.DirectoryServices.AccountManagement namespace which makes a lot of these takes much easier.

To find all computers and enumerate them, you'd do something like this:

// define a domain context - use your NetBIOS domain name
PrincipalContext ctx = new PrincipalContext(ContextType.Domain, "YOURDOMAIN");

// set up the principal searcher and give it a "prototype" of what you want to
// search for (Query by Example) - here: a ComputerPrincipal
PrincipalSearcher srch = new PrincipalSearcher();
srch.QueryFilter = new ComputerPrincipal(ctx);;

// do the search
PrincipalSearchResult<Principal> results = srch.FindAll();

// enumerate over results
foreach(ComputerPrincipal cp in results)
{
   string computerName = cp.Name;
}

Check out the Managing Directory Security Principals in the .NET Framework 3.5 on MSDN Magazine for more information on the new S.DS.AM namespace and what it offers.

If you can't move up to .NET 3.5 - you just need to keep in mind that the .Properties["name"] that you get from the search result is a collection of values - so in order to grab the actual pc name, use this:

pcName = oneMachine.Properties["name"][0].ToString();

You need to index the .Properties["name"] collection with a [0] to get the first entry (typically also the only entry - hardly any computer has more than one name).

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜