TSF – Giải pháp IT toàn diện cho doanh nghiệp SMB | HCM

P11 - Export Active Directory Users to CSV for Reporting

📘 WinServer2025 – P11: How to Export Active Directory Users to CSV for Reporting

In enterprise IT environments, Active Directory (AD) is the central identity system that manages users, computers, and access control. As organizations grow, administrators frequently need accurate user reports for operational, security, and compliance purposes.

Manually reviewing users in Active Directory Users and Computers is inefficient, time-consuming, and not scalable. That is why exporting Active Directory users to CSV using PowerShell is considered the professional and standardized approach.

In Part 11 of the Windows Server 2025 series, this tutorial demonstrates multiple real-world methods to export Active Directory users to CSV, using PowerShell scripts commonly applied in enterprise environments.


📊 Why Export Active Directory Users?

Exporting AD users is essential for many operational scenarios:

📋 HR onboarding and offboarding processes
🔍 Security audits and access reviews
📊 Compliance and inventory reporting
🧾 Management and department reviews

CSV-based reports allow administrators to quickly analyze user data using Excel, LibreOffice, Power BI, or other reporting tools.

👉 Export Active Directory Users is a must-have skill for system administrators working in enterprise environments.


🧠 What Can Be Included in an AD User Report?

When exporting users from Active Directory, PowerShell allows you to collect valuable attributes such as:

👤 Username (SamAccountName)
📧 Email address
🧑 Full display name
🏢 Organizational Unit (OU)
🔐 Account status (Enabled / Disabled)
📅 Last logon time
🆔 Employee ID

CSV format provides flexibility for reporting, auditing, and automation workflows.


🧰 Tools Used in This Demo

The following tools are used throughout this tutorial:

🖥️ Windows Server 2025
🧑‍💼 Active Directory Domain Services (AD DS)
⚙️ PowerShell
📄 CSV file format

All scripts shown are suitable for production use with proper testing.


🔧 Step-by-Step: Export Active Directory Users to CSV

📌 Step 1: Open PowerShell

Run PowerShell using an account that has permission to read Active Directory user objects.
In this demo, the user account is:

👤 User: it02
🔐 Group: Member of Domain Admins


📌 Step 2: Export Members of a Group

Export all users who are members of a specific AD group.

 
Get-ADGroupMember Identity “Company” |
Select Name, SamAccountName, DistinguishedName |
Export-Csv Path C:\Users\it02\Desktop\MemberOfGroup.csv NoTypeInformation
 

📌 Use case:

  • Group membership audits

  • Access reviews

  • Department-based reporting


📌 Step 3: Export All Active Users with Last Logon Time

This function collects accurate last logon data by querying all Domain Controllers.

💻
filename.bash
Import-Module ActiveDirectory

