BitTitan.Runbooks.MSOnline.Beta.psm1

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
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
<#
.SYNOPSIS
    PowerShell module for common MSOnline functions and resources used in BitTitan Runbooks
.NOTES
    Version: 0.2.1
    Last updated: 23 October 2018
 
    Copyright (c) BitTitan, Inc. All rights reserved.
    Licensed under the MIT License.
#>


# Install/import BitTitan.Runbooks.Modules to bootstrap the install/import of the other modules
Install-Module BitTitan.Runbooks.Modules -Scope CurrentUser -AllowClobber
Import-Module BitTitan.Runbooks.Modules -Force

# Install/import the other BitTitan.Runbooks modules
Import-BT_Module BitTitan.Runbooks.MSPComplete 1>$null

<#
.SYNOPSIS
    This function connects to MSOnline using admin account credentials or a MSPComplete Endpoint.
.DESCRIPTION
    This function connects to MSOnline using admin account credentials or a MSPComplete Endpoint.
    It returns whether the connection and logon was successful.
.PARAMETER username
    The username of the MSOnline admin account.
.PARAMETER password
    The password of the MSOnline admin account.
.PARAMETER endpoint
    The MSPComplete Endpoint for the MSOnline admin credentials.
    This endpoint can be masked or unmasked.
.EXAMPLE
    Connect-MSOnlineAdminAccount -Endpoint $Endpoint
.EXAMPLE
    $Endpoint | Connect-MSOnlineAdminAccount
.EXAMPLE
    Connect-MSOnlineAdminAccount -Username $username -Password $password
#>

function Connect-MSOnlineAdminAccount {
    param (
        # The username of the MSOnline account.
        [Parameter(Mandatory=$true, ParameterSetName="credential")]
        [String]$username,

        # The password of the MSOnline account.
        [Parameter(Mandatory=$true, ParameterSetName="credential")]
        [SecureString]$password,

        # The MSPComplete Endpoint.
        [Parameter(Mandatory=$true, ParameterSetName="endpoint", ValueFromPipeline=$true)]
        $endpoint
    )

    # If given endpoint, retrieve credential directly
    if ($PSCmdlet.ParameterSetName -eq "endpoint") {
        $msolCredential = $endpoint | Get-CredentialFromMSPCompleteEndpoint
        $username = $msolCredential.Username
    }
    # Create the MSOnline credential from the given username and password
    else {
        $msolCredential = New-Object System.Management.Automation.PSCredential($username, $password)
    }

    # Logon to MSOnline
    try {
        Connect-MsolService -Credential $msolCredential -ErrorAction Stop

        # Logon was successful
        Write-Information "Connection and logon to MSOnline successful with username '$($username)'."
        return $true
    }
    catch {
        # Logon was unsuccessful
        Write-Error "Failed MSOnline account login with username '$($username)'. $($_.Exception.Message)"
        return $false
    }
}