Confirm-ExchangeOnlineConnection.ps1

function Confirm-ExchangeOnlineConnection
{
  <#
    .SYNOPSIS
    Confirms there is an active connection to Exchange Online. Connects if prompted.
    .DESCRIPTION
    Confirms there is an active connection to Exchange Online. Connects if prompted.
    .EXAMPLE
    Confirm-ExchangeOnlineConnection -ConnectIfDisconnected
    Confirms connection. If disconnected, we connect.
    .EXAMPLE
    Confirm-ExchangeOnlineConnection
    Only confirms connection.
  #>

  [CmdletBinding()]
  param
  (
    [Parameter(Mandatory=$false, Position=0)]
    [Switch]
    $ConnectIfDisconnected
  )
  
  #Confirm we are connected to EOL. If not, connect.
  
  $ConnectionState = (Get-PSSession | ? {$_.ConfigurationName -eq "Microsoft.Exchange" -and $_.State -eq "Opened" -and $_.ComputerName -eq "outlook.office365.com"}).count
  if ($ConnectionState -eq 0) {
    #return "Disconnected"
    Write-Output 'Not connected to Exchange Online.'
    if ($ConnectIfDisconnected) {
      Write-Output 'Connecting...'
      Connect-ExchangeOnline -Verbose
      #Import-PSSession (Get-PSSession | ? {$_.ComputerName -like "*outlook*" -and $_.State -eq 'Opened'})
      #return $session
    }
  } Else {return 'Already Connected'}
}