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");
SearchResultCollection 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.AccountManagementnamespace which makes a lot of these takes much easier.To find all computers and enumerate them, you’d do something like this:
Check out the Managing Directory Security Principals in the .NET Framework 3.5 on MSDN Magazine for more information on the new
S.DS.AMnamespace 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: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).