# Connect to Exchange Online (requires ExchangeOnlineManagement module)
# Install-Module -Name ExchangeOnlineManagement -Force -AllowClobber
# Connect-ExchangeOnline -ShowProgress $true

# --- Script ---

# Get all user mailboxes
Write-Host "Retrieving all user mailboxes..."
$mailboxes = Get-Mailbox -ResultSize Unlimited -Filter {RecipientTypeDetails -eq 'UserMailbox'}

# Create a container for the OOF enabled users
$oofEnabledUsers = @()

Write-Host "Checking Out of Office status for each mailbox..."
foreach ($mailbox in $mailboxes) {
    try {
        $oofSettings = Get-MailboxAutoReplyConfiguration -Identity $mailbox.UserPrincipalName
        
        if ($oofSettings.AutoReplyState -ne "Disabled") {
            $oofEnabledUsers += [PSCustomObject]@{
                UserPrincipalName = $mailbox.UserPrincipalName
                AutoReplyState    = $oofSettings.AutoReplyState
                StartTime         = $oofSettings.StartTime
                EndTime           = $oofSettings.EndTime
                InternalMessage   = $oofSettings.InternalMessage
                ExternalMessage   = $oofSettings.ExternalMessage
            }
            Write-Host "  OOO enabled for $($mailbox.UserPrincipalName)"
        }
    }
    catch {
        Write-Warning "Could not retrieve OOF settings for $($mailbox.UserPrincipalName). Error: $($_.Exception.Message)"
    }
}

# Display the OOF configurations for all users where it's enabled
Write-Host "`n--- Summary of Users with Enabled Out of Office ---"
if ($oofEnabledUsers.Count -gt 0) {
    $oofEnabledUsers | Format-Table
} else {
    Write-Host "No users found with Out of Office enabled."
}