An alternative to this is to write a PowerShell script. When you need to retrieve a list of computer names, the Get-ADComputer cmdlet is the most useful. You can use –Filter and specify the target OU via –SearchBase to restrict the output of your query. Add the Export-Csv parameter at the end, run the script, and then open the resulting csv file to examine the results of the commands.
Using PowerShell
Open the file produced by the script in MS Excel:
How Lepide Auditor Helps
Lepide Auditor for Active Directory provides several pre-defined reports to make AD auditing easy and to list all computers in an OU, you can use the All Computers Report:
To run the All Computers Report:
- Select Lepide Auditor, Reports and from this screen, expand Active Directory, select All Computers
- Add a filter to specify the OU
- Select Generate Report
- The report is generated and can be filtered, sorted and exported to CSV and PDF format
The Get-ADComputer PowerShell cmdlet is a powerful tool for managing AD computers. It can be used to retrieve information about computer objects, search for computer objects based on specific criteria, and perform various actions on computer objects.
What is Get-ADComputer used for?
Get-ADComputer is a PowerShell cmdlet that retrieves one or more computers from Active Directory. It can be used to retrieve a single computer by specifying its distinguishedname, GUID, security identifier (SID), or SAMaccountname. Alternatively, it can be used to search for and retrieve multiple computers by using the Filter or LDAPFilter parameters. I’ll touch on those later on.
The basics of Get-ADComputer
It is a powerful tool that can be used to perform a variety of tasks, such as:
- Listing all computers in a domain
- Finding computers that meet specific criteria, such as operating system, location, or department
- Exporting computer information to a file or database
- Managing computer objects
The Get-ADComputer cmdlet, part of the Active Directory module (RSAT), has a number of parameters that can be used to control its output. For example, the Identity parameter can be used to specify a specific computer object’s name or distinguished name. The Filter parameter can be used to search for computers that meet specific criteria. The Properties parameter can be used to specify the properties that should be returned for each computer object. We’ll dig deeper into these concepts soon.
Commonly used Get-AdComputer parameters
And here we are, delving deeper. Let’s go through some of the basic parameters used with Get-ADComputer.
Get-ADComputer -Filter * | ft

Here are all of the computers in my domain, including domain controllers.
Using -SearchBase to limit results to specific OUs in AD
The -SearchBase parameter is used to specify the distinguished name (DN) of the search base for the query. This is also sometimes described as changing the ‘searchscope’ of the command. This parameter limits the search to a specific Organizational Unit (OU) or its child OUs.
Here is an example of how to use Get-ADComputer with the -SearchBase parameter.
Get-ADComputer -Filter * -SearchBase "OU=Domain Member Servers,DC=reinders,DC=local"

This shows all the computer objects in the specified OU “Domain Member Servers”. Very helpful. And, as you know, PowerShell allows you to get this information and then optionally pipe this to, as an example, Set-ADComputer, and modify the same attributes on a small or large list of computer objects in one command!
To search for computer objects using the CN= attribute, you can use the -SearchBase parameter with the distinguished name (DN) of the search base for the query. Here is an example of how to use Get-ADComputer to retrieve all computer objects in the Computers container.
Get-ADComputer -Filter * -SearchBase "CN=Computers,DC=reinders,DC=local" | ft

Using Get-AdComputer -Properties
Another handy parameter is the -Properties parameter. It is used to specify the additional properties of the computer object that should be retrieved along with the default set of properties.
Let me show you an example of how to use Get-ADComputer with the -Properties parameter.
Get-ADComputer -Identity "WS19-SSSE-01" -Properties IPv4Address,LastLogonDate,OperatingSystem,OperatingSystemVersion,WhenCreated

Listing, filtering, and sorting results using Get-AdComputer
Let me go into some more detail and depth around finding precisely what you need. As an IT Pro, you get pulled and pinged every day with specific queries from a variety of people in your environment. Hopefully, my examples will boost your efficiency when responding to said queries.
Retrieve a list of computers in an Active Directory domain
Again, we can get a simple listing of all computer objects by using ‘-Filter *’ and piping it to Format-Table.
Get-ADComputer -Filter * | ft
This displays all your computer objects in a simple table format. You can use this output to go a few levels deeper into specific computer objects or specific OUs.
Filtering results based on the computer name
Get-ADComputer -Filter {Name -like "WS19*"}

