'How to get group managed service accounts using UserPrincipal.FindByIdentity?

I have one gMSA user created. I am trying to get the user sid-

ContextType contextType= ContextType.Domain;

PrincipalContext domainContext = new PrincipalContext(contextType, domain);

using (var foundUser = UserPrincipal.FindByIdentity(domainContext, IdentityType.SamAccountName, userName))
            {
                if (foundUser != null)
                {
                    identity = foundUser.Sid.Value;
                    result = true;
                }
            }

The gMSA user is under a domain such as contoso.ab.cd.com



Solution 1:[1]

I ran in to this issue as well. In my environment, I noticed that the gMSA accounts are not in the UserPrincipal at all. Rather, they are in ComputerPrincipal. Try the following:

ContextType contextType= ContextType.Domain;

PrincipalContext domainContext = new PrincipalContext(contextType, domain);

using (var foundUser = ComputerPrincipal.FindByIdentity(domainContext, IdentityType.SamAccountName, userName))
            {
                if (foundUser != null)
                {
                    identity = foundUser.Sid.Value;
                    result = true;
                }
            }

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 ThomasT