Microsoft 365 provides a lot of well conceived admin tools via its on-line portal. Their user tool is fantastic for creating and editing user accounts, but getting reports from it can be challenging. Lucky for us Microsoft 365 can also be accessed through PowerShell.
This script will prompt for credentials and the org name. Then it will retrieve all of the licensed users’ display names, primary smtp addresses from Exchange, user principle names, and the licenses currently applied to the account. The CSV report will be saved in your documents library.
The machine you run the script from needs the MS365 PowerShell modules installed. See https://docs.microsoft.com/en-us/office365/enterprise/powershell/connect-to-office-365-powershell
$UserCredential = Get-Credential
$ExchangeOnline = New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri https://outlook.office365.com/powershell-liveid/ -Credential $UserCredential -Authentication Basic -AllowRedirection
Import-PSSession $ExchangeOnline
Connect-MsolService -Credential $UserCredential
$tenant = Read-Host "Enter Tenant Org Name"
$tenantname = $tenant + ":"
Get-MsolUser -All | Where {$_.islicensed -like "True"} | Select DisplayName, UserPrincipalName,
@{Name="Primary Email Address"; Expression={Get-Mailbox -Identity $_.UserPrincipalName | Select-Object PrimarySmtpAddress -ExpandProperty PrimarySmtpAddress}},
@{Name="Enabled Licenses"; Expression={[string]($_.Licenses.AccountSkuID).Replace("$tenantname", " ") -replace "_", " "}}|
Export-Csv -Path $env:USERPROFILE\documents\Microsoft_365_User_Report.csv -NoTypeInformation