2

first of all, I'm fairly new to programming in general. I'm working on a simple monitoring tool.

I'm trying to get a list of all locked AD users. Thanks to stackoverflow I found someone who once had the same question, unfortunately his answer does nog work for me. And I can't really figure out why, but I think I am nog searching correctly.. Below code throws the following error.

Error

(Roughly translated: Value cannot be null. Parameter name: IdentityValue)

Tried searching an alternative for "Domain Users" in below code but no luck.

GroupPrincipal grp = GroupPrincipal.FindByIdentity(context, 
IdentityType.SamAccountName, "Domain Users");

Here is the code I'm using.

var lockedUsers = new List<UserPrincipal>();
            using (var context = new PrincipalContext(ContextType.Domain, 
"domainname"))
            {
                GroupPrincipal grp = 
GroupPrincipal.FindByIdentity(context, IdentityType.SamAccountName, 
"Domain Users");
                foreach (var userPrincipal in grp.GetMembers(false))
                {
                    var user = UserPrincipal.FindByIdentity(context, 
IdentityType.SamAccountName, userPrincipal.UserPrincipalName);
                    if (user != null)
                    {
                        if (user.IsAccountLockedOut())
                        {
                            lockedUsers.Add(user);
                        }
                    }
                }
            }

1 Answers1

1

I was able to replicate the issue, and the error is in the following line: var user = UserPrincipal.FindByIdentity(context, IdentityType.SamAccountName, userPrincipal.UserPrincipalName); You are trying to find an identity by the SamAccountName because the second argument to the FindIdentity-method is the identity type to filter by but you are supplying a UserPrincipalName instead of a SamAccountName. The following options would solve your issue:

var user = UserPrincipal.FindByIdentity(context, IdentityType.UserPrincipalName, userPrincipal.UserPrincipalName);

or:

var user = UserPrincipal.FindByIdentity(context, IdentityType.SamAccountName, userPrincipal.SamAccountName);

JelleKerkstra
  • 502
  • 2
  • 4
  • 19
  • You're right, it works now. Thank you for taking the time to troubleshoot this one. – Danny van Haaren May 02 '19 at 09:01
  • Just out of curiosity, what do you think is the impact performance wise? Since it basically goes by every user in said domain I think.. – Danny van Haaren May 02 '19 at 09:04
  • I think there is no noticeable performance difference between the 2 methods in my answer. Maybe your code could be improved on overall but I would have to dive in a bit – JelleKerkstra May 02 '19 at 11:27