function disconnectExchangeOnline{
<# manually check sessions
PS C:\Windows\system32> Get-PSSession

Id Name ComputerName ComputerType State ConfigurationName Availability
-- ---- ------------ ------------ ----- ----------------- ------------
4 WinRM4 outlook.offi... RemoteMachine Opened Microsoft.Exchange Available
5 WinRM5 outlook.offi... RemoteMachine Opened Microsoft.Exchange Available
#>
$activeExchangeOnlineSessionIds=(Get-PSSession |?{$_.ConfigurationName -eq "Microsoft.Exchange"}).Id
if($activeExchangeOnlineSessionIds){
Remove-PSSession -id $activeExchangeOnlineSessionIds;
write-host "session ID $activeExchangeOnlineSessionIds is disconnected."
}
}

function connectToExchangeOnline{
param(
$credential=(get-credential),
$connectionURI="https://outlook.office365.com/powershell-liveid/"
)
#Disconnect any active sessions prior to initiating a new one
disconnectExchangeOnline;

if (!($activeExchangeOnlineSessionIds)){
#Imports the base MSOnline module
if (!(Get-Module -ListAvailable -Name MSOnline)){Install-Module MSOnline -Confirm:$false -Force;}

$GLOBAL:onlineExchangeSession = New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri $connectionURI -Credential $credential -Authentication Basic -AllowRedirection
Import-PSSession $onlineExchangeSession -AllowClobber -DisableNameChecking
}else{
write-host "An active session is already available. No new connections were made."
}
}

connectToExchangeOnline;