Get-ADUser позволяет получить информацию о пользователе Active Directory, его атрибутах и выполнять поиск среди пользователей домена. Это один из наиболее популярных командлетов PowerShell для получения информации из AD. С помощью командлета Get-ADUser можно получить значение любого атрибута учетной записи пользователя AD, вывести список пользователей в домене с нужными атрибутами, экспортировать отчеты по пользователям в CSV файлы, и использовать различные критерии для выборки доменных пользователей.
Содержание:
- Командлет Get-ADUser в модуле PowerShell Active Directory
- Get-ADUser: поиск пользователя AD и вывод атрибутов
- Получение пользователей из нескольких OU с помощью Get-ADUser
- Получить Email адреса пользователей из AD
- Get-ADUser: экспорт списка пользователей в текстовый или CSV/Excel файл
- Get-ADUser –Filter: Поиск и фильтрация списка пользователей AD
- Часто используемые примеры команд с Get-ADUser для получения информации о пользователях AD
Командлет Get-ADUser в модуле PowerShell Active Directory
Комадлет Get-ADUser входит в специальный модуль для работы с Active Directory — Active Directory Module for Windows PowerShell. Командлеты модуля RSAT-AD-PowerShell позволяют выполнять различные операции с объектами каталога AD.
Примечание. Ранее для получения информации об атрибутах учетных записей пользователей AD приходилось использовать различные инструменты: консоль ADUC (в том числе сохраненные запросы AD), vbs скрипты, утилиту dsquery и т.п. Все эти инструменты может с лёгкостью заменить командлет Get-ADUser.
В этом примере мы покажем, как с помощью командлета PowerShell Get-ADUser получить информацию о времени последней смены пароля пользователя, когда истекает срок действия пароля и другие данные пользователей.
Для использования модуля RSAT-AD-PowerShell нужно запустить консоль PowerShell с правами администратора и импортировать модуль командой:
Import-Module activedirectory
В Windows Server 2012 и выше модуль
RSAT-AD-PowerShell
устанавливается по-умолчанию при развертывании на сервере роли Active Directory Domain Services (AD DS). Для установки модуля на рядовом Windows Server в домен, выполните команду:
Install-WindowsFeature -Name "RSAT-AD-PowerShell" –IncludeAllSubFeature
В десктопных версия Windows 10 и 11 для работы коммандера Get-AdUser нужно установить соответствующую версию RSAT. Установить RSAT можно через Settings -> Apps -> Optional Features -> Add a feature -> RSAT: Active Directory Domain Services and Lightweight Directory Services Tools.
Также вы можете установить модуль AD с помощью PowerShell:
Add-WindowsCapability –online –Name “Rsat.ActiveDirectory.DS-LDS.Tools~~~~0.0.1.0”
Если на компьютере не установлен модуль RSAT-AD-PowerShell, то при запуске команды Get-ADUser появится ошибка:
get-aduser : The term 'get-aduser' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again.
Проверьте, что модуль установлен, и если нужно, импортируйте его в свою сессию PowerShell:
Import-Module ActiveDirectory
Полный список всех аргументов командлета Get-ADUser можно получить так:
help Get-ADUser
Get-ADUser: поиск пользователя AD и вывод атрибутов
Для использования командлета Get-ADUser не обязательно использовать учетную запись с правами администратора домена. Любой авторизованный пользователь домена AD может выполнять команды PowerShell для получения значений большинства атрибутов объектов AD (кроме защищенных, см. пример с LAPS). Если нужно выполнить команду Get-ADUser из-под другой учетной записи, используйте параметр Credential.
Чтобы вывести список всех учетных записей домена, выполните команду:
Get-ADUser -filter *
Важно. Не рекомендуется выполнять эту команду в доменах AD с большим количеством аккаунтов, т.к. это вызовет большую нагрузку на контроллер домена, предоставляющего данные.
Чтобы вывести свойства только определенного пользователя, используется параметр –Identity. В качестве Identity можно указать имя пользователя, имя входа (SAMAccountName), DN (Distinguished Name), SID или GUID.
Следующие команды вернут одинаковый результат об одном и том же пользователе:
Get-ADUser –Identity a.ivanov
Get-ADUser –Identity "CN=Andrey A. Ivanov,OU=Users,OU=SPB,OU=RU,DC=winitpro,DC=loc"
Get-ADUser –Identity "Andrey A. Ivanov"
По-умолчанию командлет Get-ADUser возвращает только 10 основных атрибутов (из более чем 120 свойств учетных записей пользователей): DistinguishedName, SamAccountName, Name, SID, UserPrincipalName, ObjectClass, статус аккаунта (Enabled: True/False согласно атрибуту UserAccountControl), и т.д.
В выводе командлета отсутствует информация о времени последней смены пароля пользователя.
Чтобы выполнить запрос на конкретном контроллере домена используется параметр – Server:
Get-ADUSer –Server DC01.winitpro.loc –Identity tstuser
Если нужно получить данные из другого домена, нужно указать имя сервера и учетные данные для доступа к нему:
$cred = Get-Credential
Get-ADUSer tstuser -Server DC01.newdomain.ru -Credential $Cred
Чтобы вывести полную информации обо всех доступных атрибутах пользователя tuser, выполните команду:
Get-ADUser -identity tuser -Properties *
Командлет Get-ADUser с параметром Properties * вывел список всех атрибутов пользователя AD и их значения (включая пустые). Аналогичный список атрибутов пользователей доступен в графической консоли Active Directory Users and Computers (
dsa.msc
) на вкладке редактора атрибутов.
В командлете Get-ADUser можно список атрибутов пользователя, которые нужно выводить. Например, вы хотите вывести значения следующих атрибутов:
- PasswordExpired
- PasswordLastSet
- PasswordNeverExpires
- lastlogontimestamp
Выполните команду:
Get-ADUser tuser -properties PasswordExpired, PasswordLastSet, PasswordNeverExpires, lastlogontimestamp
Теперь в информации о пользователе есть данные о статусе аккаунта (Expired: True/False), дате смены пароля и времени последнего входа в домен (lastlogontimestamp). Представим информацию в более удобном табличном виде и уберем все лишние атрибуты с помощью Select-Object –Property или Format-Table:
Get-ADUser -filter * -properties PasswordExpired, PasswordLastSet, PasswordNeverExpires | ft Name, PasswordExpired, PasswordLastSet, PasswordNeverExpires
Получение пользователей из нескольких OU с помощью Get-ADUser
Чтобы вывести пользователей только из определенного контейнера домена (Organizational Unit), воспользуйтесь параметром SearchBase:
Get-ADUser -SearchBase ‘OU=Moscow,DC=winitpro,DC=loc’ -filter * -properties PasswordExpired, PasswordLastSet, PasswordNeverExpires | ft Name, PasswordExpired, PasswordLastSet, PasswordNeverExpires
Если вам нужно выбрать пользователей сразу из нескольких OU, используйте следующую конструкцию:
$OUs = "OU=Moscow,DC=winitpro,DC=local","OU=SPB,DC=winitpro,DC=loc"
$OUs | foreach {Get-ADUser -SearchBase $_ -Filter * |select Name, Enabled}
Получить Email адреса пользователей из AD
Email пользователя это один из атрибутов в Active Directory. Чтобы вывести список email адресов пользователей, вы должны добавить поле EmailAddress в атрибуты, отображаемые командлетом Get-ADUser.
Get-ADUser -filter * -properties EmailAddress -SearchBase ‘OU=MSK,DC=winitpro,DC=loc’| select-object Name, EmailAddress
Вывести список активных пользователей с почтовыми адресами:
Get-ADUser -Filter {(mail -ne "null") -and (Enabled -eq "true")} -Properties Surname,GivenName,mail | Select-Object Name,Surname,GivenName,mail | Format-Table
Список пользователей, у которые не задан email адрес:
Get-ADUser -Filter * -Properties EmailAddress | where -Property EmailAddress -eq $null
Следующий пример позволяет выгрузить адресную книгу email адресов компании в виде csv файла, который в дальнейшем можно импортировать в Outlook или Mozilla Thunderbird:
Get-ADUser -Filter {(mail -ne "null") -and (Enabled -eq "true")} -Properties Surname,GivenName,mail | Select-Object Name,Surname,GivenName,mail | Export-Csv -NoTypeInformation -Encoding utf8 -delimiter "," $env:tempmail_list.csv
Get-ADUser: экспорт списка пользователей в текстовый или CSV/Excel файл
Полученный список пользователей домена с атрибутами можно выгрузить в текстовый файл:
Get-ADUser -filter * -properties PasswordExpired, PasswordLastSet, PasswordNeverExpires | ft Name, PasswordExpired, PasswordLastSet, PasswordNeverExpires > C:tempusers.txt
Или вы можете выгрузить пользователей AD в файл CSV, который в дальнейшем будет удобно экспортировать в Excel.
Get-ADUser -filter * -properties PasswordExpired, PasswordLastSet, PasswordNeverExpires | select Name, PasswordExpired, PasswordLastSet, PasswordNeverExpires | Export-csv -path c:tempuser-password-expires-2019.csv -Append -Encoding UTF8
Get-ADUser –Filter: Поиск и фильтрация списка пользователей AD
С помощью параметра –Filter вы можете фильтровать список пользователей по одному или нескольким атрибутам. Это удобно использовать для поиска пользователей в AD, чьи атрибуты соответствуют указанным критериям. В качестве аргументов этого параметра можно указать значения определённых атрибутов пользователей Active Directory. При использовании параметра –Filter командлет Get-ADUser выведет только пользователей, которые соответствуют критериям фильтра.
Например, выведем список активных (Enabled) учётных записей пользователей, чье имя содержит «Dmitry». В примере ниже используется множественный фильтр, вы можете комбинировать условия с помощью стандартных логических операторов сравнения PowerShell. В данном примере атрибуты пользователей должны удовлетворять обоим условиям фильтра (-and):
Get-AdUser -Filter "(Name -like '*Dmitry*') -and (Enabled -eq 'True')" -Properties * |select name,enabled
Можно использовать все логические операторы PowerShell для выбора значений атрибутов пользователей (
-eq
,
-ne
,
-gt
,
-ge
,
-lt
,
-le
,
-like
,
-notlike
,
-and
,
-or
, и т.д.)
Дополнительно с помощью Sort-Object вы можете отсортировать полученный список пользователей по определенному атрибуту. Кроме того, для выборки пользователей можно использовать командлет Where-Object. Здесь также можно использовать сразу несколько критериев фильтрации.
Get-ADUser -filter * -properties PasswordExpired, PasswordLastSet, PasswordNeverExpires -SearchBase ‘OU=Moscow,DC=winitpro,DC=loc’| where {$_.name –like “*Dmitry*” -and $_.Enabled -eq $true} | sort-object PasswordLastSet | select-object Name, PasswordExpired, PasswordLastSet, PasswordNeverExpires
Таким образом, можно получить список пользователей с любыми необходимыми атрибутами Active Directory.
Для поиска пользователей сразу по нескольким атрибутам (legacyExchangeDN, proxyAddresses, SAMAccountName, Surname, DisplayName, SamAccountName, physicalDeliveryOfficeName, RDN и msExchMailNickname) можно использовать функцию Ambiguous Name Resolution (
ANR
):
Get-ADUser -Filter {anr -eq ‘Oleg’} | select Name
Совет. При выборке пользователей с помощью Get-ADUser с точки зрения скорости и производительности предпочтительнее задавать критерии с помощью атрибута Filter, а не командлет Where-Object. В этом случае фильтрации результатов выборки будет выполнятся на контроллере домена, и к вам на компьютер будет возвращаться меньший набор данных.
Вы можете использовать LDAP фильтр в запросах Get-ADUser. LDAP фильтр указывается с помощью атрибута –LdapFilter.
Get-ADUser -LDAPFilter '(&(department=it)(title=devops))'
Часто используемые примеры команд с Get-ADUser для получения информации о пользователях AD
Далее приведем еще несколько полезных вариантов PowerShell запросов о пользователях Active Directory с помощью различных фильтров. Вы можете комбинировать их для получения необходимого списка пользователей домена:
Вывод пользователей AD, имя которых начинается с Roman:
Get-ADUser -filter {name -like "Roman*"}
Чтобы подсчитать общее количество всех аккаунтов в Active Directory:
Get-ADUser -Filter {SamAccountName -like "*"} | Measure-Object
Список всех активных (не заблокированных) учетных записей в AD:
Get-ADUser -Filter {Enabled -eq "True"} | Select-Object SamAccountName,Name,Surname,GivenName | Format-Table
Вывести дату создания учётной записи пользователя в домене:
get-aduser -Filter * -Properties Name, WhenCreated | Select name, whenCreated
Вывести всех пользователей, которые были созданы за последние 24 часа (пример отсюда):
$lastday = ((Get-Date).AddDays(-1))
Get-ADUser -filter {(whencreated -ge $lastday)}
Список учетных записей с истекшим сроком действия пароля (срок действия пароля настраивается в доменной политике паролей):
Get-ADUser -filter {Enabled -eq $True} -properties name,passwordExpired | where {$_.PasswordExpired}|select name,passwordexpired
Задача: для списка учетных записей, которые хранятся в текстовом файле (по одной учетной записи в строке), нужно получить телефон пользователя из AD и выгрузить информацию в текстовый csv файл (для дальнейшего формирования отчета в Exсel).
Import-Csv c:psusernsme_list.csv | ForEach {
Get-ADUser -identity $_.user -Properties Name, telephoneNumber |
Select Name, telephoneNumber |
Export-CSV c:psexport_ad_list.csv -Append -Encoding UTF8
}
Пользователи, которые не меняли свой пароль в течении последних 90 дней:
$90_Days = (Get-Date).adddays(-90)
Get-ADUser -filter {(passwordlastset -le $90_days)}
Найти неактивные учетные записи пользователей (не входили в домен более 180 дней). Для получения информации об истории входов пользователей в домен используется атрибут lastLogonTimpestamp:
$LastLogonDate= (Get-Date).AddDays(-180)
Get-ADUser -Properties LastLogonTimeStamp -Filter {LastLogonTimeStamp -lt $LastLogonDate } | ?{$_.Enabled –eq $True} | Sort LastLogonTimeStamp| FT Name, @{N='lastlogontimestamp'; E={[DateTime]::FromFileTime($_.lastlogontimestamp)}} -AutoSize
Чтобы получить фотографию пользователя из Active Directory и сохранить ее в jpg файл:
$user = Get-ADUser winadmin -Properties thumbnailPhoto
$user.thumbnailPhoto | Set-Content winadmin.jpg -Encoding byte
Список групп, в которых состоит учетная запись пользователя:
Get-AdUser winadmin -Properties memberof | Select memberof -expandproperty memberof
Вывести список пользователей из OU, которые состоят в определенной группе безопасности:
Get-ADUser -SearchBase ‘OU=Moscow,DC=winitpro,DC=loc’ -Filter * -properties memberof | Where-Object {($_.memberof -like “*WKS admins*”)}
Вывести всех пользователей из OU, кроме членов определенной группы:
$Users = Get-ADUser -filter * -SearchBase ‘OU=Moscow,DC=winitpro,DC=loc’ -properties memberOf
ForEach ($User In $Users)
{
$Groups = -join @($User.memberOf)
If ($Groups -notlike '*Domain Admins*')
{
$User.Name
}
}
Экспортировать пользователей из AD со указанием имени OU в графическую таблицу Out-GridView:
get-aduser -filter * -Properties cn,canonicalname | select name,userprincipalname,@{Name="OU";expression={$_.Canonicalname.substring(0,$_.canonicalname.length-$_.cn.length)}}| Out-GridView
Проверить, что пользователь AD существует:
$SamAccountName='a.ivanov2'
if (@(Get-ADUser -Filter { SamAccountName -eq $SamAccountName }).Count -eq 0)
{ Write-Host "Пользователь $SamAccountName не существует"}
Вывести список компьютеров домена, на которые разрешено входить пользователю (ограничение через атрибут LogonWorkstations):
Get-ADUser AIvanov -Properties LogonWorkstations | Format-List Name, LogonWorkstations
Совет. Для получения данных о компьютерах Active Directory используется командлет Get-ADComputer.
Get-AdUser cmdlet uses to get one or more active directory users, use Get-AdUser filter or LDAPFilter parameters to search effectively for Ad users with PowerShell.
Get-ADUser Filter parameter uses the PowerShell expression language to write query strings that get adusers objects. Get aduser filter parameter syntax does not support PowerShell wildcards other than * and ? for active directory wildcard search operation.
In this blog, I will explain how to effectively use the Get-AdUser Filter parameter to search, retrieve aduser objects with PowerShell and get multiple filters on get-aduser.
Get-AdUser Filter Syntax
Get-AdUser Filter parameter uses PowerShell expression language as below
<filter> ::= "{" <FilterComponentList> "}"
Where, <FilterComponentList> is
<FilterComponentList> ::= <FilterComponent> | <FilterComponent> <JoinOperator> <FilterComponent> | <NotOperator> <FilterComponent>
Let’s understand FilterComponentList as below
<FilterComponent> ::= <attr> <FilterOperator> <value> | "(" <FilterComponent> ")"
In the above syntax,
<attr> ::= PropertyName or LDAPDisplayName of attribute
<value> ::= compare value with attr using <FilterOperator>
<FilterOperator> ::= "-eq" | "-le" | "-ge" | "-ne" | "-lt" | "-gt"| "-approx" | "-bor" | "-band" | "-recursivematch" | "-like" | "-notlike"
<FilterOperator> contains different types of operators like equal to, not equal to, greater than, wildcard search, etc.. to get aduser from active directory.
<JoinOperator> ::= "-and" | "-or"
<JoinOperator> has and, or to join the query to get aduser object using the filter.
<NotOperator> ::= "-not"
Let’s understand get aduser filter parameter examples as below
Get-AdUser Filter Name like
To get aduser using filter name like variable specified, run below command
$UserName = "Erick Jones" Get-AdUser -Filter {Name -like $UserName}
The first command stores the user name in a variable.
The second command gets ad user filter name like variable specified. In the second command, to use a variable in the filter, the filter condition is wrapped in curly braces.
Get-AdUser Filter DistinguishedName
To get aduser filter by distinguishedname from active directory, run below command
Get-ADUser -Filter "DistinguishedName -like 'CN=Erick Jones,OU=HR,DC=SHELLPRO,DC=LOCAL'"
This command gets aduser with distinguishedname like specified 'CN=Erick Jones,OU=HR,DC=SHELLPRO,DC=LOCAL'
Get-AdUser Filter SamAccountName
To find an active directory user filter using SamAccountName, run the below command
Get-ADUser -Filter {SamAccountName -eq 'garyw'}
This command gets aduser with SamAccountName equal to garyw
.
You can also use other <FilterOperator> like not equal to, like to get ad user using SamAccountName. To use a variable in the Get-AdUser filter, the filter condition is wrapped in curly braces.
Get-AdUser Filter Properties
Get-AdUser cmdlet in Active Directory retrieves the default set of user properties. To get additional properties, use the Properties parameter.
To get a filtered list of users and additional properties where the name like specified, run the below command
Get-ADUser -Filter {Name -like 'Gary Willy'} -Properties *
This command gets aduser filter where the name like Gary Willy
and retrieves additional properties.
Get Enabled Users from AD
To find active enabled users from an active directory, run the below command
Get-ADUser -Filter * -Property Enabled | Where-Object {$_.Enabled -like "true"} | FT Name, Enabled -Autosize
In the above PowerShell script,
Get-AdUser cmdlet in active directory retrieves adusers filter by Enabled property and has the value true.
Cool Tip: How to get aduser using userprincipalname in PowerShell!
Get-AdUser Multiple Filters
To get aduser from specific OU having enabled status and passwordlastset in a specific date, use Get-AdUser multiple filters on attributes as below
Get-ADUser -Filter "Enabled -eq 'true' -and PasswordLastSet -lt '08/01/2021'" -SearchBase "OU=HR,DC=SHELLPRO,DC=LOCAL" -Properties * | Select Name,PasswordLastSet
In the above PowerShell script,
We have used multiple filters with the Get-AdUser cmdlet to get ad users having enabled status as true and passwordlastset less than the specified date in OU
In the above command, Get-AdUser Multiple Filters on attributes used are Enabled -eq 'true'
and PasswordLastSet -lt '08/01/2021'
and both these filters are joined using and
operator.
Let’s understand other commonly used scripts to get aduser filters by different properties with PowerShell.
Get AdUser Filter using Created Date
To retrieve adusers filter using created date, run below command
Get-ADUser -Filter {Created -lt '08/02/2021'} | Select Name
This command gets ad user created before the specified date.
Get Active Directory Users in Deparment
To get aduser from a specific department in an active directory, run the below command
Get-ADUser -Filter "Department -like 'HR'"
Get-AdUser Filter by Email Address
To get aduser object in an active directory by email address, run the below command
Get-ADUser -Filter "Mail -like '[email protected]'
Get-AdUser Filter by Country
To find active directory users filter by country, run the below command
Get-ADUser -Filter "Country -eq 'US'"
Cool Tip: Using Get-ADObject to find active directory objects in PowerShell!
Conclusion
I hope the above-detailed article on using the Get-AdUser Filter parameter with examples is helpful to you. We have learned how to get multiple filters on Get-AdUser attributes.
You can retrieve active directory users effectively using the get aduser filter parameter.
You can find more topics about PowerShell Active Directory commands and PowerShell basics on the ShellGeek home page.
Get-ADUser, Arguably one of the most used cmdlets I use on a day to day basis. I’m sure the same goes for other sysadmins around the world if they’re managing a Windows environment. Today we’re going to do a deep dive on Get-ADUser and the multiple ways to find Active Directory users using Powershell. As always, let’s touch on the requirements needed to use Get-ADUser.
Table Of Contents
- Requirements
- Get-ADUser Examples and Parameter Overview
- Find AD User With Identity Parameter
- Get AD User Using The Filter Parameter
- Filter By Property
- Filter by Operator
- How To Use LDAP Filters
- Filter Using Ambiguous Name Resolution (ANR)
- Display All Of The Properties For A Specified User
- Query Active Directory Users By Organizational Unit
- Specify The OU Depth Of A Search
- Target The Domain Controller Of Your Choice
- Passing Alternate Credentials
- Get-ADUser From A Different Domain
- Conclusion
Requirements
Using the Active Directory Module has a few requirements that we’ll need to make sure are up and running in order for your queries to run successfully.
- An Active Directory Domain must be setup
- The Domain Controller you’re querying must have Active Directory Web Services Service running
- Remote Server Administration Tools (RSAT)
- For Windows 10 1903 and later, view setup guide
- Active Directory Light-Weight Directory Tools Windows Feature (RSAT-AD-Tools) if running on a Windows Server
Get-ADUser Examples and Parameter Overview
In this article we’ll cover several of the parameters used in the cmdlet along with examples and screenshots so you can see exactly how to utilize these to your benefit.
Find ADUser With Identity Parameter
Get-ADUser using the -Identity Parameter is typically the most commonly used parameter when people want to query a specific user. This is because the -Identity parameter is positioned as the first parameter so it can be omitted when running the actual query.
Example: Get-ADUser -Identity aryastark
will produce the exact same results as Get-ADUser aryastark
There are 4 attributes that are allowed when using Identity parameter. Let’s list them here along with an example of what it typically looks like.
- Distinguished Name
- CN=Arya Stark,OU=Excluded,DC=ad,DC=thesysadminchannel,DC=com
- ObjectGuid
- 643d7cb4-9682-4835-908d-d696ed476649
- Security Identifier (SID)
- S-1-5-21-3946430794-117524452-1540306727-8620
- sAMAccountName (username)
- aryastark
Example of the 4 attributes that are accepted
Get-ADUser Using The Filter Parameter
The -Filter parameter in the Get-ADUser cmdlet is definitely also another fan favorite. The phrase “Filter Left, Format right” definitely applies here in getting the data you need in a reduced amount of time. This is one of those fundamental Powershell concepts that everyone should learn early on.
Pro-Top: Replace Where-Object with Filter. Anytime a filter parameter is available use that instead of Where-Object for faster results.
Get AD User Properties
Let’s take a look at get ad user properties in action. Say we wanted to get everyone with the GivenName (firstname) of ‘Arya’ – What exactly would that query look like?
#Get All Active Directory users that have a first name of Arya Get-ADUser -Filter "GivenName -eq 'Arya'" | select Name, UserPrincipalName, Enabled Name UserPrincipalName Enabled ---- ----------------- ------- Arya Stark [email protected] True Arya Cruz [email protected] True Arya Jolie [email protected] True
Select object was added to condense output
You can find other filterable attributes by choosing any one of the attributes when running -Properties *
. Commonly used filters are UserPrincipalName, Surname, Mail and even Name or DisplayName.
Filter With Operators
Regarding operators, there are several choices such as equal, like, less than and even greater than that’s convenient for us to use.
When using the -eq
operator, the filter has to match the property exactly so make sure you specify the text exactly as it’s shown in AD. As noted in the above example, we searched for all users with the first name ‘Arya.’ Say we wanted to only filter for the Name ‘Arya Stark’.
#Get the AD user whos name is Arya Stark Get-ADUser -Filter "Name -eq 'Arya Stark'" | select Name, UserPrincipalName, Enabled Name UserPrincipalName Enabled ---- ----------------- ------- Arya Stark [email protected] True
Let’s now dive into the -like
operator and how to specifically use it for filters. A great example I’ve used in the past is to see who are all the people that have the word Remote in their AD Office Attribute.
#Get all users who are remote Get-ADUser -Filter "Office -like 'Remote*'" -Properties Office | select UserPrincipalName, Name, Office UserPrincipalName Name Office ----------------- ---- ------ [email protected] Arya Cruz Remote - California [email protected] Arya Stark Remote - Winterfell #Get all users who are in California Get-ADUser -Filter "Office -like '*California*'" -Properties Office | select UserPrincipalName, Name, Office UserPrincipalName Name Office ----------------- ---- ------ [email protected] Arya Cruz Remote - California arya[email protected] Arya Jolie Palo Alto - California
With regard to auditing, I’ve always found filtering accounts by LastLogonDate has always been extremely helpful. For an in-depth write-up check out the link above. Otherwise, let’s go over a quick example to get the gist of what’s happening. We’ll also couple it with the -and
operator to string multiple queries together and narrow down your filter.
#Get Remote Users who have not logged in, in over 90 days $CutoffDate = (Get-Date).AddDays(-90) Get-ADUser -Filter "LastLogonDate -lt '$CutoffDate' -and Office -like '*Remote*'" -Properties LastLogonDate ` | select UserPrincipalName, Name, LastLogonDate UserPrincipalName Name LastLogonDate ----------------- ---- ------------- ar[email protected] Arya Stark 3/17/2021 5:29:46 PM
How To Use LDAP Filters
To be perfectly honest, I can probably count the number of times on one hand that I’ve used an LDAP filter. The methods mentioned above have been ingrained into my brain since that’s how I learned. The reason being is that the syntax is a bit more complex and the standard operators like -and/-or don’t really come into play here.
If you’re great with VBScript then it might be up your alley. In any event, here we go.
#Get AD user using an LDAP filter query Get-ADUser -LdapFilter "(&(objectClass=user)(Name=Arya Stark))" | select Name, UserPrincipalName, Enabled Name UserPrincipalName Enabled ---- ----------------- ------- Arya Stark [email protected] True
Filter Using Ambiguous Name Resolution (ANR)
Ambiguous Name Resolution, aka ANR, allows multiple objects to be resolved on a single query. Think of it like a built-in -like operator that queries against GivenName, Surname, DisplayName, SamAccountName, physicalDeliveryOfficeName and even the Exchange MailNickName without any added effort.
ANR is especially useful in larger organizations where people share a similar display name. It just helps to truncate multiple -and/-or queries into a single function to ease your searches. Let’s cover an example of using ambiguous name resolution in an actual filter (using Arya Stark as our example).
#Get all users who have Arya in their name Get-ADUser -Filter "Anr -eq 'Arya'" | select UserPrincipalName, Name, Enabled UserPrincipalName Name Enabled ----------------- ---- ------- [email protected] Arya Stark True [email protected] Arya Cruz True [email protected] Arya Jolie True #Get all users who have Stark in their name Get-ADUser -Filter "Anr -eq 'Stark'" | select UserPrincipalName, Name, Enabled UserPrincipalName Name Enabled ----------------- ---- ------- [email protected] Arya Stark True
Notice we didn’t need to specify GivenName, Surname or even use the -Like Operator.
Display All Of The Properties For A Specified User
All Active Directory users have the same core attributes populated but they’re not displayed by default. If you notice in the examples above, I had to specify -Property
in order for Powershell to know to check those AD properties. If you omit the property parameter, the filter won’t find it even though the attribute is there on the user’s account.
A good thing is this allows a wildcard (*) so you can see what’s available. I would also recommend to explicitly specify your properties when querying many users so you’re not putting to much stress on the remote Domain Controller.
#Get all properties for a user. Get-ADUser aryastark -Properties *
Query Active Directory Users By Organizational Unit
The ability to query users by an Organizational Unit is an excellent method to ensure you’re getting the most out of your Active Directory OU structure. A great, real world example for this would be if you have your AD Org units structured by regional location and you’re looking to get all users in that location.
SearchBase uses the DistinguishedName as the parameter input. You can grab the DN by one of 2 ways.
- Query a user in that OU and select the DN property. Extract OU DN from there
- Use Get-ADOrganizationalUnit and filter by name
#Query a user in the OU and select the DN property to get the OU syntax. Get-ADUser aryastark DistinguishedName ----------------- CN=Arya Stark,OU=Excluded,DC=ad,DC=thesysadminchannel,DC=com #Use Get-ADOrganizationalUnit and filter by name Get-ADOrganizationalUnit -Filter "Name -like '*Excluded*'" | select DistinguishedName DistinguishedName ----------------- OU=Excluded,DC=ad,DC=thesysadminchannel,DC=com
Now that we have the Organizational Unit’s DistinguishedName, we can use that as the input parameter. This coupled with the -Filter parameter will help narrow your search by Org Unit.
#Get All users under the Excluded OU. Use a custom label to show Organizational Unit Get-ADUser -Filter * -SearchBase "OU=Excluded,DC=ad,DC=thesysadminchannel,DC=com" | select Name, ` @{Name = 'OrganizationalUnit'; ` Expression = {$Length = ($_.DistinguishedName).IndexOf(",OU"); $_.DistinguishedName.Substring($Length + 1) }} | ` Sort-Object OrganizationalUnit Name OrganizationalUnit ---- ------------------ Arya Jolie OU=Excluded,DC=ad,DC=thesysadminchannel,DC=com Isabella Contreras OU=Excluded,DC=ad,DC=thesysadminchannel,DC=com Arya Cruz OU=Excluded,DC=ad,DC=thesysadminchannel,DC=com Director of IT OU=Excluded,DC=ad,DC=thesysadminchannel,DC=com Arya Stark OU=Excluded,DC=ad,DC=thesysadminchannel,DC=com Test1 OU=Test,OU=Excluded,DC=ad,DC=thesysadminchannel,DC=com Test2 OU=Test,OU=Excluded,DC=ad,DC=thesysadminchannel,DC=com
Wildcards are also allowed to use with Filter to search for All
Specify The OU Depth Of A Search
Building off of the SearchBase parameter from above, you might have noticed that the search was recursive. Meaning that it drilled down to all Sub OU’s without having the need to specify them. The question however, is what if we don’t want to drill down. What if we only want that explicit OU?
This is where the SearchScope parameter comes into play. Using the same query above, let’s exclude the two test accounts in the Test OU.
#Get Users in the Excluded OU and Exclude the Test OU Users Get-ADUser -Filter * -SearchBase "OU=Excluded,DC=ad,DC=thesysadminchannel,DC=com" -SearchScope OneLevel | ` select Name, ` @{Name = 'OrganizationalUnit'; ` Expression = {$Length = ($_.DistinguishedName).IndexOf(",OU"); $_.DistinguishedName.Substring($Length + 1) }} Name OrganizationalUnit ---- ------------------ Arya Cruz OU=Excluded,DC=ad,DC=thesysadminchannel,DC=com Arya Jolie OU=Excluded,DC=ad,DC=thesysadminchannel,DC=com Arya Stark OU=Excluded,DC=ad,DC=thesysadminchannel,DC=com Director of IT OU=Excluded,DC=ad,DC=thesysadminchannel,DC=com Isabella Contreras OU=Excluded,DC=ad,DC=thesysadminchannel,DC=com
When SearchScope is omitted, it will default to Subtree
Target The Domain Controller Of Your Choice
Anytime you make an Active Directory query, you’ll most likely always default to a Domain Controller in your site. This is defined by Active Directory Sites and Services and an easy way to check what Domain Controller you’re currently authenticating against is to use $env:LogonServer
.
This is great and all, but what if you wanted to query a Domain Controller in another site, perhaps one across the globe? You would use the -Server
parameter to do this. Specifically for me, I always like to use the Primary Domain Controller, PDC Emulator, as this is the heart of all replication changes. If you specify this Domain Controller specifically, you can avoid waiting for replication and can move on with your script without adding sleep commands.
You can use Powershell to query, or transfer FSMO Roles to a different Domain Controller.
Let’s walk through an example for how to use the server parameter to specify the PDC emulator dynamically.
#Get PDC Emulator dynamically and save it to a variable for later use $DomainController = Get-ADDomain | select -ExpandProperty PDCEmulator $DomainController PAC-DC01.ad.thesysadminchannel.com Get-ADUser aryastark -Server $DomainController | select UserPrincipalName, Name UserPrincipalName Name ----------------- ---- [email protected] Arya Stark
Using the Server parameter can bypass replication times and it recommended for automation.
Passing Alternate Credentials for Get-ADUser
Being able to pass a different set of credentials would come in handy for use cases like automation or other use cases like users in a different domain. Since Active Directory grants read-only access to all users by default, there really isn’t a need to pass in alternate credentials if you’re querying something in the same domain. It should be able to do it with no problem.
When this comes in handy is if you need to make changes to AD Objects and you need to use different credentials. To make this happen you’ll use the -Credential
parameter and use Get-Credential
to securely set the username and password. Since we’re so keen on examples, let’s test it.
#Save user credentials into a variable using Get-Credential $Credential = Get-Credential -UserName 'adpcontreras' -Message 'Enter in a Password' PS C:> Get-ADUser aryastark -Credential $Credential | select UserPrincipalName, Name UserPrincipalName Name ----------------- ---- [email protected] Arya Stark
In the sprit of this article, we’ll pass on credentials for Get-ADUser
Get-ADUser From A Different Domain
If you happen to have multiple Domains in your forest and you’re too lazy to Remote Desktop into a Domain Controller on that domain to run the query (guilty of it myself from time to time), it’s absolutely helpful to be able to run your query from a single machine. You can do this by combining two of the parameters above. Those parameters being -Credential
as well as -Server
.
I don’t have any other domains in my forest so I won’t be able to provide a working screenshot. However, one thing to keep in mind is that you’ll need to provide the Fully Qualified Domain Name (FQDN) for the remote DC. Overall, the basic syntax should look like this:
#Save user credentials into a variable using Get-Credential $Credential = Get-Credential -UserName 'otherdomainmyaccount' -Message 'Enter in a Password' Get-ADUser myaccount -Server DC01.otherdomain.thesysadminchannel.com -Credential $Credential
Conclusion
Hopefully this deep dive on how to use Powershell Get AD User has been incredible helpful for you. I’m also hoping you learned a thing or two that you can implement in your environment. As I mentioned, Get-ADUser is probably one of the most fundamental cmdlets that anyone administrator should have in their arsenal of tools.
It can be useful, especially when providing reports on the current state of your environment. If you liked this article, feel free to browse our other Active Directory as well as our own personal Powershell gallery full of useful scripts. Finally, if you’re interested in video content, check out our Youtube Channel for sysadmin videos
The Active Directory is our main source when it comes to managing user accounts. The management console is great for looking up a single user, but when we need more, then the Get-ADUser cmdlet in PowerShell is much more powerful.
It allows us to quickly get a selection of users or to get details from a single or multiple users. It’s also a great way to export users’ accounts or information to a CSV file.
In this article, we are going to take a look at the get aduser cmdlet in PowerShell. Also, I will give you some useful examples when it comes to looking up and exporting ad users. And as a bonus, if have added a complete script to export your AD users.
Install Active Directory Module
To be able to use the Get-ADuser cmdlet in PowerShell you will need to have the Active Directory Module installed. By default, it’s installed on the domain controller, but on Windows 10 or 11 you will need to install it.
You can run the following PowerShell command in Windows 10 or 11 to install the module:
Add-WindowsCapability –online –Name “Rsat.ActiveDirectory.DS-LDS.Tools~~~~0.0.1.0”
The Get-ADUser cmdlet allows us to find user accounts in the Active Directory and extract information from them. The true power of this cmdlet is that it comes with different options to find those user accounts.
We have the following options when it comes to finding accounts:
- Identity – Find a user account based on it’s identity. This will return only a single user account
- Filter – Retrieve multiple objects (user accounts) based on a query
- LDAPFilter – Use a LDAP query string to filter the user accounts.
- SearchBase – Specify the Active Directory path (OU) to search in
- SearchScope – Specify how deep you want to search (baselevel, one level or complete subtree)
The identity parameter is mainly used when you know the user’s SAMAccountName
(login name). This allows you to select a single user from the Active Directory and view the properties of the account.
Get-ADUser -identity arhodes
As you can see some basic properties are returned of the user. We can use the -properties parameter to retrieve more information from the user. I will explain later more about retrieving different properties, but if you want to see all possible information of a user account, then use the following command:
Get-ADUser -identity arhodes -Propeties *
Using the Filter
A more common way to find user(s) in the Active Directory is to use the -filter
parameter. The filter parameter uses the PowerShell Expression Language the filter the result. This means that we can use the following operators in our queries:
Operator | Description |
---|---|
-eq | Equals |
-le | Less than or equal to |
-ge | Great than or equal to |
-ne | Not equal to |
-lt | Less then |
-gt | Greater then |
-like | Like |
-notlike | Not like |
-and -or | and/or |
-not | Not |
So let’s take a look at a couple of commonly used examples when filtering Active Directory users.
To find a user by their first or last name we can use the following filter
# Search on first name Get-ADUser -Filter "GivenName -eq 'Alan'" # Search on last name: Get-ADUser -Filter "Surname -eq 'Rhodes'"
Another option is to use the like operator in combination with a wildcard. This is particularly useful when you know a part of the name. Note the *
symbol that indicates the wildcard.
Get-ADUser -Filter "name -like '*rho*'"
The -ge
and -le
can for example be used to find all users based on their failed login attempts:
# Find all users that have more then 3 failed login attempts Get-ADUser -Filter "badpwdcount -ge 3"
To find all users that have a particular field not filled, we can use the -notlike
operator. For example, we want to retrieve all users that don’t have the email address field filled in.
Using the -notlike
filter in combination with a wildcard we can search for all users that don’t have any data in the email field.
Get-ADUser -Filter "Email -notlike '*'" | ft
You can easily combine this with the Set-ADUser
cmdlet, to update a lot of users with a single command. For example, we get all users that don’t have the webpage attribute filled, and set it to the company website:
Get-ADUser -Filter "homepage -notlike '*'" | Set-ADUser -HomePage "lazyadmin.nl"
Combining filters
We can also expand our filter query with multiple expressions. This allows you to further narrow down your filter queries. For example, we want to find all employees that are “account manager”.
If we would use the following filter, then it will return all users with the job title account manager:
Get-ADUser -Filter "title -eq 'account manager'" | Select Name,Enabled | ft
But the problem is that this also includes accounts that are disabled. We only want active users, we are not interested in the users that already left the company. Thus what we can do is also filter on accounts that are enabled:
Get-ADUser -Filter "title -eq 'account manager' -and enabled -like 'true'" | Select Name,Enabled | ft
The last filter example that I want to share with you is to get users based on a date field. Let’s say we want to find all inactive accounts.
For this, we can use the lastlogon
field in the Active Directory. We first need to create a date variable, by taking the date from today and subtracting 30 days from it.
We can then get all users that haven’t login the past 30 days on the domain:
$date = (Get-Date) - (New-TimeSpan -Days 30) Get-ADUser -Filter 'lastLogon -lt $date' | ft
Get ADUser SearchBase
When you have a lot of users in your Active Directory you probably want to narrow down the search. To do this we can use the -SearchBase parameter for the Get-ADUser cmdlet. This allows us to specify the distinguishedName
(OU level) where we want to search.
To specify the OU where we want to search we need to write the distinguishedName from the bottom up. Thus, the string starts with the OU where you want to search and ends with the domain name.
Take the following Active Directory structure, we want to get all users from the IT OU:
The SearchBase
string, in this case, would be:
1: IT 2: Amsterdam 3: Sites 4: Lazyadmin 5: NL "OU=IT,OU=Amsterdam,OU=Sites,DC=Lazyadmin,DC=NL"
Thus to get all users from the IT department in Amsterdam we can use the following PowerShell command:
Get-ADUser -Filter * -SearchBase "OU=IT,OU=Amsterdam,OU=Sites,DC=Lazyadmin,DC=NL" | ft
Using the SearchScope
By default, the -SearchBase
parameter will return all users from the specified OU and nested OU’s. With the -SearchScope
parameter, we can specify how deep or not we want to search through the Active Directory tree.
Let’s say we want the users from the Amsterdam OU, but not from the nested OU’s.
If we would use the following SearchBase, then all users, including those from the IT, Marketing, and Production OU’s are returned:
Get-ADUser -Filter * -SearchBase "OU=Amsterdam,OU=Sites,DC=Lazyadmin,DC=NL" | ft
To get only the users from the Amsterdam OU we can use the SearchScope parameter. This allows us to limit the SearchBase to the current level only:
Get-ADUser -Filter * -SearchBase "OU=IT,OU=Amsterdam,OU=Sites,DC=Lazyadmin,DC=NL" -SearchScope OneLevel | ft
Get ADUser Properties
When using the Get ADUser cmdlet you may have noticed that it will only return a couple of properties of the user account. But as you probably know, the user account has a lot more properties.
To return all properties, we need to add the -properties parameter to the cmdlet:
Get-ADUser -identity arhodes -properties *
This will return a long list with all the possible properties of a user account. Now, this is probably too much information, so you might want to specify the actual fields that you need.
To do this you will need to pipe the select command behind it, where we specify the fields that we need. It’s also a good idea to specify the same fields in the properties parameter, instead of requesting all the data.
For example, if you want the full name, job title, and email address, then you could use the following command:
Get-ADUser -identity arhodes -properties emailaddress,title | select name,emailaddress,title
Selecting Distinct Values
The next tip is not really related to the Get ADUser cmdlet, but it’s something I use often in combination with getting user information out of the Active Directory.
When you want to export a list of all possible job titles in your Active Directory you can use the -Unique parameter in PowerShell.
Get-ADUser -Filter * -Properties title | Select title -Unique
This command will give you all the job titles that you have used in your Active Directory.
Export AD Users to CSV with PowerShell
Exporting results in PowerShell to CSV is pretty common. We all use PowerShell often to retrieve information only to process it further in Excel. I have written a complete guide about the Export-CSV cmdlet, but I also want to give you a couple of useful examples when working with the Get-ADUser cmdlet.
To simply export all AD Users we can use the following command:
Get-ADUser -filter * | Export-CSV c:tempusers.csv -NoTypeInformation
But as you will notice this will give not really the results that you are looking for. It will include all user accounts, enabled and disabled, and not really the information that we need.
Export extra fields
So the first step is to specify the fields that we really want to export. For example, if we want to export the names, job titles, department, and email addresses we could use the following command:
Get-ADUser -filter * -properties mail,title,department | select name,title,department,mail | Export-CSV c:tempusers.csv -NoTypeInformation
Export only enabled users
To export only the active (enabled) users from the AD to a CSV file we can use the following command in PowerShell:
# Export all enabled users Get-ADUser -Filter "Enabled -like 'true'" | Export-CSV c:tempusers.csv -NoTypeInformation # OR Export only disabled users Get-ADUser -Filter "Enabled -like 'False'" | Export-CSV c:tempusers.csv -NoTypeInformation
Complete Export AD Users to CSV Script
I have created a PowerShell script that will Export all AD Users to CSV for you with the most commonly needed properties.
When you run the script you specify a couple of options:
- Get the manager’s display name or not (default true)
- Specify the searchBase (OU), default whole Active Directory
- Get enabled or disabled accounts or both (default only enabled)
- Export path CSV file (default script location)
The script will get all the user accounts from the active directory if you don’t specify the searchBase (OU). It’s also possible to specify multiple OU’s:
.Get-ADusers.ps1 -searchBase "OU=users,OU=Amsterdam,DC=LazyAdmin,DC=Local","OU=users,OU=Oslo,DC=LazyAdmin,DC=Local" -path c:tempusers.csv
Follow these steps to export the AD Users with the PowerShell script:
- Download the complete Export AD Users script from my Github
- Open PowerShell and navigate to the script
- Run the export script: Get-ADUsers.ps1 -csvpath c:tempadusers.csv
When complete, the script will automatically open Excel for you. You can also run the script without the csvpath parameter to output the result to the console.
param( [Parameter( Mandatory = $false, HelpMessage = "Get the users manager" )] [switch]$getManager = $true, [Parameter( Mandatory = $false, HelpMessage = "Enter the searchbase between quotes or multiple separated with a comma" )] [string[]]$searchBase, [Parameter( Mandatory = $false, HelpMessage = "Get accounts that are enabled, disabled or both" )] [ValidateSet("true", "false", "both")] [string]$enabled = "true", [Parameter( Mandatory = $false, HelpMessage = "Enter path to save the CSV file" )] [string]$CSVpath ) Function Get-Users { <# .SYNOPSIS Get users from the requested DN #> param( [Parameter( Mandatory = $true )] $dn ) process{ # Set the properties to retrieve $properties = @( 'name', 'userprincipalname', 'mail', 'title', 'enabled', 'manager', 'department', 'telephoneNumber', 'office', 'mobile', 'streetAddress', 'city', 'postalcode', 'state', 'country', 'description', 'lastlogondate' ) # Get enabled, disabled or both users switch ($enabled) { "true" {$filter = "enabled -eq 'true'"} "false" {$filter = "enabled -eq 'false'"} "both" {$filter = "*"} } # Get the users Get-ADUser -Filter $filter -Properties $properties -SearchBase $dn | select $properties } } Function Get-AllADUsers { <# .SYNOPSIS Get all AD users #> process { Write-Host "Collecting users" -ForegroundColor Cyan $users = @() if ($searchBase) { # Get the requested mailboxes foreach ($dn in $searchBase) { Write-Host "- Get users in $dn" -ForegroundColor Cyan $users += Get-Users -dn $dn } }else{ # Get distinguishedName of the domain $dn = Get-ADDomain | Select -ExpandProperty DistinguishedName Write-Host "- Get users in $dn" -ForegroundColor Cyan $users += Get-Users -dn $dn } $users | ForEach { $manager = "" If (($getManager.IsPresent) -and ($_.manager)) { # Get the users' manager $manager = Get-ADUser -Identity $_.manager | Select -ExpandProperty Name } [pscustomobject]@{ "Name" = $_.Name "UserPrincipalName" = $_.UserPrincipalName "Emailaddress" = $_.mail "Job title" = $_.Title "Manager" = $manager "Department" = $_.Department "Office" = $_.Office "Phone" = $_.telephoneNumber "Mobile" = $_.mobile "Enabled" = $_.enabled "Street" = $_.StreetAddress "City" = $_.City "Postal code" = $_.PostalCode "State" = $_.State "Country" = $_.Country "Description" = $_.Description "Last login" = $_.lastlogondate } } } } If ($CSVpath) { # Get mailbox status Get-AllADUsers | Sort-Object Name | Export-CSV -Path $CSVpath -NoTypeInformation -Encoding UTF8 if ((Get-Item $CSVpath).Length -gt 0) { Write-Host "Report finished and saved in $CSVpath" -ForegroundColor Green # Open the CSV file Invoke-Item $path } else { Write-Host "Failed to create report" -ForegroundColor Red } } Else { Get-AllADUsers | Sort-Object Name }
Wrapping Up
The Get ADUser cmdlet is really useful when it comes to exacting information out of the Active Directory. Using the different filters allows you to retrieve only the information that you really need.
To Export the AD users to CSV you can try the script. You can easily change the properties that it retrieves to your own need.
If you have any questions, just drop a comment below.
external help file | Module Name | online version | schema |
---|---|---|---|
Microsoft.ActiveDirectory.Management.dll-Help.xml |
ActiveDirectory |
https://learn.microsoft.com/powershell/module/activedirectory/get-aduser?view=windowsserver2012-ps&wt.mc_id=ps-gethelp |
2.0.0 |
SYNOPSIS
Gets one or more Active Directory users.
SYNTAX
Filter (Default)
Get-ADUser [-AuthType <ADAuthType>] [-Credential <PSCredential>] -Filter <String> [-Properties <String[]>]
[-ResultPageSize <Int32>] [-ResultSetSize <Int32>] [-SearchBase <String>] [-SearchScope <ADSearchScope>]
[-Server <String>] [<CommonParameters>]
Identity
Get-ADUser [-AuthType <ADAuthType>] [-Credential <PSCredential>] [-Identity] <ADUser> [-Partition <String>]
[-Properties <String[]>] [-Server <String>] [<CommonParameters>]
LdapFilter
Get-ADUser [-AuthType <ADAuthType>] [-Credential <PSCredential>] -LDAPFilter <String> [-Properties <String[]>]
[-ResultPageSize <Int32>] [-ResultSetSize <Int32>] [-SearchBase <String>] [-SearchScope <ADSearchScope>]
[-Server <String>] [<CommonParameters>]
DESCRIPTION
The Get-ADUser cmdlet gets a specified user object or performs a search to get multiple user objects.
The Identity parameter specifies the Active Directory user to get.
You can identify a user by its distinguished name (DN), GUID, security identifier (SID), or Security Account Manager (SAM) account name.
You can also set the parameter to a user object variable such as $<localUserObject>
or pass a user object through the pipeline to the Identity parameter.
To search for and retrieve more than one user, use the Filter or LDAPFilter parameters.
The Filter parameter uses the PowerShell Expression Language to write query strings for Active Directory.
PowerShell Expression Language syntax provides rich type-conversion support for value types received by the Filter parameter.
For more information about the Filter parameter syntax, type Get-Help about_ActiveDirectory_Filter
.
If you have existing Lightweight Directory Access Protocol (LDAP) query strings, you can use the LDAPFilter parameter.
This cmdlet retrieves a default set of user object properties.
To retrieve additional properties use the Properties parameter.
For more information about how to determine the properties for user objects, see the Properties parameter description.
EXAMPLES
Example 1: Get all of the users in a container
PS C:> Get-ADUser -Filter * -SearchBase "OU=Finance,OU=UserAccounts,DC=FABRIKAM,DC=COM"
This command gets all users in the container OU=Finance,OU=UserAccounts,DC=FABRIKAM,DC=COM.
Example 2: Get a filtered list of users
PS C:> Get-ADUser -Filter 'Name -like "*SvcAccount"' | Format-Table Name,SamAccountName -A
Name SamAccountName
---- --------------
SQL01 SvcAccount SQL01
SQL02 SvcAccount SQL02
IIS01 SvcAccount IIS01
This command gets all users that have a name that ends with SvcAccount.
Example 3: Get all of the properties for a specified user
PS C:> Get-ADUser -Identity ChewDavid -Properties *
Surname : David
Name : Chew David
UserPrincipalName :
GivenName : David
Enabled : False
SamAccountName : ChewDavid
ObjectClass : user
SID : S-1-5-21-2889043008-4136710315-2444824263-3544
ObjectGUID : e1418d64-096c-4cb0-b903-ebb66562d99d
DistinguishedName : CN=Chew David,OU=NorthAmerica,OU=Sales,OU=UserAccounts,DC=FABRIKAM,DC=COM
This command gets all of the properties of the user with the SAM account name ChewDavid.
Example 4: Get a specified user
PS C:> Get-ADUser -Filter "Name -eq 'ChewDavid'" -SearchBase "DC=AppNC" -Properties "mail" -Server lds.Fabrikam.com:50000
This command gets the user with the name ChewDavid in the Active Directory Lightweight Directory Services (AD LDS) instance.
Example 5: Get all enabled user accounts
C:PS> Get-ADUser -LDAPFilter '(!userAccountControl:1.2.840.113556.1.4.803:=2)'
This command gets all enabled user accounts in Active Directory using an LDAP filter.
PARAMETERS
-AuthType
Specifies the authentication method to use.
The acceptable values for this parameter are:
- Negotiate or 0
- Basic or 1
The default authentication method is Negotiate.
A Secure Sockets Layer (SSL) connection is required for the Basic authentication method.
Type: ADAuthType Parameter Sets: (All) Aliases: Accepted values: Negotiate, Basic Required: False Position: Named Default value: Microsoft.ActiveDirectory.Management.AuthType.Negotiate Accept pipeline input: False Accept wildcard characters: False
-Credential
Specifies the user account credentials to use to perform this task.
The default credentials are the credentials of the currently logged on user unless the cmdlet is run from an Active Directory PowerShell provider drive.
If the cmdlet is run from such a provider drive, the account associated with the drive is the default.
To specify this parameter, you can type a user name, such as User1 or Domain01User01 or you can specify a PSCredential object.
If you specify a user name for this parameter, the cmdlet prompts for a password.
You can also create a PSCredential object by using a script or by using the Get-Credential cmdlet.
You can then set the Credential parameter to the PSCredential object.
If the acting credentials do not have directory-level permission to perform the task, Active Directory PowerShell returns a terminating error.
Type: PSCredential Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False
-Filter
Specifies a query string that retrieves Active Directory objects.
This string uses the PowerShell Expression Language syntax.
The PowerShell Expression Language syntax provides rich type-conversion support for value types received by the Filter parameter.
The syntax uses an in-order representation, which means that the operator is placed between the operand and the value.
For more information about the Filter parameter, type Get-Help about_ActiveDirectory_Filter
.
Syntax:
The following syntax uses Backus-Naur form to show how to use the PowerShell Expression Language for this parameter.
<filter> ::= «{» <FilterComponentList> «}»
<FilterComponentList> ::= <FilterComponent> | <FilterComponent> <JoinOperator> <FilterComponent> | <NotOperator> <FilterComponent>
<FilterComponent> ::= <attr> <FilterOperator> <value> | «(» <FilterComponent> «)»
<FilterOperator> ::= «-eq» | «-le» | «-ge» | «-ne» | «-lt» | «-gt»| «-approx» | «-bor» | «-band» | «-recursivematch» | «-like» | «-notlike»
<JoinOperator> ::= «-and» | «-or»
<NotOperator> ::= «-not»
<attr> ::= <PropertyName> | <LDAPDisplayName of the attribute>
<value>::= <compare this value with an <attr> by using the specified <FilterOperator>>
For a list of supported types for <value>, type Get-Help about_ActiveDirectory_ObjectModel
.
Note: For String parameter type, PowerShell will cast the filter query to a string while processing the command. When using a string variable as a value in the filter component, make sure that it complies with the PowerShell Quoting Rules. For example, if the filter expression is double-quoted, the variable should be enclosed using single quotation marks:
Get-ADUser -Filter «Name -like ‘$UserName'». On the contrary, if curly braces are used to enclose the filter, the variable should not be quoted at all: Get-ADUser -Filter {Name -like $UserName}.
Note: PowerShell wildcards other than *, such as ?, are not supported by the Filter syntax.
Note: To query using LDAP query strings, use the LDAPFilter parameter.
Type: String Parameter Sets: Filter Aliases: Required: True Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False
-Identity
Specifies an Active Directory user object by providing one of the following property values.
The identifier in parentheses is the LDAP display name for the attribute.
The acceptable values for this parameter are:
- A distinguished name
- A GUID (objectGUID)
- A security identifier (objectSid)
- A SAM account name (sAMAccountName)
The cmdlet searches the default naming context or partition to find the object.
If two or more objects are found, the cmdlet returns a non-terminating error.
This parameter can also get this object through the pipeline or you can set this parameter to an object instance.
Type: ADUser Parameter Sets: Identity Aliases: Required: True Position: 0 Default value: None Accept pipeline input: True (ByValue) Accept wildcard characters: False
-LDAPFilter
Specifies an LDAP query string that is used to filter Active Directory objects.
You can use this parameter to run your existing LDAP queries.
The Filter parameter syntax supports the same functionality as the LDAP syntax.
For more information, see the Filter parameter description or type Get-Help about_ActiveDirectory_Filter
.
Type: String Parameter Sets: LdapFilter Aliases: Required: True Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False
-Partition
Specifies the distinguished name of an Active Directory partition.
The distinguished name must be one of the naming contexts on the current directory server.
The cmdlet searches this partition to find the object defined by the Identity parameter.
In many cases, a default value is used for the Partition parameter if no value is specified.
The rules for determining the default value are given below.
Note that rules listed first are evaluated first, and when a default value can be determined, no further rules are evaluated.
In AD DS environments, a default value for Partition is set in the following cases:
- If the Identity parameter is set to a distinguished name, the default value of Partition is automatically generated from this distinguished name.
- If running cmdlets from an Active Directory provider drive, the default value of Partition is automatically generated from the current path in the drive.
- If none of the previous cases apply, the default value of Partition is set to the default partition or naming context of the target domain.
In AD LDS environments, a default value for Partition is set in the following cases:
- If the Identity parameter is set to a distinguished name, the default value of Partition is automatically generated from this distinguished name.
- If running cmdlets from an Active Directory provider drive, the default value of Partition is automatically generated from the current path in the drive.
- If the target AD LDS instance has a default naming context, the default value of Partition is set to the default naming context.
To specify a default naming context for an AD LDS environment, set the msDS-defaultNamingContext property of the Active Directory directory service agent object (nTDSDSA) for the AD LDS instance. - If none of the previous cases apply, the Partition parameter does not take any default value.
Type: String Parameter Sets: Identity Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False
-Properties
Specifies the properties of the output object to retrieve from the server.
Use this parameter to retrieve properties that are not included in the default set.
Specify properties for this parameter as a comma-separated list of names.
To display all of the attributes that are set on the object, specify * (asterisk).
To specify an individual extended property, use the name of the property.
For properties that are not default or extended properties, you must specify the LDAP display name of the attribute.
To retrieve properties and display them for an object, you can use the Get-* cmdlet associated with the object and pass the output to the Get-Member cmdlet.
Type: String[] Parameter Sets: (All) Aliases: Property Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False
-ResultPageSize
Specifies the number of objects to include in one page for an Active Directory Domain Services query.
The default is 256 objects per page.
Type: Int32 Parameter Sets: Filter, LdapFilter Aliases: Required: False Position: Named Default value: 256 Accept pipeline input: False Accept wildcard characters: False
-ResultSetSize
Specifies the maximum number of objects to return for an Active Directory Domain Services query.
If you want to receive all of the objects, set this parameter to $Null (null value).
You can use Ctrl+C to stop the query and return of objects.
The default is $Null.
Type: Int32 Parameter Sets: Filter, LdapFilter Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False
-SearchBase
Specifies an Active Directory path to search under.
When you run a cmdlet from an Active Directory provider drive, the default value of this parameter is the current path of the drive.
When you run a cmdlet outside of an Active Directory provider drive against an AD DS target, the default value of this parameter is the default naming context of the target domain.
When you run a cmdlet outside of an Active Directory provider drive against an AD LDS target, the default value is the default naming context of the target LDS instance if one has been specified by setting the msDS-defaultNamingContext property of the Active Directory directory service agent (DSA) object (nTDSDSA) for the AD LDS instance.
If no default naming context has been specified for the target AD LDS instance, then this parameter has no default value.
When the value of the SearchBase parameter is set to an empty string and you are connected to a GC port, all partitions are searched.
If the value of the SearchBase parameter is set to an empty string and you are not connected to a GC port, an error is thrown.
Type: String Parameter Sets: Filter, LdapFilter Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False
-SearchScope
Specifies the scope of an Active Directory search.
The acceptable values for this parameter are:
- Base or 0
- OneLevel or 1
- Subtree or 2
A SearchScope with a Base value searches only for the given user. If an OU is specified in the SearchBase parameter, no user will be returned by, for example, a specified Filter statement.
A OneLevel query searches the immediate children of that path or object. This option only works when an OU is given as the SearchBase. If a user is given, no results are returned.
A Subtree query searches the current path or object and all children of that path or object.
Type: ADSearchScope Parameter Sets: Filter, LdapFilter Aliases: Accepted values: Base, OneLevel, Subtree Required: False Position: Named Default value: Subtree Accept pipeline input: False Accept wildcard characters: False
-Server
Specifies the Active Directory Domain Services instance to connect to, by providing one of the following values for a corresponding domain name or directory server.
The service may be any of the following: Active Directory Lightweight Domain Services, Active Directory Domain Services or Active Directory Snapshot instance.
Domain name values:
- Fully qualified domain name (FQDN)
- NetBIOS name
Directory server values:
- Fully qualified directory server name
- NetBIOS name
- Fully qualified directory server name and port
The default value for the Server parameter is determined by one of the following methods in the order that they are listed:
- By using Server value from objects passed through the pipeline.
- By using the server information associated with the Active Directory PowerShell provider drive, when running under that drive.
- By using the domain of the computer running PowerShell.
Type: String Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False
CommonParameters
This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see about_CommonParameters.
INPUTS
None or Microsoft.ActiveDirectory.Management.ADUser
A user object is received by the Identity parameter.
OUTPUTS
Microsoft.ActiveDirectory.Management.ADUser
Returns one or more user objects.
This cmdlet returns a default set of ADUser property values.
To retrieve additional ADUser properties, use the Properties parameter.
To get a list of the default set of properties of an ADUser object, use the following command:
Get-ADUser
<user>| Get-Member
To get a list of the most commonly used properties of an ADUser object, use the following command:
Get-ADUser
<user>-Properties Extended | Get-Member
To get a list of all the properties of an ADUser object, use the following command:
Get-ADUser
<user>-Properties * | Get-Member
NOTES
- This cmdlet does not work with an Active Directory Snapshot.
RELATED LINKS
New-ADUser
Remove-ADUser
Set-ADUser