How to Export Active Directory Users to CSV and Build Reports
Get a new level of security for your M365 data with immutable backup copies on any object storage. Try the new Veeam Backup for M365 v7.
Table of Contents
For many Active Directory (AD) admins, retrieving users from AD was an entry point to PowerShell. PowerShell is a powerful tool for interrogating systems, and Active Directory is no exception. Searching for and returning AD users with PowerShell is just the beginning. Let’s take that up a notch and export Active Directory users to CSV!
Not a reader? Watch this related video tutorial!”
Are compromised passwords lurking in your Active Directory? Download Specops Password Auditor and scan for password vulnerabilities for FREE!
In this tutorial, you will learn how to perform some basic AD queries with PowerShell and create handy reports. Using PowerShell, you will learn to format output by renaming columns, merging text fields, and performing calculations to develop valuable reports.
Prerequisites
This tutorial will be a hands-on demonstration. If you’d like to follow along, be sure you have the following:
- Logged into an AD-joined computer with a domain user.
- PowerShell – This tutorial uses PowerShell Version 7.1.4, but any version of PowerShell should work.
Getting Comfortable with the Get-ADUser PowerShell Cmdlet
Before creating reports, you must first figure out how to find the AD users you’d like to export Active Directory users to CSV. To do that, you’ll use the Get-ADUser cmdlet. The Get-ADUser cmdlet is a PowerShell cmdlet that comes with the PowerShell ActiveDirectory module.
Open a PowerShell console and run the Get-ADUser cmdlet using the Filter parameter and argument of * . Using an asterisk with the Filter parameter tells Get-ADUser to return all AD users. You’ll create more sophisticated filters a bit later.
The Get-AdUser cmdlet returning all users
By default, the Get-ADUser cmdlet will return the following properties:
- DistinguishedName – The full LDAP name of the user object.
- Enabled – Is the user enabled, true or false.
- GivenName – The user’s first name.
- Name – The user’s full name.
- ObjectClass – The type of AD object this is.
- ObjectGUID – The ID of the AD object.
- SamAccountName – This was the login name up to Windows NT4.0
- SID – Another type of Object ID.
- Surname – The user’s last name.
- UserPrincipalName – The user’s login name.
In your report, you probably don’t need all of these properties. By default, Get-ADUser also returns the built-in domain Administrator and Guest accounts. You almost certainly want to exclude those. You’ll learn how in the following sections.
Limiting Searches to OUs with the SearchBase Parameter
AD users can be spread across sometimes dozens of organizational units (OUs). Sometimes, you need to limit the search to only a particular OU. To do that, you can use the SearchBase parameter. The SearchBase parameter allows you to specify a single OU as a starting point to search for users.
For example, perhaps you have an ATA-Users OU with various department OUs inside, as shown below. Inside the department OUs contains all of the user accounts you’d like to include in your export to CSV.

Example AD OU structure
You can define the SearchBase argument as ATA-Users OU’s distinguished name (DN) like below to limit the search to the ATA-Users OU and all OUs inside.

Get-AdUser Unfiltered Searchbase
The output above displays many different properties for each user, but let’s limit that down a bit only to show the properties you might be interested in. To do this, use the Select-Object cmdlet only to return the Name and UserPrincipalName properties.

Get-ADUser Searchbase2
Perhaps you’d like to only export Active Directory users to CSV in the Sales OU. To do that, specify the Sales OU in the SearchBase parameter like below.

Get-ADUser Unfiltered Searchbase3
Filtering AD User Accounts from Get-ADUser
Up to this point, you have ignored the Filter parameter by simply specifying an asterisk to return all users. But if you need to query only certain users matching specific criteria, the Filter parameter is your friend.
Let’s say you’d like to eventually export all Active Directory users to a CSV inside of the ATA-Users OU, but only if they have their Department AD attribute set to Sales like the example user account below.

An AD user account with Sales as a Department attribute
Using the Filter parameter on Get-ADUser , specify the AD attribute ( Department ), the operator -eq equating to “equal to” and the value of the Department attribute ( Sales ).
If you have users inside the ATA-Users OU with the Department attribute set to Sales , Get-ADUser will only return those users.

Get-ADUser only returning Sales users
Maybe you’d like to include the Department attribute in the output. To do that, you’d typically specify the Department property as another property to show via the Select-Object ( select ) cmdlet, as shown below. But notice the Department property doesn’t show up.

