Active Directory – Exporting all User email addresses

Business Development, PR, Customer Relations, whatever the department happens to be called in your organisation, the time will come when you will get a request for all of the email addresses in your organisation. No idea why, people just love lists of data.

Here is a nice and simple Powershell script that does exactly that, it has saved me a huge amount of time on more than one occassion:

#Export all email addresses
Import-Module ActiveDirectory
Get-ADuser -Filter * -Property Name, Office, mail |
? {$_.Enabled -eq $True} |
Export-CSV c:\temp\email_addresses.csv

OK, the code is relatively simple, but let’s break it down into the individual parts.

#Export all email addresses

This for me is an essential port of any of the code that I put together, it is the comment. It is not executed by Powershell, but it is a useful tool to remind yourself what the piece of code does.

Import-Module ActiveDirectory

None of the subsequent lines of code will work without this. This line tells Powershell to make the Active Directory cmdlets available to the current Powershell session. This line will error if the Remote Server Administration Tools are not installed.

Get-ADuser -Filter * -Property Name, Office, mail |
? {$_.Enabled -eq $True} |

It is here that we are making the real query and filtering out what we need. The second line tests if the account is enabled as I am only interested in accounts that are in use. It is possible to filter against any of the attributes an object has in Active Directory, for example the samaccountname could be used to filter out real users accounts from other account types if there is a length or naming convention in place.

Export-CSV c:\temp\email_addresses.csv

The data outputting to the screen is only of so much use, so the final part of the script uses the Export-CSV cmdlet to send the output to a csv file for ease of reference.