June 6, 2020

PowerShell :: output email addresses from Active Directory

PowerShell ISE logo
(Last Updated On: 16th September 2016)

Hopefully you’ve landed here from my series on macro malware and you need to output a list of all you users email addresses to send them some dummy phishing emails for educational purposes.  If not and you need to output a list of all your email addresses in Active Directory then you’re still in the right place!

This code needs to run on a Domain Controller and it is pre-configured to output in a format that PowerShell can take as an array for my macro malware sending script.  This can be changed though as there is a definable $prefix, $suffix and $suffixForAllButLast.  The idea here is that you can put a string before the email address ($prefix), after the email address ($suffix) and after the suffix on all but the last email address ($suffixForAllButTheLast).  If you look at this example list of two emails it will make a little sense.

[email protected]”,”[email protected]

$outputFilePath = "C:\Temp\Emails.txt"
$prefix = '"'
$suffix = '"'
$suffixForAllButLast = ","

$outputContent = ""
Out-File -FilePath $outputFilePath -InputObject "" -ErrorAction Stop

Import-Module ActiveDirectory
ForEach ($userAccount in (Get-ADGroupMember "Global Email Users" | Get-ADUser -Properties mail ))
if ($userAccount.mail) {$outputContent += ($prefix + $userAccount.mail + $suffix + $suffixForAllButLast)}

Write-Output $outputContent.TrimEnd($suffixForAllButLast) > $outputFilePath

TIP: If you need them on different lines then simply drop the ” from $suffixForAllButLast onto the next line in the PowerShell code like below.

$suffixForAllButLast = ",


Previous «
Next »

Simon is a sysadmin for a global financial organisation and specialises in Windows, security and automation.

Leave a Reply

Subscribe to SYNACK via Email

%d bloggers like this: