I am having issues with adding/removing a domain user into the Administrator group o the local machine. I am piecing this with code samples from the web, but I am realising that I am not doing it right and am out of my depth with this one. Please help!
I have a function that gets the user from the domain (this part works well):
internal static async Task<DirectoryEntry> GetUserAsync(Logger log, string upn)
{
try
{
await log.LogTraceAsync(string.Format("Retrieving user {0} from AD.", upn));
DirectoryEntry user = null;
using (var context = new PrincipalContext(ContextType.Domain))
{
using (var searcher = new PrincipalSearcher(new UserPrincipal(context)))
{
UserPrincipal u = new UserPrincipal(context);
u.UserPrincipalName = upn;
searcher.QueryFilter = u;
var result = searcher.FindOne();
if (result != null)
{
DirectoryEntry de = result.GetUnderlyingObject() as DirectoryEntry;
if (de != null) user = de;
}
}
}
return user;
}
catch (PrincipalServerDownException) { return null; }
catch (Exception ex)
{
await log.LogErrorAsync("An error ocurred while getting user from AD.", ex);
return null;
}
}
Ths one works well. I can find the user that I am looking for.
Than I would want to add/remove this user in/from the local Administrator group of the local machine (which is also domain joined).
Here is the code for that (add only, remove is very similar).
internal static async Task<bool> AddUserInLocaAdministratorGroupAsync(Logger log, DirectoryEntry user)
{
try
{
await log.LogTraceAsync(string.Format("Adding user {0} is in local machine {1} administartor group.", user.Name, Environment.MachineName));
string uname = user.Properties["samaccountname"][0].ToString().ToLower();
DirectoryEntry localMachine = new DirectoryEntry("WinNT://" + Environment.MachineName);
DirectoryEntry admGroup = localMachine.Children.Find("administrators", "group");
await log.LogTraceAsync(string.Format("Adding user {0}", user.Path.ToString()));
admGroup.Invoke("Add", new object[] { user.Path.ToString() });
return true;
}
catch (Exception ex)
{
await log.LogErrorAsync("An error acurred while adding user to local admin group.", ex);
return false;
}
}
The user.Path.ToString()
is like this LDAP://CN=Lastname, Firstname,OU=NoPolicy,OU=_Users,DC=studio, DC=someorg,DC=net
.
And this is the error that I get: System.Runtime.InteropServices.COMException (0x80005000): An invalid directory pathname was passed
.
Clearly I am doing something wrong.
Can you help fixing this, or proposing a better way to make this call?
Thanks