functions/Disconnect-O365.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
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
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" }
        {
            try
            {
                Disconnect-AzureAD -ErrorAction Stop
            }
            catch {}
        }
        { $_ -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
        }
    }
}