Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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;
}
like image 500
Dario D. Goddin Avatar asked Sep 12 '25 15:09

Dario D. Goddin


2 Answers

There's no reason to call InvokeSet, also. This is the correct way to do this:

foreach (SearchResult AdObj in Searcher.FindAll()) { 
  DirectoryEntry user = AdObj.GetDirectoryEntry(); 
  user.Properties["HomeDirectory"].Value = @"\\winfileserver\" + Convert.ToString(AdObj.Properties["sAMAccountName"][0]); 
  user.Properties["HomeDrive"].Value = "H"; 
  user.CommitChanges(); 
} 
like image 191
Brian Desmond Avatar answered Sep 14 '25 03:09

Brian Desmond


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();
}
like image 37
Joshua Avatar answered Sep 14 '25 05:09

Joshua