So quick and easy. We used the -Filter command and checked for objects wherein the ‘Name’ attribute starts with ‘WS19’ with anything else after it. Say that three times fast.
Sorting your results
Next, I’ll show you some examples and methods of using ‘Sort-Object‘ in PowerShell to sort the output of your computer objects in AD.
Get-ADComputer -Filter * | Sort-Object Name | ft

Let’s sort them by the operating system.
Get-ADComputer -Filter * -Properties OperatingSystem | Sort-Object OperatingSystem -Descending | ft

So awesome. There is so much power here. It goes from Windows Server 2022 Datacenter all the way to Windows 10 Enterprise. Slick.
Exporting your results to a CSV file
To export the results of Get-ADComputer to a CSV file, you can use the Export-CSV cmdlet, as you’ve seen before. Here is an example of how to use Get-ADComputer to retrieve all computers in the domain and export the results to a CSV file.
Get-ADComputer -Filter * | Export-CSV -Path "C:\Users\administrator.reinders\Downloads\Computers.csv" -NoTypeInformation
I didn’t include a screenshot here as there is no output.
This command retrieves all your computer objects in the domain and it exports them to a CSV file named “Computers.csv” in the location specified in the ‘-Path’ parameter.

How to filter for inactive computers using Get-AdComputer
To filter for inactive computers, you can use the LastLogonDate property and the Where-Object cmdlet. Here is an example of retrieving all inactive computers that have not logged on in the last 90 days.
$DaysInactive = 90
$time = (Get-Date).AddDays(-($DaysInactive))
Get-ADComputer -Filter {LastLogonDate -lt $time} -Properties LastLogonDate | Select-Object Name, LastLogonDate

You can further refine your query results by using Select-Object to display only the properties you need. Let me show you some helpful examples here.
Get-ADComputer -Filter * -Properties OperatingSystem | Select-Object Name, OperatingSystem

The default list of properties returned with Get-ADComputer does not include ‘OperatingSystem’, so I need to include that with the ‘-Properties’ parameter. And there we are.
Here’s another useful one – you can also use LDAP queries. Here, we query your AD using the ‘LDAPFilter’ parameter to find all the ‘Server’ computer objects. This scans the operatingsystem attribute for anything with ‘server’ in the name.
Get-ADComputer -LDAPFilter "(&(objectCategory=computer)(operatingSystem=*Server*))" -Properties Name, OperatingSystem | ft�

Accessing results from a specific domain controller (-Server)
If you have the need to retrieve the information from a specific domain controller in your environment, you can use the -Server parameter thusly.
Get-ADComputer -Filter * -Server "WS16-DC2.reinders.local" | ft

