.Net code to set an Active Directory attribute to

2019-06-23 09:12发布

问题:

In the Active Direcotry mmc snap-in you cant see attributes that are "Not Set". When you use ADSIEDIT.MSC tool, if attribute values are null you do see them as "Not Set".

How can I set an attribute to "Not Set" in .Net code?

Here is the answer in Powershell but I need to do it with some .Net code (VB.Net/C#). http://social.technet.microsoft.com/Forums/en-US/winserverpowershell/thread/d6d0bfa1-73da-41ea-a7f5-f622de9f7d1b/

ps msExchHideAddressLists is the culprit attribute, when its True or False in this domain it prevents user information replicating from AD to Sharepoint.

回答1:

In the MSDN you can found :

Within commonly used directories that support LDAP, an attribute without a value does not exist. When the attribute value is set to a non-null value by a change, replace, or append operation, the attribute is created if it does not already exist. Similarly, if an attribute is modified to have no value (or values), the entire attribute is removed. At times you may want to set an attribute to null. While this concept does not exist in directories that support LDAP, you can accomplish this by removing the attribute entirely and specifying that the property is to be cleared.

Here is an example using System.DirectoryServices :

/* Connection to Active Directory
 */
DirectoryEntry deBase = new DirectoryEntry("LDAP://192.168.183.220:389/dc=societe,dc=local", "administrateur", "adm");

/* Directory Search
 */
DirectorySearcher dsLookForOUs = new DirectorySearcher(deBase);
dsLookForOUs.Filter = "(objectCategory=organizationalUnit)";
dsLookForOUs.SearchScope = SearchScope.Subtree;
dsLookForOUs.PropertiesToLoad.Add("cn");
dsLookForOUs.PropertiesToLoad.Add("ou");
dsLookForOUs.PropertiesToLoad.Add("telephoneNumber");

SearchResultCollection srcOUs = dsLookForOUs.FindAll();

foreach (SearchResult srOU in srcOUs)
{
  Console.WriteLine("{0}", srOU.Path);
  DirectoryEntry de = srOU.GetDirectoryEntry();
  if (de.Properties["TelephoneNumber"].Value!= null)
  {
    // Both solutions are working. Don't forget to commit

    //de.Properties["TelephoneNumber"].Clear();
    de.Properties["TelephoneNumber"].Value=null;
    de.CommitChanges();
  }
}