Functions/Disconnect-ExchangeOnline.ps1

<#
.SYNOPSIS
    This function disconnects from the current Exchange Online session.
.DESCRIPTION
    This function disconnects from the current Exchange Online session
    It returns whether the disconnect was successful.
#>

function Disconnect-ExchangeOnline {
    # Retrieve sessions
    $exchangeOnlineSession = Get-PSSession | Where-Object { $_.Name -eq "ExchangeOnline" }

    # There is at least one existing session
    if ($null -ne $exchangeOnlineSession) {
        # There is more than one existing session
        if ($null -ne $exchangeOnlineSession.length -and $exchangeOnlineSession.length -gt 1) {
            foreach ($session in $exchangeOnlineSession) {
                $session | Remove-PSSession
            }
            Write-Information "Disconnected Exchange Online sessions."
        }

        # There is only one existing session
        else {
            $exchangeOnlineSession | Remove-PSSession
            Write-Information "Disconnected Exchange Online session."
        }
        return $true
    }

    # There are no existing sessions
    else {
        Write-Warning "Attempting to disconnect Exchange Online session when there isn't one running."
        return $false
    }
}