Как составить все компьютеры в организационной подразделении

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
The basics of Get-ADComputer to find all computer objects
The basics of Get-ADComputer to find all computer objects (Image Credit: Petri/Michael Reinders)

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"
Using -Searchbase to find computers in a specific OU or container
Using -Searchbase to find computers in a specific OU or container (Image Credit: Petri/Michael Reinders)

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
We can also find all objects in the Computers container
We can also find all objects in the Computers container (Image Credit: Petri/Michael Reinders)

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
We can use the Get-AdComputer -Properties parameter to output non-default attributes for our computers
We can use the Get-AdComputer -Properties parameter to output non-default attributes for our computers (Image Credit: Petri/Michael Reinders)

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*"}
We can utilize the Get-AdComputer -Filter parameter to find specific computers starting with 'WS19....'
We can utilize the Get-AdComputer -Filter parameter to find specific computers starting with ‘WS19….’ (Image Credit: Petri/Michael Reinders)

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
We are using Sort-Object to alphabetically display our computers
We are using Sort-Object to alphabetically display our computers (Image Credit: Petri/Michael Reinders)

Let’s sort them by the operating system.

Get-ADComputer -Filter * -Properties OperatingSystem | Sort-Object OperatingSystem -Descending | ft
Here we are sorting by the operating system of each computer as reported in Active Directory
Here we are sorting by the operating system of each computer as reported in Active Directory (Image Credit: Petri/Michael Reinders)

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.

Here's our Get-AdComputer CSV output in Microsoft Excel
Here’s our Get-AdComputer CSV output in Microsoft Excel (Image Credit: Petri/Michael Reinders)

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
Finding all inactive computers that haven't 'checked in' in > 90 days using PowerShell Get-AdComputer” data-lazy-srcset=”https://petri.com/wp-content/uploads/2023/10/Screenshot-2023-10-06-093001-1024×597.png 1024w, https://petri.com/wp-content/uploads/2023/10/Screenshot-2023-10-06-093001-300×175.png 300w, https://petri.com/wp-content/uploads/2023/10/Screenshot-2023-10-06-093001-768×448.png 768w, https://petri.com/wp-content/uploads/2023/10/Screenshot-2023-10-06-093001-610×356.png 610w, https://petri.com/wp-content/uploads/2023/10/Screenshot-2023-10-06-093001.png 1285w” data-lazy-sizes=”(max-width: 1024px) 100vw, 1024px”> </picture><figcaption>Finding all inactive computers that haven’t ‘checked in’ in > 90 days using PowerShell Get-AdComputer (Image Credit: Petri/Michael Reinders)</figcaption></figure><p>Nice. This is the coolest thing. We get a listing of computer objects that haven’t logged into Active Directory in over 90 days using the date variable. We utilize the LastLogonDate and find objects ‘lt’ (less than) 90 days prior.</p><h3><span id=Using the Select-Object parameter

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
Using the Select-Object PowerShell parameter to grab more attributes than the standard returned
Using the Select-Object PowerShell parameter to grab more attributes than the standard returned (Image Credit: Petri/Michael Reinders)

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�
Here we see all of our computers running a 'Server' variant of Windows (SKU)
Here we see all of our computers running a ‘Server’ variant of Windows (SKU) – (Image Credit: Petri/Michael Reinders)

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
Our final output is showing output from a specific domain controller (DC) in our domain
Our final output is showing output from a specific domain controller (DC) in our domain (Image Credit: Petri/Michael Reinders)

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.

:/>  Убираем сообщение Вам понадобится новое приложение, чтобы открыть этот ms-gamingoverlay

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 подключен по-умолчанию.

RSAT включить модуль Active Directory Module for Windows PowerShell

help Get-ADUser

Чтобы вывести список всех учетных записей домена, выполним команду:

Get-ADUser -filter *

Важно. Не рекомендуется выполнять эту команду в доменах с большим количеством аккаунтов, т.к. возможно перегрузка контроллера домена, предоставляющего данные.

Get-ADUser -filter * - вывести список всех пользователей в ADФормат возвращаемого списка не очень удобен для использования, выводится только некоторые основные 10 из более 120 атрибутов и свойств учетных записей пользователей (DN, SamAccountName, Name, SID, UPN и т.д) кроме того, мы видим, что информация о времени последней смены пароля отсутствует.

Get-ADUser -identity tuser -properties *
  • PasswordExpired
  • PasswordLastSet
  • PasswordNeverExpires
Get-ADUser tuser -properties PasswordExpired, PasswordLastSet, PasswordNeverExpires

Get-ADUse - время смены и истечения срока действия пароля в ADТеперь в данных пользователя есть информация о дате смены пароля и времени, когда срок пароля истечет. Представим информацию в более удобном табличном виде:

Get-ADUser -filter * -properties PasswordExpired, PasswordLastSet, PasswordNeverExpires | ft Name, PasswordExpired, PasswordLastSet, PasswordNeverExpires

Get-ADUser - табличное преставление о свойствах пользователейЧтобы вывести данные пользователей из определенной 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

Get-ADUser с условием where и сохранением в 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).

:/>  Как перемещаться по каталогам в cmd

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.

get all computer accounts

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.

get all computers and all properties

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.

get all computers from 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.

get all computers status

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 all 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.

get all disabled computers

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.

filter computers by name

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.

get all computers and ip address

9. Get All Computers lastlogondate

Get-ADComputer -Filter * -properties * | select name,lastlogondate

This command gets all domain computers and displays the lastlogondate value.

get all computers lastlogondate

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).

all computers from an ou and modified date

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()
})
}
}
}

Оставьте комментарий