Public/Session/Disconnect-VCDService.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
function Disconnect-VCDService(){
    <#
    .SYNOPSIS
    This cmdlet removes the currently connected VMware Cloud Director service connection.

    .DESCRIPTION
    This cmdlet removes the currently connected VMware Cloud Director service connection.

    .EXAMPLE
    Disconnect-VCDSService
    Tears down the current session to the VMware Console Services Portal (CSP)

    .NOTES
    AUTHOR: Adrian Begg
    LASTEDIT: 2020-07-06
    VERSION: 1.1
    #>

    if(!$global:VCDService.IsConnected){
        Write-Warning "You are currently not connected to the VMware Cloud Services Portal. Nothing will be performed."
    } else {
        # Make the call to the API (TO DO) to logoff and remove the session variable from PowerShell - the below call does not end the session ?
        try{
            # A Hashtable of Request Parameters for the Logoff
            [Hashtable] $RequestParameters = @{
                URI = "https://console.cloud.vmware.com/csp/gateway/am/api/auth/logout"
                Method = "Post"
                ContentType = "application/json"
                Headers = @{
                    "csp-auth-token" = "$($global:VCDService.AccessToken)"
                    "Accept" = "application/json"
                }
                UseBasicParsing = $true
                Body = "{ ""idToken"" : ""$($global:VCDService.AccessToken)"" }"
            }
            $CSPTokenResult = Invoke-WebRequest @RequestParameters
        } catch {
            throw "An error has occurred during the logoff process."
        }
        if($CSPTokenResult.StatusCode -ne 200) {
            throw "An error has occurred during the logoff process."
        }
        # Finally clear the PowerShell variable for the expired session
        Set-Variable -Name "VCDService" -Value $null -Scope Global
    }
}