Filtering a list of usernames based on OU or Container

Recently I was given a list of usernames and asked to find all the user who were in a specific OU in Active Directory.  This sounds complicated but is actually quite easy to do with powershell in 3 easy steps:

Step 1: I created a txt file with the list of usernames called userList.txt

Step 2: I then created a simple powershell script to read in username and return the users DN

Step 3: If the users DN contained the OU I was looking for I appended that users info to a new file called matchedUsers.txt

$userList = Get-Content "c:\fileLocation\userList.txt" #open the file and read the data in an array
write-host $userList.count total lines read from file #output total lines read
foreach ($user in $userList)#do this for each user read from file
$userDN = dsquery user -samID $user #does a dsquery using the read in samID and returns the userDN

if ($userDN.Contains("Name_Of_OU_or_Container")) #if the userDN contains the target OU or container
$lineOutToFile = $user + " " + $userDN #concatenate the user name and userDN
$lineOutToFile | Out-File "c:\fileLocation\matchedUsers.txt" -append #output the user+userDN to file

The result is you get a file output with all username and userDNs that are located in the container or OU you wanted to search for.

About Dane

Currently working on scripting and IT automation. My skill set includes IDM, Active Directory and Exchange Administration, powershell scripting and more...
This entry was posted in Active Directory, Powershell and tagged , , . Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *


You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>