Including Department Attribute
By default, the Get-ADUser cmdlet does not return all properties. To return all non-default properties, you must use the Properties parameter. In this case, tell Get-ADUser to return the Department property.
Now that you have a basic filter, you can continue to add more criteria to the Filter as necessary, combining them with the PowerShell and and or operators. Below, for example, Get-ADUser will return all AD users that are enabled that are either in the Sales or Finance departments.

Adding Criteria to the Filter
In the tutorial’s environment, Steve James is an account in the Sales department, but his account is not enabled, so his account will not show up via the command above.

Account not Enabled
Exporting Active Directory Users to CSV
You now have the foundational knowledge to retrieve AD users with PowerShell. The final step is to export those Active Directory users to a CSV file to create a report you can share.
Let’s say you’ve built your Get-ADUser command, and it’s returning the users you’d like to include in your CSV report like below.
- Retrieves all AD users in the ATA-Users OU and all child OUs.
- Outputs extra properties like Department , PasswordLastSet , and PasswordNeverExpires .
- Limits the properties returned via Select-Object to include in the report like Name , UserPrincipalName , Department , and any property that begins with Password .
Notice password* in this example. Using an asterisk with Select-Object tells Select-Object to return all properties that start with password .
To export the Active Directory users, this command returns to CSV, pipe the objects to the Export-Csv cmdlet. The Export-Csv cmdlet is a PowerShell cmdlet that allows you to send various objects to (AD user accounts in this example) and then append those objects as CSV rows.
To export each AD user returned in the command above, append | Export-Csv <csv file name>.csv to the end. This action pipes all of the objects that Select-Object returns and “converts” them into a CSV file.
You’ll see below that Export-Csv creates a CSV file called pass_report.csv that includes headers as object property names and one row per AD user account.

Example output from Export-CSV
Customizing CSV Headers with Select-Object
The report you can now generate contains all the required information, but the CSV headers are not grammatically correct and can be misleading. A manager may not know what a UserPrincipalName is, and having column headings with multiple words without spaces is good English.
To export the Active Directory users to CSV and create custom CSV headers, use the Select-Object cmdlet’s calculated properties. The calculated properties feature is a way you can define custom property names and values.
The Select-Object cmdlet’s calculated properties feature requires you to define a hashtable with two key/value pairs; Name to indicate the name of the property and Expression to represent the code to manipulate the original object property value or simply the actual property name.
In this example, let’s say you’d like the CSV to show a header name of:
- Login Name instead of UserPrincipalName
- Password Last Set Date instead of PasswordLastSet
- Password Never Expires instead of PasswordNeverExpires
- Password Last Set Date instead of PasswordLastSet that’s represented with a short date.
To make these changes, you’d first build a hashtable for each property like below.
Now that you have the hashtables add them to the list of properties you provide to the Select-Object cmdlet just like you would a typical property name.
The Select-Object cmdlet’s Property parameter accepts an array. If you have many properties to pass, you can create an array first and then pass that array to the Property parameter for easier readability.
A FREE read only tool that scans your AD and generates multiple interactive reports for you to measure the effectiveness of your password policies against a brute-force attack. Download Specops Password Auditor now!.
Combining Get-ADUser with the new Select-Object construct created above gives you the below code snippet.
Once complete, PowerShell will create a CSV file for you that looks like the example below.

