PowerShell one-liner: Find AD user based on property

While working in Active Directory based environment you are often dealing with AD user accounts and probably using often Get-ADUser command. In this article I want to present several simple examples how to use it.

Normally when we want to display user details we use -Identity :

Get-ADUser -Identity 'S-1-5-21-329123456-141345322-1417344333-41244447' | Select-Object name
Get-ADuser -Identity Pawel.Janowicz

To list names of all available user properties we can use Get-Member command:

(Get-ADuser -Identity Pawel.Janowicz -Properties * | Get-Member -MemberType Property).name

The case will be a little bit different when we have for example only user “mobile” and we want to find out quickly to which user it belongs.

Below you can find several example how to search a user in Active Directory based on other properties and using filter option:

# Use filter to find user based on SID
Get-ADUser -Filter { SID -eq 'S-1-5-21-329123456-141345322-1417344333-41244447' }

# Searching user based on mobile phone attribute
Get-ADUser -Filter { mobile -eq '+48555444333' }

# Find all accounts where givename is like “Pawel” 
Get-ADuser -Filter { givenname -like 'Pawel' } 
Get-ADuser -Filter { givenname -like 'Pawel' } | Select-Object name | Sort-Object name
Get-ADuser -Filter { givenname -like 'Pawel' } -Properties name,emailaddress,enabled | Select-Object name,emailaddress,enabled | Sort-Object name

# Find all users where given name starts with "P" and surname starts with "J"
Get-ADUser -Filter { givenname -like 'P*' -and surname -like 'J*' } | Select-Object name

Find all enabled accounts where givename is like “Pawel” and skip admin accounts if you have one:

$Pawels = Get-ADuser -Filter {givenname -like 'Pawel'} -Properties name,emailaddress,enabled | Where-Object {($_.enabled -eq "True") -and ($_.name -notlike "admin.*")} | Select-Object name,emailaddress,enabled | Sort-Object name | Out-GridView

If you are working in large scale environment sometimes it’s better to use SearchBase:

Get-ADUser -Filter {givenname -like 'Pawel'} -SearchBase "OU=PolandUsers,OU=UserAccounts,DC=PowerShellBros,DC=com"

Additionally I want to show you how to use ADSISearcher to make searching even quicker:

# Find all users with given name Pawel
([adsisearcher]"givenname=pawel").FindAll()

# Find users based on other attibutes
([adsisearcher]"(&(objectClass=User)(surname=janowicz))").FindAll()
([adsisearcher]"(&(objectClass=User)(city=Warsaw))").FindAll()
([adsisearcher]"(&(objectClass=User)(mobile=+48555444333))").FindOne()

# Find user based on name and display all properties
([adsisearcher]"(&(objectClass=person)(objectClass=user)(name=pawel.janowicz))").FindAll().properties

I hope that this has been informative and you’ve learned something new 🙂

Leave a Reply

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.