Export UPN and Email Addresses of Microsoft 365 Users using PowerShell

In this blog, we will explore how to export all Microsoft Office 365 Users to a CSV file using PowerShell. The exported report includes the properties of users such as the user’s UserPrincipalName (UPN), Primary SMTP Email address, Alias Email Addresses / Proxy Email Addresses, Object Id (User Id), and more. 

We can use the Get-AzureADUser cmdlet from the Azure AD PowerShell module to get user details. In Azure AD, the Primary SMTP Address and Alias Email Addresses are available in the ProxyAddresses attribute. Refer to this post to know more about how the proxyAddresses attribute is populated in Azure AD. The Get-AzureADUser cmdlet also provides the separate field Mail which contains Primary SMTP Addresses of the user.

Before you start, run the following command to connect the Azure AD PowerShell module.

Connect-AzureAD

The below command retrieves the details for the given Microsoft 365 user account.

Get-AzureADUser -ObjectId "[email protected]" | Select DisplayName,UserPrincipalName,Mail,ProxyAddresses

Export All Microsoft Office 365 Users to CSV file

The following commands fetch all the Azure AD Users and export the user details ( DisplayName, ObjectId, UPN, Primary SMTP Address, and Email Aliases) to a CSV file.

$Result = @()

# Get all Azure AD Users with all properties
#$AllUsers = Get-AzureADUser -All $true

# Get all Azure AD Users with required properties
$AllUsers = Get-AzureADUser -All $true | Select DisplayName,UserPrincipalName,Mail,ProxyAddresses,ObjectId

ForEach ($User in $AllUsers)
{
# Add user detail to $Result array one by one
$Result += New-Object PSObject -property $([ordered]@{
UserName = $User.DisplayName
UserPrincipalName = $User.UserPrincipalName
PrimarySmtpAddress = $User.Mail
AliasSmtpAddresses = ($User.ProxyAddresses | Where-Object {$_ -clike 'smtp:*'} | ForEach-Object {$_ -replace 'smtp:',''}) -join ','
UserId= $User.ObjectId
})
}
# Export M365 Users report to CSV file
$Result | Export-CSV "C:\Microsoft365Users.CSV" -NoTypeInformation -Encoding UTF8
Advertisement