PowerShell: Find AD User by Full Name
Most of the time when searching for a user in AD you are going to be finding them by their username, however what happens if you don’t have their username and you still want to find them?
This script allows you to search for AD users based on their Full Name even when you don’t know their username.
Overview – How does it work?
Before we get into the actual coding, lets determine what we want to achieve. Below are the high-level steps the script needs to complete:
- Collect a list of user’s full names from a text file (i.e. the list of user’s we want to find)
- For each one of these full names, find the user in Active Directory
- Once the user is found, collect the desired information and store it in an array
- Output all of this data for each user to a spreadsheet (i.e. CSV file)
Pre-Requirements
Before being able to execute this script a few things need to be pointed out:
- You need the Active Directory PowerShell module installed on the machine you are running. To do this, follow the instructions in this MSDN Blog article
- You need to import the Active Directory PowerShell module (if you haven’t done so already). This is completed in line 1 of the script
- The PowerShell Active Directory module uses Active Directory Web Services (ADWS) to communicate with the domain and for this reason you need this installed in your domain to be able to use this script. The good news is that all Windows 2008 R2 and 2012 domain controllers have this installed automatically. Alternatively you can install this manually for Windows 2003 \ 2008 (i.e. not R2) servers. You can download the ADWS package from here
- Other than this, you are ready to go!
The Script: Find AD User by Full Name
Here is the script in its entirety. After this we will go through the main points of the script:
Detailed Explanation
Below is a detailed explanation of all of the steps outlined above:
Step 1: Getting Content from a File
To get the content from a file just simply use the Get-Content
cmdlet and store it in a variable. In this case we are storing it in $List
:
$List = Get-Content ".\List.txt"
Step 2: Find AD User by Full Name
To this we need to use the Get-ADUser
cmdlet and use the -Filter
attribute to filter on displayName which is the AD attribute which stores the user’s full name by default.
You can filter on any AD attribute and you can also filter on AND and OR statements. In my situation, I needed to eliminate all admin account (i.e. accounts that start with “admin-“) hence I added a second filter to exclude all usernames (SamAccountName) that start with “admin-“. Finally I also wanted to get only enabled account:
$User = Get-ADUser -Filter{displayName -like $Item -and SamAccountName -notlike "admin-*" -and Enabled -eq $True} -Properties SamAccountName, GivenName, Surname, telephoneNumber, mail
To speed up the results, I limited the number of attributes the cmdlet returns for each user by specifying the -Properties
attribute and selecting the only the attributes I am interested in. You can edit these as you like, or you can just set *
to collect all of them.
Step 3: Collect AD User Information
Now that we have found the user we want to collect some information from the Active Directory object and then we will save this in an array so we can export it later.
My solution to this is to use a hash-table or a PS Object and then store each PS Object within an array. Each PS Object contains the information we require for full name within the text file. Doing it this way is easier than playing with two dimensional arrays (or at least it is for me).
The information we require for each user in this example is:
- Full Name (we already have this info from the text file)
- User Name
- Telephone Number
- Email Address
The code below shows you how to create a PS Object and then store all of the properties we require from the found AD object into a PS Object. A PS Object is jut an object with properties – essentially exactly like the AD object that is retrieved. We are just simply creating our own set of properties and then populating those properties with values from the AD object and its properties.
$hItemDetails = New-Object -TypeName psobject -Property @{
FullName = $Item
UserName = $User.SamAccountName
Email = $User.mail
Tel = $User.telephoneNumber
}
The next step is to store the PS Object into an array where each array element is a separate AD object. To do this you simply do the following:
$aResults += $hItemDetails
Step 4: Output results to CSV file
To find all of the users listed in the text file, we simply a ForEach loop as per line 6 in the script. All this does is execute steps 2 and 3 for each line item in the text file and store each result found in a new element within the $aResults array.
Once the ForEach loop has finished processing we now need to output the data. To do this we can use the Export-CSV
cmdlet, as per the code below:
$aResults | Export-CSV ".\Results.csv"
And that is pretty much it…. Enjoy!
Thanks man, just what I was trying to do.
Hello,
Very clear and concise explanation. Are you able to explain a bit more on
$Item = $Item.Trim()
art please? What it does and is it necessary?
Regards,
GSG
Hi GSG,
The Trim method is used to remove any trailing and leading spaces in a string.
So for example, lets say $Item = ” hello ” (with 2 spaces either side of the string hello). If we did $Item = $Item.Trim() it would mean that $Item would now be “hello” and not ” hello “.
Hope this helps.
Luca
Thanks!
Can you please post a screen shot of the format of the text file? I’m unsure if you have a column for first name and last name or have you combined them both into one column?
Thanks
M
Hi Marion,
The format of the text file is simply the full name of the person on a single line, with a new person on a new line.
Here is an example to help you:
John Smith
Peter Doe
Jane Smith
Hope this helps
Luca
Hi this works for me
But it’s not picking up full names with apostrophe like Harry O’Brian for example
How would I resolve this?
Hi J,
The way to solve this would be to add quotes around the match case
-like
, so$Item
would be"$Item"
. Like below:$User = Get-ADUser -Filter{displayName -like "$Item" -and SamAccountName -notlike "admin-*" -and Enabled -eq $True} -Properties SamAccountName, GivenName, Surname, telephoneNumber, mail
Try that and see how it goes.
Thanks
Luca
Hi Luca
It still did not work. Below is my script
Import-Module ActiveDirectory
$aResults = @()
$List = Get-Content “.\List.txt”
ForEach($Item in $List){
$Item = $Item.Trim()
$User = Get-ADUser -Filter{displayName -like “$Item” -and SamAccountName -notlike “admin-*” -and Enabled -eq $True} -Properties SamAccountName, GivenName, Surname, telephoneNumber, mail
$hItemDetails = New-Object -TypeName psobject -Property @{
FullName = "$Item"
UserName = $User.SamAccountName
Email = $User.mail
Tel = $User.telephoneNumber
}
#Add data to array
$aResults += $hItemDetails
}
$aResults | Export-CSV “.\Results.csv”
Hello!
I have a question…
I have to use powershell to change manager in AD.
It goes like this:
1 worker is going to have “Manager 1” as manager.
1 other worker is going to have “manager 2” as manager.
How do i write it?
ALso want to specify search for the workplace (1 Worker and manager 1 is in “health care”
worker 2 and manager 2 is in “technical”
Hi Nordstrom,
Unfortunately I don’t have an already written script that can be of help to you. If you are unsure of how to achieve what you require, then try a google search as there are some really good articles around Active Directory management and searching using PowerShell.
If you are still unsure on how to achieve it, I do some consulting work, so if you are interested in me developing the script for you, then click on the Hire link in the main menu above and we can discuss your requirements further.
Hope this helps
Luca
Hi,
Hopefully you still see comments on this post even though it was made 3 years ago.
The script works great, but I would like some help in what to do when a DisplayName exists more than once. I use this to pull SamAccountName and Emailaddress to help clients import information into external systems not managed by myself and my team. I work in a very large organisation so duplicate names happen. When I ran this script I ended up getting System.Object[] results on those duplicate display names. Any way to sort this out?
Hi Fredric,
You can try this changes:
1. Rename $User to $Users
2. Put this “$hItemDetails = New-Object….” into foreach loop like:
ForEach ($User in $Users)
{
$hItemDetails = New-Object….
$aResults += $hItemDetails
}
As an alternative way to do this, I can recommend my free Active Directory reporting tool – AD FastReporter Free.
You can get various information about users, computers, etc., and export it to csv, xlsx and html files.
@Fredric – I use this script a lot and have the same question! surprised it has not been answered yet!
Hello,
Thank you for the information. Its the best script I’ve found so far. I’m able to run the script but for some names I’m not able to receive an output, and for those I do I’m not receiving a phone number. I’m really new to powershell, do I need to save the file with a headline or something? and If I just need to filter the username can I take the rest out from the script or do I need to make a new one?
Thank you so much for your help!
@Luca Sturlese:
Could you help me to output this powershell script to CSV or TXT?
The script it ran and displayed results in console, but I can’t make the Export CSV cmdlet to work. I have tried so many cmdlet, But…Thank you in advance.
Get-Content -c:\0-AD\UserStatus7.csv
Out-File – c:\0-AD\UserStatus7.csv -notype -append
$data|export-csv c:\0-AD\UserStatus7.csv -notype
write-output c:\0-AD\UserStatus7.csv -notype -append
Import-Module activedirectory
$aResults = @()
$List = Get-Content “C:\0-AD\username-786.csv”
$Results =Import-Csv c:\0-AD\username-786.csv
$users=Import-csv C:\0-AD\username-786.csv
foreach($user in $users){
Try{
$ErrorActionPreference=’Stop’
get-aduser $user.samaccountname |select Name,samaccountname, @{n =”AccountStatus”;E={if(($_.Enabled -eq ‘TRUE’)) {‘Enabled’} Else {‘Disabled’}}}
}
catch{
“Not Found $($user.samaccountname)”
}
#Add data to array
$aResults += $hItemDetails
}
$aResults | Export-CSV “C:\0-AD\UserStatus8.csv”
Run results:
Not Found RPM9006
Not Found RSD9005
Not Found SAC9068
Not Found BERNARD
Not Found SPJ9002
Not Found STS9113
Not Found TOI9001
Export-Csv : Cannot bind argument to parameter ‘InputObject’ because it is null.
At C:\0-AD\cwid-exist-8.ps1:26 char:13
+ $aResults | Export-CSV “C:\0-AD\UserStatus8.csv”
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidData: (:) [Export-Csv], ParameterBindingValidationException
+ FullyQualifiedErrorId : ParameterArgumentValidationErrorNullNotAllowed,Microsoft.PowerShell.Commands.ExportCsvCommand
Thanks for the script however if an account is disabled it doesn’t detect it at all so it looks like the account doesn’t exist
Does anyone else run the script then notice that the output does not show up in the order it is listed in the script?
I modified the various AD attributes I want to grab so I get the info I need, but regardless of the order I put the commands in the script, they always come out the same way (whether displayed on screen or exported to a file).
This is how I have the script configured:
Import-Module ActiveDirectory
$aResults = @()
$List = Get-Content “c:\temp\names.txt”
ForEach($Item in $List){
$User = Get-ADUser -Filter{displayName -like $Item} -Properties employeenumber, sn, GivenName, samaccountname, mail
$hItemDetails = New-Object -TypeName psobject -Property @{
EmployeeNumber = $User.employeenumber
LastName = $User.sn
FirstName = $User.givenname
UserName = $User.SamAccountName
Email = $User.mail}
Add data to array
$aResults += $hItemDetails
}
$aResults | Export-csv -Path c:\Temp\EmpUpdate.csv -notypeinformation
You can see in the script that I have the data ordered as employeenumber, lastname, firstname, samaccountname, email.
However, the output always comes out samaccountname, email, employeenumber, firstname, lastname.
Hi Joe,
This is a result of the
export-csv
function. For some reason it does that, it puts in in a different order. It really annoyed me too. I usually just open in in Excel and then re-order from there if need to.Luca