CSV export of AD users using calculated properties
Conclusion
PowerShell is a powerful tool for reporting on Active Directory Users. This tutorial showed you how to find and filter users based on various criteria and create a CSV file from that output using just a few lines of code.
Now that you have the foundational knowledge to query AD users and export Active Directory users to CSV, where do you see yourself using this knowledge in your daily work life?
Hate ads? Want to support the writer? Get many of our tutorials packaged as an ATA Guidebook.
More from ATA Learning & Partners
Recommended Resources!
Recommended Resources for Training, Information Security, Automation, and more!
Get Paid to Write!
ATA Learning is always seeking instructors of all experience levels. Regardless if you’re a junior admin or system architect, you have something to share. Why not write on a platform with an existing audience and share your knowledge with the world?
ATA Learning Guidebooks
ATA Learning is known for its high-quality written tutorials in the form of blog posts. Support ATA Learning with ATA Guidebook PDF eBooks available offline and with no ads!
Скрипты выгрузки всех пользователей из MS Active Directory (ITGC)
Одной из стандартных процедур проведения аудита ITGC для каталога Active Directory является получение выгрузки всех пользователей домена. На основании полученных данных далее формируются процедуры тестирования, к примеру изучение списка администраторов или выявление пользователей с истекшим паролем. Наиболее эффективным для формирования такой выгрузки будет использование стандартного интерфейса PowerShell , примеры которого мы и рассмотрим в данной статье
Ниже представлен скрипт PowerShell, как один из наиболее простых и быстрых способов получить список всех пользователей домена AD в формате CSV, который без проблем открывается тем же Excel’ем.
Get-ADUser -filter * -properties PasswordExpired, PasswordLastSet, PasswordNeverExpires | where <$_.name –like “*Dmitry*”>| sort-object PasswordLastSet | select-object Name, PasswordExpired, PasswordLastSet, PasswordNeverExpires | Export-csv -path c:tempuser-password-expires-2015.csv
$_.name>
Excel вместо PowerShell: запросы к AD и системные отчеты «на коленке»

В комментариях к предыдущей статье вспомнили про учет в Excel вместо 1С. Что ж, проверим, насколько вы знаете Excel. Сегодня я покажу, как получать данные из Active Directory и работать с ними без макросов и PowerShell — только штатными механизмами Office. Например, можно запросто получить аналитику по использованию операционных систем в организации, если у вас еще нет чего-либо вроде Microsoft SCOM. Ну, или просто размяться и отвлечься от скриптов.
Для работы с данными я буду использовать механизм Power Query. Для офиса 2010 и 2013 придется устанавливать плагин, в Microsoft Office 2016 этот модуль уже встроен. К сожалению, стандартной редакции нам не хватит, понадобится Professional.
Сам механизм предназначен для получения и обработки данных из самых разных источников ― от старого ODBC и текстовых файлов, до Exchange, Oracle и Facebook. Подробнее о механизме и встроенном скриптовом языке «M» уже писали на Хабре, я же разберу пару примеров использования Power Query для получения данных из Active Directory.
Разминка: посмотрим, когда наши пользователи логинились
Сам запрос к базе домена создается на вкладке «Данные ― Новый запрос ― Из других источников ― Из Active Directory».
Указываем источник данных.
Понадобится выбрать название домена, указать необходимые данные для подключения. Далее выберем тип объектов, в этом примере ― user. Справа в окне предпросмотра запрос уже выполняется, показывая предварительный вид данных.
Подготавливаем запрос, любуемся предпросмотром.
Предварительно запрос стоит подготовить, нажав кнопку «изменить» и выбрав нужные колонки. По сути эти колонки ― это классы Каждый из них содержит набор определенных атрибутов объекта Active Directory, кроме основной колонки displayName, которая сама является атрибутом. Я остановлюсь на классах user, person, top и securityPrincipal. Теперь необходимо выбрать нужные атрибуты из каждого класса с помощью «расширения» ― значок с двумя стрелочками у заголовка колонки:
- класс user расширим, выбрав lastLogonTimestamp и userAccountControl;
- в person выберем telephoneNumber;
- в top ― whenCreated;
- и в securityPrincipal ― SamAccountName.
Расширяем запрос.
Теперь настроим фильтр: в частности, чтобы не получить заблокированные аккаунты, нужно чтобы атрибут userAccountControl имел значение 512 или 66048. Фильтр может быть другой в вашем окружении. Подробнее про атрибут можно прочитать в документации Microsoft.
Применяем фильтр.
Теперь столбец userAccountControl стоит удалить ― в отображении он не нужен совершенно. И нажимаем «Загрузить и закрыть».
Получилась табличка, которую осталось совсем немного довести до ума. Например, переименовать столбцы в что-то удобочитаемое. И настроить автоматическое обновление данных.
Автоматическое обновление при открытии таблицы или по таймауту настраивается во вкладке «Данные» в «Свойствах».

