Functions/Disconnect-Office365SecurityAndCompliance.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
<#
.SYNOPSIS
    This function disconnects from the current Office 365 Security and Compliance Center session.
.DESCRIPTION
    This function disconnects from the current Office 365 Security and Compliance Center session
    It returns whether the disconnect was successful.
#>

function Disconnect-Office365SecurityAndCompliance {
    [CmdletBinding(PositionalBinding=$false)]
    [OutputType([Bool])]
    param ()

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

    # Disconnect the sessions
    if ($office365Sessions.length -gt 0) {
        foreach ($session in $office365Sessions) {
            $session | Remove-PSSession
        }
        return $true
    }

    # There are no existing sessions
    else {
        Write-Warning "Attempting to disconnect Office 365 Security and Compliance Center session when there isn't one running."
        return $false
    }
}