PowerShell Script to Export AD Users to CSV File
Get-ADUser -Filter * -Properties EmailAddress | Select-Object Name,SamAccountName,EmailAddress | Export-Csv -Path 'users.csv' -NoTypeInformation to export all AD users with selected properties to a CSV file.Examples
How to Think About It
Get-ADUser. Then select the user properties you want to save. Finally, export the selected data to a CSV file using Export-Csv.Algorithm
Code
Import-Module ActiveDirectory Get-ADUser -Filter * -Properties EmailAddress | Select-Object Name,SamAccountName,EmailAddress | Export-Csv -Path 'users.csv' -NoTypeInformation Write-Output "Export completed: users.csv"
Dry Run
Let's trace exporting all AD users with Name and EmailAddress to CSV
Get all AD users
Get-ADUser -Filter * -Properties EmailAddress returns a list of user objects with many properties including EmailAddress
Select properties
Select-Object Name,SamAccountName,EmailAddress extracts only these fields
Export to CSV
Export-Csv writes the selected data to 'users.csv' without type info
| Name | SamAccountName | EmailAddress |
|---|---|---|
| Alice Johnson | ajohnson | alice.johnson@example.com |
| Bob Smith | bsmith | bob.smith@example.com |
Why This Works
Step 1: Get-ADUser fetches users
The Get-ADUser cmdlet retrieves user accounts from Active Directory based on the filter.
Step 2: Select-Object picks fields
Using Select-Object lets you choose which user properties to include in the output.
Step 3: Export-Csv saves data
The Export-Csv cmdlet writes the selected user data into a CSV file for easy use.
Alternative Approaches
Get-ADUser -Filter * -Properties * | Export-Csv -Path 'all_users.csv' -NoTypeInformation Write-Output "Export completed: all_users.csv"
Get-ADUser -Filter {Department -eq 'Sales'} -Properties EmailAddress | Select-Object Name,EmailAddress | Export-Csv -Path 'sales_users.csv' -NoTypeInformation
Write-Output "Export completed: sales_users.csv"Get-ADUser -LDAPFilter '(objectClass=user)' -Properties EmailAddress | Select-Object Name,EmailAddress | Export-Csv -Path 'ldap_users.csv' -NoTypeInformation Write-Output "Export completed: ldap_users.csv"
Complexity: O(n) time, O(n) space
Time Complexity
The script processes each user once, so time grows linearly with the number of users.
Space Complexity
Memory usage grows with the number of users because all selected user data is stored before exporting.
Which Approach is Fastest?
Filtering users before selecting properties reduces data size and speeds up export compared to exporting all properties.
| Approach | Time | Space | Best For |
|---|---|---|---|
| Select specific properties | O(n) | O(n) | Balanced speed and file size |
| Export all properties | O(n) | O(n) | Complete data but slower and large files |
| Filter users by attribute | O(m) where m ≤ n | O(m) | Targeted exports with fewer users |
-NoTypeInformation with Export-Csv to avoid extra type info in your CSV file.