Functions/Connect-Office365SecurityAndComplianceAdminAccount.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
60
61
62
<#
.SYNOPSIS
    This function connects to Office 365 Security and Compliance Center using admin account credentials or a MSPComplete Endpoint.
.DESCRIPTION
    This function connects to Office 365 Security and Compliance Center using admin account credentials or a MSPComplete Endpoint.
    It returns whether the connection and logon was successful.
.EXAMPLE
    Connect-Office365SecurityAndComplianceAdminAccount -Endpoint $Endpoint
.EXAMPLE
    $Endpoint | Connect-Office365SecurityAndComplianceAdminAccount
.EXAMPLE
    Connect-Office365SecurityAndComplianceAdminAccount -Username $username -Password $password
#>

function Connect-Office365SecurityAndComplianceAdminAccount {
    [CmdletBinding(PositionalBinding=$false)]
    [OutputType([String])]
    param (
        # The username of the Office 365 Security and Compliance Center admin account.
        [Parameter(Mandatory=$true, ParameterSetName="credential")]
        [string]$username,

        # The password of the Office 365 Security and Compliance Center admin account.
        [Parameter(Mandatory=$true, ParameterSetName="credential")]
        [SecureString]$password,

        # The MSPComplete Endpoint for the Office 365 Security and Compliance Center admin credentials.
        [Parameter(Mandatory=$true, ParameterSetName="endpoint", ValueFromPipeline=$true)]
        $endpoint
    )

    # If given endpoint, retrieve username and password
    if ($PSCmdlet.ParameterSetName -eq "endpoint") {
        $office365Credential = $endpoint.Credential
        $username = $office365Credential.Username
    }

    # Create the Office 365 Security and Compliance Center credential from the given username and password
    else {
        $office365Credential = [PSCredential]::new($username, $password)
    }

    # Logon to Office 365 Security and Compliance Center
    try {
        $office365Session = New-PSSession -ConfigurationName Microsoft.Exchange `
            -ConnectionUri "https://ps.compliance.protection.outlook.com/powershell-liveid/" `
            -Credential $office365Credential -Authentication Basic -AllowRedirection -Name "Office365SecurityAndCompliance"

        # Additional Import-Module ensures that imported cmdlets are visible globally
        Import-Module (Import-PSSession $office365Session -DisableNameChecking -AllowClobber -Prefix "SC_") -Global

        # Logon was successful
        Write-Information "Logon to Office 365 Security and Compliance Center successful with username '$($username)'."
        return $true
    }

    # Logon was unsuccessful
    catch {
        Write-Error "Exception while attempting to logon to Office 365 Security and Compliance Center with username '$($username)'.`r`n$($_.Exception.Message)"
        return $false
    }
}