Public/Connection/Assert-GraphConnection.ps1

# Module: Orbit.Authentication
# Function: Testing
# Author: David Eberhardt
# Updated: 27-MAY 2023
# Status: Live

#IMPROVE This is the same as Test - it does not try to re-establish connect as Assert-<>Connection Cmdlets should - Remove?


function Assert-GraphConnection {
  <#
  .SYNOPSIS
    Tests whether a valid PS Session exists for MicrosoftTeams
  .DESCRIPTION
    A connection established via Connect-MicrosoftTeams is parsed.
  .EXAMPLE
    Test-MicrosoftTeamsConnection
 
    Will Return $TRUE only if a session is found.
  .INPUTS
    System.Void
  .OUTPUTS
    System.Boolean
  .NOTES
    Calls Get-PsSession to determine whether a Connection to MicrosoftTeams (SkypeOnline) exists
  .COMPONENT
    TeamsSession
  .FUNCTIONALITY
    Tests the connection to MicrosoftTeams (SkypeOnline)
  .LINK
    https://github.com/DEberhardt/Orbit/tree/main/docs/Orbit.Authentication/Assert-GraphConnection.md
  .LINK
    https://github.com/DEberhardt/Orbit/tree/main/docs/about/about_TeamsSession.md
  .LINK
    https://github.com/DEberhardt/Orbit/tree/main/docs/
  #>


  [CmdletBinding()]
  [OutputType([Boolean])]
  param() #param

  begin {
    #Write-Verbose -Message "[BEGIN ] $($MyInvocation.MyCommand)"
    #Show-OrbitFunctionStatus -Level Live
    $Stack = Get-PSCallStack
    $Called = ($stack.length -ge 3)
  } #begin

  process {
    #Write-Verbose -Message "[PROCESS] $($MyInvocation.MyCommand)"
    $TenantInfo = [PsCustomObject][Ordered]@{
      TenantId = $null
      DisplayName = $null
      Connected = $false
      AccessEstablished = $false
    }
    try {
      $Tenant = Get-MgContext -WarningAction SilentlyContinue -ErrorAction Stop
      $TenantInfo.Connected = $true
      if ( $Tenant ) {
        $TenantInfo.TenantId = $Tenant.TenantId
        $TenantInfo.DisplayName = $Tenant.DisplayName
        $TenantInfo.AccessEstablished = $true
      }
    }
    catch {
      if ( $_.Exception.Message -eq 'sessionNotInitialized' ) {
        $TenantInfo.AccessEstablished = $false
      }
      elseif ( $_ -match 'Access denied' ) {
        $TenantInfo.AccessEstablished = $false
      }
    }
    return $TenantInfo
  } #process

  end {
    #Write-Verbose -Message "[END ] $($MyInvocation.MyCommand)"
  } #end
} # Assert-GraphConnection