Skip to content

Get-Mailboxes-Query

Exchange Online: Query-format list of mailboxes

#Requires -Version 5.1

[CmdletBinding()]
Param(
    [switch]$InactiveMailboxOnly,
    [switch]$IncludeInactiveMailbox,
    [switch]$ExcludeResources
)

Process {
    try {
        [string[]]$Properties = @('PrimarySmtpAddress','UserPrincipalName','DisplayName','WindowsEmailAddress','IsInactiveMailbox','IsResource')

        if ($InactiveMailboxOnly) {
            $boxes = Get-Mailbox -InactiveMailboxOnly -SortBy DisplayName -ErrorAction Stop | Select-Object $Properties
        }
        elseif ($IncludeInactiveMailbox) {
            $boxes = Get-Mailbox -IncludeInactiveMailbox -SortBy DisplayName -ErrorAction Stop | Select-Object $Properties
        }
        else {
            $boxes = Get-Mailbox -SortBy DisplayName -ErrorAction Stop | Select-Object $Properties
        }

        if ($null -eq $boxes -or $boxes.Count -eq 0) {
            Write-Output "No Mailboxes found"
            return
        }

        if ($ExcludeResources) {
            $boxes = $boxes | Where-Object -Property IsResource -EQ $false
        }

        foreach ($itm in $boxes) {
            [PSCustomObject]@{
                Timestamp    = Get-Date -Format "yyyy-MM-dd HH:mm:ss"
                Value        = $itm.UserPrincipalName
                DisplayValue = $itm.DisplayName
            }
        }
    }
    catch { throw }
}
Off

Include only inactive mailboxes in the results

Off

Include inactive mailboxes in the results

Off

Exclude resource mailboxes from the results

An interactive directory of PowerShell scripts.