functions/Disconnect-O365.ps1

function Disconnect-O365
{
    [CmdletBinding()]
    PARAM
    (
        [parameter(Mandatory = $true)]
        [ValidateSet("AzureActiveDirectory","Exchange","ComplianceCenter","Sharepoint","Skype","*")]
        [string[]]
        $Services
    )

    if ($Services -eq "*")
    {
        $Services = $AllServices
    }

    switch ($Services)
    {
        { $_ -contains "AzureActiveDirectory" }
        {
            # the MSOnline module does not support disconnection - we'll leave this for later when we add support for the AzureAD module
        }
        { $_ -contains "Exchange" }
        {
            Get-PSSession | Where-Object ComputerName -eq $ExchComputerName | Remove-PSSession
            Remove-Module -Name ExchangeOnline -ErrorAction SilentlyContinue
        }

        { $_ -contains "Skype" }
        {
            Get-PSSession | Where-Object ComputerName -Like "*$SkypeComputerName" | Remove-PSSession
            Remove-Module -Name SkypeForBusiness -ErrorAction SilentlyContinue
        }

        { $_ -contains "Sharepoint" }
        {
            try
            {
                Microsoft.Online.Sharepoint.PowerShell\Disconnect-SPOService -ErrorAction Stop
            }
            catch [System.InvalidOperationException] { }
            catch
            {
                Write-Error $_
            }
        }

        { $_ -contains "ComplianceCenter" }
        {
            Get-PSSession | Where-Object ComputerName -eq 'ps.compliance.protection.outlook.com' | Remove-PSSession
            Remove-Module -Name ComplianceCenter -ErrorAction SilentlyContinue
        }
    }
}