Public/Authentication/Close-SCASession.ps1

function Close-SCASession {
    <#
    .SYNOPSIS
        Discards a psSCA session and its cached access token.
    .DESCRIPTION
        Removes the named session from memory. The access token is not revoked server-side (the
        platform token endpoint does not document a revocation operation); it simply becomes
        unreachable and expires naturally at its original expiry time.
    .PARAMETER Name
        The session to close. Defaults to the current default session.
    .EXAMPLE
        Close-SCASession

        Closes the current default session.
    .EXAMPLE
        Close-SCASession -Name Production

        Closes the session named 'Production'.
    .INPUTS
        None.
    .OUTPUTS
        None.
    .LINK
        https://api-docs.cyberark.com/create-api-token/docs/create-api-token
    #>

    [CmdletBinding(SupportsShouldProcess, ConfirmImpact = 'Low')]
    param(
        [Parameter(Position = 0)]
        [string]$Name
    )

    $targetName = if ($Name) { $Name } else { $script:SCACurrentSessionName }

    if (-not $targetName -or -not $script:SCASessions.Contains($targetName)) {
        Write-Warning "psSCA: no active session named '$targetName' to close."
        return
    }

    if ($PSCmdlet.ShouldProcess($targetName, 'Close psSCA session')) {
        $script:SCASessions.Remove($targetName)
        if ($script:SCACurrentSessionName -eq $targetName) {
            $script:SCACurrentSessionName = if ($script:SCASessions.Count -gt 0) {
                @($script:SCASessions.Keys)[0]
            }
            else {
                $null
            }
        }
        Write-Verbose "psSCA: closed session '$targetName'."
    }
}