We all have a time where we cannot dump the contents of Exchange to a CSV file as that platform contains email address that are valid but do not need to get certain emails, in this particular example the list I required was for a "status page" - ironically covered in my post about Cachet.
That means I did not need all the shared mailboxes and all the service accounts that also have mailboxes, I only required mailboxes that had "users" at the other end, not service accounts or system mailboxes, so to the Powershell cave.....
I also required the output not not contain "quotes" and the data should look like this:
e-mail
lee@bear.local
bear@bear.local
This is the script that did the magic for my requirements.....
# Import the required modules
Import-Module ExchangeOnlineManagement
# Connect to Exchange Online
Connect-ExchangeOnline
# Define prefixes to exclude
$excludedPrefixes = @(
"exclusion1", "exclusion2", "exclusion3", "exclusion4"
)
# Retrieve all user mailboxes
$mailboxes = Get-Mailbox -ResultSize Unlimited
# Extract email addresses and exclude those starting with specified prefixes
$emailAddresses = $mailboxes | Where-Object {
$exclude = $false
foreach ($prefix in $excludedPrefixes) {
if ($_.PrimarySmtpAddress -like "$prefix*") {
$exclude = $true
break
}
}
-not $exclude
} | Select-Object -ExpandProperty PrimarySmtpAddress
# Prepare data for CSV export
$emailData = $emailAddresses | ForEach-Object { [PSCustomObject]@{ "e-mail" = $_ } }
# Define the path to the output CSV file
$outputPath = "mailboxes.csv"
# Export to CSV without quotes around fields
$emailData | ConvertTo-Csv -NoTypeInformation | Select-Object -Skip 1 | ForEach-Object { $_ -replace '"', '' } | Set-Content -Path $outputPath
# Disconnect from Exchange Online
Disconnect-ExchangeOnline -Confirm:$false