Confirm-ExchangeOnlineConnection.ps1

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
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'}
}