Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get Domain from GroupPrincipal?

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?

like image 745
altso Avatar asked Jul 20 '11 09:07

altso


1 Answers

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());
}
like image 196
Nicole Calinoiu Avatar answered Nov 22 '22 14:11

Nicole Calinoiu