Private/Save-CIEMToken.ps1

function Save-CIEMToken {
    <#
    .SYNOPSIS
        Saves ARM and/or Graph tokens to script scope and PSU secrets.

    .DESCRIPTION
        Single source of truth for token storage. Stores tokens in script-scoped
        variables and persists to PSU secrets when running in PSU context.

    .PARAMETER ARMToken
        The ARM access token to store.

    .PARAMETER GraphToken
        The Graph access token to store.

    .EXAMPLE
        Save-CIEMToken -ARMToken $armResponse.access_token -GraphToken $graphResponse.access_token
    #>

    [CmdletBinding()]
    param(
        [Parameter()]
        [string]$ARMToken,

        [Parameter()]
        [string]$GraphToken
    )

    # Check PSU context once
    $inPSUContext = $null -ne (Get-PSDrive -Name 'Secret' -ErrorAction SilentlyContinue)

    if ($ARMToken) {
        $script:ARMAccessToken = $ARMToken
        Write-Verbose "ARM token stored in script scope"

        if ($inPSUContext) {
            $Secret:CIEM_Azure_ARMToken = $ARMToken
            Write-Verbose "ARM token stored in PSU secret"
        }
    }

    if ($GraphToken) {
        $script:GraphAccessToken = $GraphToken
        Write-Verbose "Graph token stored in script scope"

        if ($inPSUContext) {
            $Secret:CIEM_Azure_GraphToken = $GraphToken
            Write-Verbose "Graph token stored in PSU secret"
        }
    }
}