Private/Test-SCASession.ps1
|
function Test-SCASession { <# .SYNOPSIS Resolves and validates the psSCA session a cmdlet should use. .DESCRIPTION Accepts whatever a cmdlet's -Session parameter was bound to: nothing (use the current default session), a session name, or a session object piped in from Get-SCASession. Then returns a single validated session object. Throws a terminating error if no session is available or the cached access token has expired, since expecting Invoke-SCARequest to return a 401 in that case would send an authenticated-looking request that fails late and without an actionable message. .PARAMETER Session A psSCA.Session object, a session name, or $null to use the current default session. .OUTPUTS psSCA.Session #> [CmdletBinding()] [OutputType([psobject])] param( [Parameter(Position = 0)] [AllowNull()] [object]$Session ) $resolved = $null if ($Session -is [psobject] -and $Session.PSObject.TypeNames -contains 'psSCA.Session') { $resolved = $Session } elseif ($Session -is [string] -and $Session) { $resolved = $script:SCASessions[$Session] if (-not $resolved) { throw "No psSCA session named '$Session' was found. Run Get-SCASession to list active sessions." } } elseif (-not $Session) { if (-not $script:SCACurrentSessionName -or -not $script:SCASessions.Contains($script:SCACurrentSessionName)) { throw 'No active psSCA session. Run New-SCASession first.' } $resolved = $script:SCASessions[$script:SCACurrentSessionName] } else { throw 'Test-SCASession: -Session must be a psSCA.Session object, a session name, or omitted.' } if ([DateTime]::UtcNow -ge $resolved.ExpiresAt) { throw "The psSCA session '$($resolved.Name)' expired at $($resolved.ExpiresAt.ToString('u')). Run New-SCASession to start a new session." } return $resolved } |