public/Connect-OneShortcut.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
function Connect-OneShortcut {
    [CmdletBinding()]
    Param(
        [Parameter(Mandatory = $true)]
        [string] $TenantId,
    
        [Parameter(Mandatory = $true)]
        [string] $ClientId,
    
        [Parameter(Mandatory = $false)]
        [System.Security.Cryptography.X509Certificates.X509Certificate2] $ClientCertificate,
    
        [Parameter(Mandatory = $false)]
        [securestring] $ClientSecret
    )

    begin {
        Write-Verbose "[$(Get-Date)] [BEGIN ] $($MyInvocation.MyCommand)"
    }

    process {
        Write-Verbose "[$(Get-Date)] [CALL ] Test-OneConnection()"
        if (Test-OneConnection) {
            Write-Error "[$(Get-Date)] [ERROR ] Connection already established. Please use Disconnect-OneShortcut to clear the existing session." -ErrorAction Stop
        } else {
            $OneShortcutSession.AzureAdApp.TenantId = $TenantId
            $OneShortcutSession.AzureAdApp.ClientId = $ClientId

            if ($ClientCertificate) {
                $OneShortcutSession.AzureAdApp.ClientCertificate = $ClientCertificate
            } elseif ($ClientSecret) {
                $OneShortcutSession.AzureAdApp.ClientSecret = $ClientSecret
            } else {
                Write-Error "[$(Get-Date)] [ERROR ] Either ClientCertificate or ClientSecret has to be specified." -ErrorAction Stop
            }

            Write-Verbose "[$(Get-Date)] [CALL ] Invoke-OneTokenRequest()"
            $Token = Invoke-OneTokenRequest
            
            if ($Token.Response.StatusCode -eq "200") {
                $OneShortcutSession.Token.AccessToken = $Token.Data.AccessToken
                $OneShortcutSession.Token.ExpiresOn = $Token.Data.ExpiresOn

                Write-Host "Connected!"
            } else {
                Write-Error "[$(Get-Date)] [ERROR ] Unable to get token. Reason: $Token.Response.Message" -ErrorAction Stop
            }
        }
    }

    end {
        Write-Verbose "[$(Get-Date)] [END ] $($MyInvocation.MyCommand)"
    }
}