function Get-ADUsersLastLogon {
    $dcs = Get-ADDomainController -Filter *
    $users = Get-ADUser -Filter 'Enabled -eq $true' -Properties DistinguishedName

    foreach ($user in $users) {
        $time = 0

        foreach ($dc in $dcs) {
            $currentUser = Get-ADUser $user.SamAccountName -Server $dc.HostName `
                -Properties lastLogon, lastLogonTimestamp

            if ($currentUser.lastLogon -gt $time) {
                $time = $currentUser.lastLogon
            }
            if ($currentUser.lastLogonTimestamp -gt $time) {
                $time = $currentUser.lastLogonTimestamp
            }
        }

        [PSCustomObject]@{
            Name           = $user.Name
            SamAccountName = $user.SamAccountName
            LastLogon      = ([DateTime]::FromFileTime($time)).ToString("yyyy-MM-dd HH:mm")
            OU             = $user.DistinguishedName
        }
    }
}

Get-ADUsersLastLogon |
Export-Csv -Path C:\Users\it02\Desktop\users.csv -NoTypeInformation -Encoding UTF8

📌 Use case:

  • User activity tracking

  • Security reviews

  • Inactive account detection


📌 Step 4: Export Detailed LastLogonDate Information

This script aggregates LastLogon, LogonCount, Password Last Set, and more.

💻
filename.bash
Import-Module ActiveDirectory

$properties = ("Name", "SamAccountName", "lastLogon", "createTimeStamp", "logonCount", "pwdLastSet", "employeeID", "accountExpires", "distinguishedName")
$users = @{}

foreach ($hostname in (Get-ADDomainController -Filter { IsReadOnly -eq $false }).HostName) {
    foreach ($user in (Get-ADUser -Server $hostname -Filter 'enabled -eq $true' -Properties $properties | Select-Object $properties)) {
        if ($users.Item($user.SamAccountName)) {
            if ($user.lastLogon -gt $users.Item($user.SamAccountName).lastLogon) {
                $users.Item($user.SamAccountName).lastLogon = $user.lastLogon
            }
            $users.Item($user.SamAccountName).logonCount += $user.logonCount
        }
        else {
            $users.Add($user.SamAccountName, $user)
        }
    }
}

$hostname = (Get-ADDomainController -Discover -NextClosestSite).HostName
foreach ($user in $users.Values) {
    if ($user.lastLogon) { $user.lastLogon = [DateTime]::FromFileTime($user.lastLogon) }
    if ($user.pwdLastSet) { $user.pwdLastSet = [DateTime]::FromFileTime($user.pwdLastSet) }
    if ($user.accountExpires -eq "9223372036854775807" -or $user.accountExpires -eq "0") {
        $user.accountExpires = "never expires"
    }
    else {
        $user.accountExpires = [DateTime]::FromFileTime($user.accountExpires)
    }
}

$users.Values |
Export-Csv -Path C:\users\bao.tran\desktop\UserLastLogonDate.csv -NoTypeInformation -Encoding UTF8

📌 Step 5: Export Users Who Have Not Logged In for X Days (Sub OU)

💻
filename.bash
Import-Module ActiveDirectory

$DaysInactive = 10
$Time = (Get-Date).AddDays(-$DaysInactive)

Get-ADUser -Filter { LastLogonTimeStamp -lt $Time -and enabled -eq $true } `
-SearchBase "OU=BRO-HCM,OU=Users,OU=XYZ.LOCAL,DC=xyz,DC=local" `
-Properties * |
Select Name, SamAccountName, DistinguishedName, LastLogonDate |
Export-Csv "C:\users\bao.tran\desktop\usernologon10day.csv" -Encoding UTF8 -NoTypeInformation

📌 Use case:

  • Inactive user cleanup

  • Security hardening

  • Audit preparation


🔐 Best Practices for Active Directory Reporting

🛡️ Use read-only accounts when possible
📁 Store CSV reports securely
📏 Export only required attributes
🕒 Schedule recurring exports if needed

“Accurate AD reporting improves security, visibility, and operational control.”


🔥 Why This Matters in Enterprise IT

Active Directory is the identity backbone of most organizations.
Accurate and up-to-date user reports are critical for:

✔️ Security
✔️ Compliance
✔️ Operational efficiency

Being able to export Active Directory users to CSV using PowerShell is a core skill for every system administrator.


🧩 Final Thoughts

Mastering how to Export Active Directory Users using PowerShell gives administrators deep visibility into their environment while enabling automation, auditing, and compliance.

By following this tutorial, you gain production-ready scripts that can be reused across audits, reporting workflows, and enterprise operations on Windows Server 2025.

If you found this guide helpful, don’t forget to like, share, and subscribe for more real-world Windows Server and Active Directory tutorials 🚀

See also related articles

P19 – Safely Demote Domain Controller: Critical FSMO Guide

P19 – Safely Demote Domain Controller: Critical FSMO Guide https://youtu.be/vLgyzgmxzPI WinServer 2025 – P19 Demote Domain Controller Holding All FSMO Roles Demoting Domain Controller holding all FSMO roles is a critical operation in any Active Directory infrastructure. If done incorrectly, it can break authentication, replication, and domain services across the...

Read More

P18 – Critical Fix Guide Delete ADC Died Server 2025

P18 – Critical Fix Guide Delete ADC Died Server 2025 https://youtu.be/82fvirmHZ2k WinServer2025 – P18 Critical Fix Remove Dead ADC from Active Directory (Server 2025) When an Additional Domain Controller (ADC) fails permanently, leaving it inside Active Directory can cause serious long-term issues. Replication errors, DNS conflicts, GC problems, and even...

Read More

P17 – Critical Guide Delete PDC Died in Server 2025

P17 – Critical Guide Delete PDC Died in Server 2025 https://youtu.be/ipF1EziL_C8 WinServer2025 – P17 How to Remove a Failed Domain Controller in Windows Server 2025 When a Primary Domain Controller (PDC) fails permanently and cannot be brought back online, simply shutting it down is not enough. The failed controller still...

Read More