BB
# Connect to Exchange Online
Connect-ExchangeOnline -UserPrincipalName your_email@yourdomain.com
# Get all mail-enabled users (exclude groups, shared mailboxes, etc.)
$users = Get-Recipient -RecipientTypeDetails UserMailbox -ResultSize Unlimited
# Initialize an array to store user data
$orgData = @()
# Loop through each user and get their details
foreach ($user in $users) {
# Get detailed mailbox information
$mailbox = Get-Mailbox -Identity $user.PrimarySmtpAddress
# Get manager information (if available)
$manager = $null
try {
$manager = Get-User -Identity $mailbox.Manager
} catch {
# If no manager is found, handle the error silently
}
# Add user data to the array
$orgData += [PSCustomObject]@{
Name = $user.DisplayName
Email = $user.PrimarySmtpAddress
JobTitle = $mailbox.Title
Department = $mailbox.Department
Manager = if ($manager) { $manager.DisplayName } else { "No Manager" }
}
}
# Export the data to a CSV file
$orgData | Export-Csv -Path "OrgStructure.csv" -NoTypeInformation -Encoding UTF8
Write-Host "Organization structure exported to OrgStructure.csv"