Настройка обновления данных.
После того, как настройка обновления будет завершена, можно смело отдавать таблицу сотрудникам отдела персонала или службе безопасности ― пусть знают, кто и когда входил в систему.
Создаем адресную книгу, или что делать, когда корпоративный портал с AD не дружит
Другой вариант использования Excel в связке с Active Directory ― это формирование адресной книги, исходя из данных AD. Понятно, что адресная книга получится актуальной, только если в домене порядок.
Создадим запрос по объекту user, развернем класс user в mail, а класс person в telephoneNumber. Удалим все столбцы, кроме distinguishedName ― структура домена повторяет структуру предприятия, поэтому названия Organizational Units соответствуют названиям подразделений. Аналогично в качестве основы названий подразделений можно использовать и группы безопасности.
Теперь из строки CN=Имя Пользователя, OU=Отдел Бухгалтерии, OU=Подразделения, DC=domain, DC=ru нужно извлечь непосредственно название отдела. Проще всего это сделать с использованием разделителей на вкладке «Преобразование».
Извлекаем текст.
В качестве разделителей я использую OU= и ,OU=. В принципе, достаточно и запятой, но я перестраховываюсь.
Вводим разделители.
Теперь с помощью фильтра можно отсечь ненужные OU, вроде заблокированных пользователей и Builtin, настроить сортировку и загрузить данные в таблицу.
Вид итоговой таблицы.
Быстрый отчет по составу рабочих станций, без внедрения агентов и прочей подготовки
Теперь попробуем создать полезную таблицу, получив данные по компьютерам. Сделаем отчет по используемым компанией операционным системам: для этого создадим запрос, но в навигаторе на этот раз выберем computer.
Делаем запрос по объекту computer.
Оставим классы-колонки computer и top и расширим их:
- класс computer расширим, выбрав cn, operatingSystem, operatingSystemServicePack и operatingSystemVersion;
- в классе top выберем whenCreated.
Расширенный запрос.
При желании можно сделать отчет только по серверным операционным системам. Например, применить фильтр по атрибуту operatingSystem или operatingSystemVersion. Я не буду этого делать, но поправлю отображение времени создания ― мне интересен только год. Для этого на вкладке «Преобразование» выберем нужную нам колонку и в меню «Дата» выберем «Год».
Извлекаем год из времени ввода компьютера в домен.
Теперь останется удалить столбец displayname за ненадобностью и загрузить результат. Данные готовы. Теперь можно работать с ними, как с обычной таблицей. Для начала сделаем сводную таблицу на вкладке «Вставка» ― «Сводная таблица». Согласимся с выбором источника данных и настроим ее поля.
Настройки полей сводной таблицы.
Теперь остается настроить по вкусу дизайн и любоваться итогом:
/>
Сводная таблица по компьютерам в AD.
При желании можно добавить сводный график, также на вкладке «Вставка». В «Категории» (или в «Ряды», по вкусу) добавим operatingSystem, в данные ― cn. На вкладке «Конструктор» можно выбрать тип диаграммы по душе, я предпочел круговую.
Круговая диаграмма.
Теперь наглядно видно, что, несмотря на идущее обновление, общее количество рабочих станций с Windows XP и серверов с Windows 2003 довольно велико. И есть к чему стремиться.
Но и это еще не все
Надо отметить, что Excel умеет составлять не только любимые бухгалтерией таблички. При умелом подходе ему по плечу и аналитика многомерных данных (OLAP-кубы), и решение системы уравнений с помощью матриц. А для тех, у кого на стенке пылится сертификат от Microsoft – есть вариант заморочиться даже с 3D-играми. Не Doom конечно, но вечер точно займет.
А что вы думаете про Excel как инструмент администратора? Доводилось использовать что-то из описанного?
Export AD Users to CSV with PowerShell

In this tutorial, you will learn how to export Active Directory users to CSV with PowerShell.
I’ll also show you how to export users from an OU, and get specific user attributes like last logon, email addresses, state, city, and so on.
To run the commands from this guide you need to make sure PowerShell is up to date and you have the RSAT tools installed. For this demo, I’m using a Windows 10 computer and using PowerShell version 5.1. You can check your version with this command.
How to Export Active Directory Users to CSV
Here are the steps to export Active Directory users to CSV.
Step 1: Get-ADUser PowerShell Command
To export users with PowerShell, the Get-ADUser cmdlet is used. This command will get user accounts from Active Directory and display all or selected attributes. It’s important to know how this command works so you can export the data you need.
The most important thing to remember is how to display all the user attributes. This will come in useful when you want to export only specific account details.
The below command will get all user attributes for a single user.
Change the “username” to a user in your domain.
Pay attention to the left column. These are the user attribute names and the values on the right. In example 4, I’ll show you how to select specific attributes to include in the export.

