Functions/Disconnect-ExchangeOnline.ps1

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
<#
.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 {
    [CmdletBinding(PositionalBinding=$false)]
    [OutputType([Bool])]
    param ()

    # Retrieve sessions
    $exchangeOnlineSession = ConvertTo-Array (Get-PSSession | Where-Object { $_.Name -eq "ExchangeOnline" })

    # Disconnect the sessions
    if ($exchangeOnlineSession.length -gt 0) {
        foreach ($session in $exchangeOnlineSession) {
            $session | Remove-PSSession
        }
        Write-Information "Disconnected Exchange Online session(s)."
        return $true
    }

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