# Ensure TLS 1.2 for secure connections
[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12
# Check PowerShell version
$psVersion = $PSVersionTable.PSVersion.Major
if ($psVersion -ge 7) {
Write-Warning "PowerShell $psVersion may have compatibility issues with ExchangeOnlineManagement. Windows PowerShell 5.1 is recommended."
} else {
Write-Host "PowerShell $psVersion detected. Proceeding." -ForegroundColor Green
}
# Check and install ExchangeOnlineManagement module
$module = Get-Module -ListAvailable -Name ExchangeOnlineManagement
if (-not $module) {
Write-Host "Installing ExchangeOnlineManagement module..." -ForegroundColor Yellow
try {
Install-Module -Name ExchangeOnlineManagement -Force -Scope CurrentUser -ErrorAction Stop
Write-Host "Module installed successfully." -ForegroundColor Green
} catch {
Write-Host "Failed to install module. Error: $_" -ForegroundColor Red
exit
}
} else {
Write-Host "ExchangeOnlineManagement module already installed." -ForegroundColor Green
}
# Import module
Import-Module ExchangeOnlineManagement
# Connect to Exchange Online
try {
Connect-ExchangeOnline -ShowProgress $true -ErrorAction Stop
} catch {
Write-Host "Failed to connect to Exchange Online. Error: $_" -ForegroundColor Red
exit
}
# Get shared mailboxes with licenses
$results = Get-Mailbox -RecipientTypeDetails SharedMailbox -ResultSize Unlimited |
ForEach-Object {
$user = Get-User -Identity $_.UserPrincipalName -ErrorAction SilentlyContinue
if ($user -and $user.IsLicensed) {
[PSCustomObject]@{
DisplayName = $_.DisplayName
UserPrincipalName = $_.UserPrincipalName
PrimarySmtpAddress = $_.PrimarySmtpAddress
LicenseStatus = "Licensed"
}
}
}
# Disconnect from Exchange Online
Disconnect-ExchangeOnline -Confirm:$false
# Export results to CSV
$csvPath = "C:\Temp\LicensedSharedMailboxes.csv"
if ($results) {
$results | Export-Csv -Path $csvPath -NoTypeInformation -Encoding UTF8
Write-Host "Licensed shared mailboxes exported to $csvPath" -ForegroundColor Green
} else {
Write-Host "No licensed shared mailboxes found." -ForegroundColor Yellow
}
# Display results
$results | Format-Table -AutoSize