I know there are use cases where this would be useful, but, it is slightly more obscure and therefore is in the ‘Advanced’ section of my post.
Retrieve a single computer or multiple computers by using various Get-AdComputer parameters
In conclusion, Get-ADComputer is a powerful cmdlet that can be used to retrieve computer objects from Active Directory. It can be used to retrieve a single computer or multiple computers by using various parameters such as -Identity, -Filter, -LDAPFilter, -SearchBase, and -Properties.
Some advanced techniques include filtering for inactive computers, searching for computers in a specific OU and its child OUs, exporting results to a CSV file, and sorting results by one or more properties.
Table of Contents
List All Users from an OU with PowerShell
Step 1. Open PowerShell
Step 2. Copy and paste the command below. You will need the distinguishedName of the OU, see details below.
get-aduser -filter * -searchbase "OU=Purchasing,OU=ADPRO Users,DC=ad,DC=activedirectorypro,DC=com" | select name, DistinguishedName
Get Users in OU and Sub OU
get-aduser -filter * -searchbase "OU=Purchasing,OU=ADPRO Users,DC=ad,DC=activedirectorypro,DC=com" -SearchScope subtree | select name, DistinguishedName
How to Get the DistinguishedName of OU
Click on the “Attribute Editor” and copy the distinguishedName value.
If you do not see the Attribute Editor tab you need to turn on “Advanced Features” from the view dropdown.
Step 1. Open the AD Pro Toolkit.
Step 3. Click Browse to select one or more OUs
Step 4. Click Run
Не секрет, что начиная с первой версии PowerShell, Microsoft пытается сделать из него основной инструмент администрирования Windows. И во многом это получается! Сегодня на простых примерах, мы покажем возможности PowerShell, которые можно использовать для получения различной информации о пользователях Active Directory и их атрибутах.
Примечание. Ранее для получения информации об атрибутах учетных записей пользователей AD приходилось использовать различные инструменты: консоль ADUC (в том числе сохраненные запросы AD), vbs скрипты, утилиту dsquery и т.п. Выбор инструмента обычно основывался на поставленной задачи и способностях администратора в программировании.
Запускаем окно Powershll с правами администратора и импортируем модуль Active Directory командой:
Import-Module activedirectory
Совет. В Windows Server 2012 и выше этот пункт можно пропустить, так как модуль PowerShell Active Directory подключен по-умолчанию.
help Get-ADUser
Чтобы вывести список всех учетных записей домена, выполним команду:
Get-ADUser -filter *
Важно. Не рекомендуется выполнять эту команду в доменах с большим количеством аккаунтов, т.к. возможно перегрузка контроллера домена, предоставляющего данные.
Формат возвращаемого списка не очень удобен для использования, выводится только некоторые основные 10 из более 120 атрибутов и свойств учетных записей пользователей (DN, SamAccountName, Name, SID, UPN и т.д) кроме того, мы видим, что информация о времени последней смены пароля отсутствует.
Get-ADUser -identity tuser -properties *
- PasswordExpired
- PasswordLastSet
- PasswordNeverExpires
Get-ADUser tuser -properties PasswordExpired, PasswordLastSet, PasswordNeverExpires
Теперь в данных пользователя есть информация о дате смены пароля и времени, когда срок пароля истечет. Представим информацию в более удобном табличном виде:
Get-ADUser -filter * -properties PasswordExpired, PasswordLastSet, PasswordNeverExpires | ft Name, PasswordExpired, PasswordLastSet, PasswordNeverExpires
Чтобы вывести данные пользователей из определенной OU, воспользуемся параметром SearchBase:
Get-ADUser -SearchBase ‘OU=Moscow,DC=winitpro,DC=loc’ -filter * -properties PasswordExpired, PasswordLastSet, PasswordNeverExpires | ft Name, PasswordExpired, PasswordLastSet, PasswordNeverExpires
Результат выполнения команды можно выгрузить в текстовый файл:
Get-ADUser -filter * -properties PasswordExpired, PasswordLastSet, PasswordNeverExpires | ft Name, PasswordExpired, PasswordLastSet, PasswordNeverExpires > C:\temp\users.txt
Или в CSV, который в дальнейшем будет удобно экспортировать в Excel (дополнительно с помощью sort-object отсортируем таблицу по столбцу PasswordLastSet , а также добавим условие where – имя пользователя должно содержать строку «Dmitry»):
Get-ADUser -filter * -properties PasswordExpired, PasswordLastSet, PasswordNeverExpires | where {$_.name –like “*Dmitry*”} | sort-object PasswordLastSet | select-object Name, PasswordExpired, PasswordLastSet, PasswordNeverExpires | Export-csv -path c:\temp\user-password-expires-2015.csv
Таким образом, можно построить таблицу с любыми необходимыми атрибутами пользователей Active Directory.
Совет. Для получения данных о компьютерах Active Directory используется командлет Get-ADComputer.
Далее приведем еще несколько полезных вариантов запросов о пользователях Active Directory с помощью различных фильтров. Вы можете их комбинировать для получения необходимого списка пользователей AD:
Вывод пользователей 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 {Enabled -eq $True} -properties passwordExpired | where {$_.PasswordExpired}
Список активных учеток с почтовыми адресами:
Get-ADUser -Filter {(mail -ne "null") -and (Enabled -eq "true")} -Properties Surname,GivenName,mail | Select-Object Name,Surname,GivenName,mail | Format-Table
Задача: для списка учетных записей, которые хранятся в текстовом файле (по одной учетке в строке) нужно получить телефон пользователя в AD и выгрузить информацию в текстовый csv файл (можно легко импортировать в Esxel).
Import-Csv c:\ps\usernsme_list.csv | ForEach {
Get-ADUser -identity $_.user -Properties Name, telephoneNumber |
Select Name, telephoneNumber |
Export-CSV c:\ps\export_ad_list.csv -Append -Encoding UTF8
}
Следующий пример позволяет выгрузить адресную книгу предприятия в виде 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:temp\mail_list.csv
Пользователи, которые не меняли свой пароль в течении последних 90 дней:
$90_Days = (Get-Date).adddays(-90)
Get-ADUser -filter {(passwordlastset -le $90_days)}
Чтобы получить фотографию пользователя из 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
In this post, I’ll show you several examples of the Get-ADComputer PowerShell command. This command is used to search active directory to get single or all computer accounts. I’ll also show you how to use the Get-ADComputer filter option to limit results based on specific computer properties (for example, the name, OU, and modified date).
Let’s get started.
Get-ADComputer Examples
1. Get All AD Computers
get-adcomputer -filter *
This command will get a list of all computers in the domain.

