I need to list all users from the specific local group in the following format: "Domain\UserName". I can extract collection of GroupPrincipal objects for the group, but I don't know how to get users in required format. GroupPrincipal doesn't have property Domain.
The following code outputs users without domain (e.g. "UserName").
using (var context = new PrincipalContext(ContextType.Machine, null))
{
using (var group = GroupPrincipal.FindByIdentity(context, IdentityType.SamAccountName, @"My Local Group"))
{
if (group != null)
{
foreach (var p in group.GetMembers(false))
{
Console.WriteLine(p.SamAccountName);
}
}
}
}
Is it possible to get domain netbios name from the principal object? And if so, how to get it?
You can get the domain details from the principal's Context. e.g.:
foreach (var p in group.GetMembers(false))
{
Console.Write(p.SamAccountName);
if (p.ContextType == ContextType.Domain)
{
Console.Write(" ({0})", p.Context.Name);
}
Console.WriteLine();
}
If you just want to output account names in the "domain\user" format from a machine on the domain, you can translate the principal's SecurityIdentifier to an NTAccount. e.g.:
foreach (var p in group.GetMembers(false))
{
Console.WriteLine(p.Sid.Translate(typeof(NTAccount)).ToString());
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With