Private/Auth/Disconnect-GraphSession.ps1
|
# Copyright (c) 2026 Sandy Zeng. All rights reserved. # Source-available. All rights reserved. See LICENSE file. <# Disconnect-GraphSession.ps1 — Signs out from Microsoft Graph and clears all session state. Author: Sandy Zeng Project: IntuneDiff Version History: 1.0.0 Initial release. 1.0.2 Full session cleanup on window close; module state cleared on sign-out. #> function Disconnect-GraphSession { <# .SYNOPSIS Signs out from Microsoft Graph, removes the cached token for the current user, and clears module state. #> [CmdletBinding()] param( [switch]$KeepCache ) try { # Remove the current account from the MSAL token cache if (-not $KeepCache -and $script:SignedInUser -and $script:MSALApp) { $accounts = $script:MSALApp.GetAccountsAsync().GetAwaiter().GetResult() $targetAccount = $accounts | Where-Object { $_.Username -eq $script:SignedInUser.Account } | Select-Object -First 1 if ($targetAccount) { Remove-MSALCachedAccount -Account $targetAccount Write-MSALCache } } if (Test-GraphConnection) { Disconnect-MgGraph -ErrorAction SilentlyContinue | Out-Null } } finally { $script:SignedInUser = $null } } |