2. Get All Computers with all properties
get-adcomputer -filter * -properties *
This command will get all computers and all of the computer properties (attributes). By default, the get-adcomputer command only displays 8 properties. You must use the -properties * command to list them all.

3. Get All Computers from an OU
Get-ADComputer -Filter * -SearchBase "OU=ADPRO Computers,DC=ad,DC=activedirectorypro,DC=com"
This command will get all computers from a specific OU by using the -SearchBase parameter and the distinguishedName of the OU.

4. Get All Computers and Show Specific Properties
Get-ADComputer -Filter * | select name, Enabled
This command will get all computers and limit the output to display the name and enabled properties only.

5. Get All Enabled Computers
Get-ADComputer -Filter "Enabled -eq 'True'"
This command uses the -filter option to limit the results to only enabled computers.

Get-ADComputer -Filter "Enabled -eq 'True'" | select Name, Enabled
6. Get All Disabled Computers
Get-ADComputer -Filter "Enabled -eq 'false'" | select Name, Enabled
This command filters for enabled computers and limits the output to the name and enabled properties.

7. Get All Computers with a specific Name (Wildcard Search)
Get-ADComputer -Filter "Name -like 'SRV*'" | select Name, Enabled
This command searches for computers that start with srv in the name field.

8. Get All Computers and IP Addresses
Get-ADComputer -Filter * -properties * | select Name, Enabled,ipv4address
This command gets all computers and displays the IP address of each computer.

9. Get All Computers lastlogondate
Get-ADComputer -Filter * -properties * | select name,lastlogondate
This command gets all domain computers and displays the lastlogondate value.

10. Get All Computers Last Modified Date from an OU
Get-ADComputer -Filter * -SearchBase "OU=ADPRO Computers,DC=ad,DC=activedirectorypro,DC=com" -properties *| select name, whenchanged
This command will get all computers from a specific OU and display the computer’s last modified date (whenchanged attribute).

Built-in Active Directory Computer Reports

Download a Free Trial of the AD Pro Toolkit.
{ | |
( | |
[()][] | |
[()][] | |
) | |
{} | |
() { | |
( ) | |
} | |
() { | |
( ) | |
} | |
SearchBase Filter { rightsGuid } Properties rightsGuid | |
System.Collections.ArrayList | |
( ) { | |
[] | |
SearchBase Filter { attributeSecurityGUID } Properties | |
( ) { | |
([]{ | |
([] ).ToString() | |
}) | |
} | |
} | |
} |