Last active
June 21, 2018 22:43
-
-
Save brunomartinspro/6358331cf7ce2c9deab8a503f257c20c to your computer and use it in GitHub Desktop.
Get Active Active Directory Users based on List of usernames
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.Linq; | |
using System.Collections.Generic; | |
using System.DirectoryServices; | |
using BrunoMartinsPro.Data.Interfaces.Utils.ActiveDirectory; | |
namespace BrunoMartinsPro.Utils.ActiveDirectory | |
{ | |
public class ADUtils : IADUtils | |
{ | |
private readonly DirectoryEntry _directoryEntry; | |
public ActiveDirectoryUtils(DirectoryEntry directoryEntry) | |
{ | |
_directoryEntry = directoryEntry; | |
} | |
/// <summary> | |
/// Get all ActiveDirectory Users | |
/// </summary> | |
public List<string> GetActiveDirectoryUsers(List<string> existingUsernameList) | |
{ | |
List<string> users = new List<string>(); | |
var usernameQuery = $"(|{String.Join(string.Empty, existingUsernameList.Select(x => $"(SAMAccountName=*{x}*)").ToList())})"; | |
//Create Directory Search | |
DirectorySearcher search = new DirectorySearcher(_directoryEntry); | |
//Search for a user that is member of anything and is active | |
string query = $"(&(objectCategory=person)(objectClass=user)(!userAccountControl:1.2.840.113556.1.4.803:=2){usernameQuery})"; | |
//Apply search query | |
search.Filter = query; | |
//Add property SAM ACCOUNT NAME | |
search.PropertiesToLoad.Add("samaccountname"); | |
//Execute search | |
SearchResultCollection mySearchResultColl = search.FindAll(); | |
//Add users | |
foreach (SearchResult result in mySearchResultColl) | |
{ | |
//Get user | |
var userToAdd = result.Properties["samaccountname"][0].ToString(); | |
//Add user | |
users.Add(userToAdd); | |
} | |
//return users | |
return users; | |
} | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.Collections.Generic; | |
using System.Linq; | |
using System.Text; | |
using System.Threading.Tasks; | |
namespace BrunoMartinsPro.Data.Interfaces.Utils.ActiveDirectory | |
{ | |
public interface IADUtils | |
{ | |
List<string> GetActiveDirectoryUsers(List<string> existingUsernameList); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment