Public/Disconnect-DattoApi.ps1

function Disconnect-DattoApi {
<#
.SYNOPSIS
Disposes one or more Datto API connections and removes credentials from module memory.
.DESCRIPTION
Disposes the associated HttpClient instances, removes PSCredential references, and removes the connections from the current PowerShell session. With no parameter, the default connection is disconnected.
.PARAMETER Connection
A connection object, name, or ID. Accepts pipeline input.
.PARAMETER All
Disconnects every Datto API connection in the current module session.
.EXAMPLE
Disconnect-DattoApi
.EXAMPLE
Get-DattoApiConnection | Disconnect-DattoApi
.EXAMPLE
Disconnect-DattoApi -All
#>

    [CmdletBinding(DefaultParameterSetName = 'Connection', SupportsShouldProcess, ConfirmImpact = 'Low')]
    param(
        [Parameter(ValueFromPipeline, Position = 0, ParameterSetName = 'Connection')]
        [AllowNull()]
        [object]$Connection,

        [Parameter(Mandatory, ParameterSetName = 'All')]
        [switch]$All
    )

    process {
        if ($All) {
            $states = @($script:DattoApiState.Connections.Values)
        }
        else {
            $states = @(Resolve-DattoApiConnectionState -Connection $Connection)
        }

        foreach ($state in $states) {
            if ($PSCmdlet.ShouldProcess("Datto API connection '$($state.Name)'", 'Disconnect and remove credentials from module memory')) {
                $id = [string]$state.Id
                $wasDefault = ([string]$script:DattoApiState.DefaultConnectionId -eq $id)
                Remove-DattoApiConnectionInternal -ConnectionState $state
                $null = $script:DattoApiState.Connections.Remove($id)
                if ($wasDefault) {
                    $next = @($script:DattoApiState.Connections.Values | Select-Object -First 1)
                    if ($next.Count -gt 0) { $script:DattoApiState.DefaultConnectionId = [string]$next[0].Id }
                    else { $script:DattoApiState.DefaultConnectionId = $null }
                }
            }
        }
    }
}