<# .SYNOPSIS Gets a Bearer token for the Ka-Note production API via MSAL.PS. Installs MSAL.PS automatically if missing. Uses cached tokens / refresh tokens — browser login only needed on first run or after token cache is cleared. .OUTPUTS Writes the access token string to stdout. .EXAMPLE $token = & "$PSScriptRoot\get-token.ps1" #> param() $ErrorActionPreference = 'Stop' $ClientId = '1aba7af7-eec1-4e49-b87e-9f941c0e8630' $TenantId = '94cf90d7-e9ff-49a1-bc3b-a5b94d3cc8ca' $Scopes = "api://$ClientId/access" # --- Ensure MSAL.PS is available --------------------------------------------- if (-not (Get-Module -ListAvailable -Name 'MSAL.PS')) { Write-Host " [INFO] Installing MSAL.PS module..." -ForegroundColor DarkGray Install-Module -Name 'MSAL.PS' -Scope CurrentUser -Force -AllowClobber } Import-Module MSAL.PS -ErrorAction Stop # --- Acquire token ----------------------------------------------------------- $params = @{ ClientId = $ClientId TenantId = $TenantId Scopes = $Scopes } $result = $null # 1. Try silent first (uses cached access token or refresh token) try { $result = Get-MsalToken @params -Silent 2>$null } catch { # No cached token or refresh failed — fall back to interactive } # 2. Interactive browser login if (-not $result) { Write-Host " [AUTH] Opening browser for login..." -ForegroundColor Yellow $result = Get-MsalToken @params -Interactive } if (-not $result -or -not $result.AccessToken) { Write-Error "Failed to acquire token." exit 1 } # Output only the token (callers capture via $token = & .\get-token.ps1) Write-Output $result.AccessToken