简体   繁体   中英

Fetching list of locked AD users throws error. Am I using incorrect search terms?

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);
                        }
                    }
                }
            }

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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM