Search code examples
c#active-directorydirectoryentry

c# DirectoryEntry InvokeSet HomeDirectory and HomeDrive, errors


I'm trying to modify the Profiles / Home Directory / Home Drive setting for each AD user in a specified OU,

I have below some very basic code that should achieve this feat but is instead throwing the following exception:

The requested operation did not satisfy one or more constraints associated with the class of the object.

Has anyone had this problem and if so, have a way of fixing it?

Thank you.

DirectoryEntry Entry = new DirectoryEntry("LDAP://OU=Company,DC=corp,DC=Placeholder,DC=com", null, null, AuthenticationTypes.Secure);

DirectorySearcher Searcher = new DirectorySearcher(Entry);
Searcher.SearchScope = SearchScope.Subtree;

Searcher.PropertiesToLoad.Add("sAMAccountName");
Searcher.Filter = "(&(objectClass=user)(objectCategory=person))";

foreach (SearchResult AdObj in Searcher.FindAll())
{
   Entry.InvokeSet("HomeDirectory", @"\\winfileserver\" + Convert.ToString(AdObj.Properties["sAMAccountName"][0]));
   Entry.InvokeSet("HomeDrive", "H");
   Entry.CommitChanges();
}
catch (Exception ex)
{
   richTextBox1.Text += ex.Message;
}

Solution

  • It looks like you're using Entry which is pointing to your directory root, not the object you found and that's why the call is failing.

    I believe you can change your foreach loop to:

    foreach (SearchResult AdObj in Searcher.FindAll()) {
      DirectoryEntry user = AdObj.GetDirectoryEntry();
      user.InvokeSet("HomeDirectory", @"\\winfileserver\" + Convert.ToString(AdObj.Properties["sAMAccountName"][0]));
      user.InvokeSet("HomeDrive", "H");
      user.CommitChanges();
    }