Step 2: Export to CSV command
Add “export-CSV -path” to the end of the command to export to a CSV file. See the below example, I’m exporting all the properties for this user to c:\temp\export.csv.

You should now have a CSV export of all user properties for a single user.
Step 3: Export specific user attributes
If you don’t want to export all user attributes then use the “select-object” command and enter only the attributes you need. If you have followed along from the beginning then you know how to find the attribute names, if not then jump to example 2.
In the below example I’ll export the DisplayName, City and State.
Step 4: How to export all users
To export all users remove (-identity) and add (-filter *) to the command. In the below example I’m exporting all users and selecting displayname, city, company, department, EmailAddress, and telephonenumber.
Here is what this looks like in Powershell.

Here is the CSV.

Step 5: Export Users from a specific OU

To export users from specific OUs use the “-SearchBase” command and the “distinguishedName” value of the OU.
In the below example I’m getting all the users in my accounting OU.
Here is the PowerShell output.

Then add export-csv -path to the end to export this to CSV.
At this point, you should be able to export single, all users, or users from a specific OU. I also showed you how to export all or specific user attributes.
Below are a few more PowerShell examples.
Export only enabled users
To get just the enabled user accounts you need to add a filter that searches for enabled = true.
Export users to CSV with last logon date
Export Users With the GUI AD Export Tool
If you need advanced exports such as adding additional user properties or users group membership then check out the examples below of the AD User Export Tool.
Export User information to CSV using AD Pro Toolkit
You can download a free trial of the AD User Export Tool by clicking the button below.
Step 1: Open the AD User Export Tool
Once you have the AD Pro toolkit installed click on “User Export”
Step 2: Choose Path to Export
In the search criteria box pick where you want to export from, you can pick the following:
- Entire Domain – This will export all users in your domain
- Select OU or Group – This allows you to select one or multiple OUs or groups to export.
In this example, I’m going to export all users from two security groups “Management_folders” and Management_Printers”.

Step 3: Pick AD User Fields to include in the Export
The attribute picker has over 50 attributes you can easily add or remove to the export.

For this example, I’m going to leave the default fields selected. You can always remove unwanted fields after exporting by deleting the columns in the CSV file.
Step 4: Click the Run button to preview the export

The last step is to click the export button and select the export file type.
You will be prompted to save the file. Give the file a name and save it to your computer.
Here is an example export.
Include Users Group Membership in the CSV
One nice feature of the GUI tool is it will include the user’s group membership. Below is an example from my export. So for each user, it will show you which security groups they are a member of. Of course, you can just uncheck “memberOf” in the columns picker if you don’t want to see this info.
The graphical user export tool makes it easy for anyone to export user information to CSV. If you don’t want to mess with complicated PowerShell scripts then I recommend checking it out.
Export Users with Active Directory Users and Computers
This method uses the Active Directory Users and Computers console to export users. If you need a very basic export with limited user fields then this option is for you. The one problem is it is limited to a single folder.
Step 1: Open Active Directory Users and Computers
Step 2: Browse to the container that has the users you want to export.
In my test environment, I’ll be exporting the users from the HR container.

Step 3: Click the export button

Now just browse to where you want to save the file, name it and change save as type to CSV.
I’ll open the CSV file in excel to verify it was exported.

How Do You Export all Users to CSV?
The problem with exporting users from ADUC (Active Directory Users and Computers Console)is that it only exports users from a specific folder. If you have users organized into many different folders, you would have to export from each one of them.
To Export all Users you have two options.
- User Export GUI Tool
- PowerShell
Using the GUI tool you just select “Entire Domain” and click run.
With PowerShell, the below command will export all users to CSV. This will just export the user’s name, you will need to add additional attributes as needed.
Summary
I just showed you 3 options for exporting Active Directory users to CSV. I recommend you try them all out and see which option is best for you. The built-in Microsoft console has the fewest options but if you just need a simple export then it works ok.
PowerShell can be a great option for exporting user accounts but it can be complex and challenging at times for quick solutions. If you are not into PowerShell and need an option to export from groups, OUs, and to select which fields to export then the AD User Export Tool is a great choice.
Recommended Tool: Permissions Analyzer for Active Directory
This FREE tool lets you get instant visibility into user and group permissions and allows you to quickly check user or group permissions for files, network, and folder shares.
You can analyze user permissions based on an individual user or group membership.