How to Check Connect-ExchangeOnline Session

Meanwhile, I remain connected on Exchange Online and often required to check Connect-ExchangeOnline Session, is active or expired. Therefore, I created a small code snippet to run before my routine Exchange PowerShell commands. Most importantly, i divided this tutorials into two main sections. Firstly, I used Get-PSSession command with command parameters to check the available sessions. Secondly, I wrote a small code snippet where I stored Get-PSSession command output in a variable. Then, I use the variable to check the exchange online session. Further, if a Connect-ExchangeOnline session is already active, I simply initiated Connect-ExchangeOnline command.

Get-PSSession Command

Firstly, I am using Get-PSSession command to confirm the active session name, computer name and session state. Therefore, Get-PSSession command will show results displayed in image below.

Get-PSSession | Format-Table -Property Name, ComputerName, State
Get-PSSession Command

Check Connect-ExchangeOnline Session

Afterward, Based on the above mentioned information under Get-PSSession command, we need to check the session first. Therefore, I wrote a small code snippet to check if a Connect-ExchangeOnline is already actived?.

#Connect & Login to ExchangeOnline with or without MFA
 $getSessionNames = Get-PSSession | Select-Object -Property Name, State
 $isConnected = (@($getSessionNames) -like '@{State=Opened; Name=ExchangeOnlineInternalSession*').Count -gt 0
 If ($isConnected -ne "True") {
      Connect-ExchangeOnline
 }

Finally, I achieved the required results. Now, Let me explain the above code in detail.

  • $getSessionNames = Get-PSSession | Select-Object -Property Name, State
    • $getSessionNames variable is used to store Get-PSSession information. I am simply selecting Session Name and Session State.
  • $isConnected is an other variable to store ExchangeOnlineInternalSession Name with count 0.
  • If ($isConnected -ne “True”) statement, I use to Connect-ExchangeOnline, if $isConnected is True.
Check Connect-ExchangeOnline Session

Disconnect-ExchangeOnline

Most importantly, We need to disconnect exchange online by using Disconnect-ExchangeOnline command. Therefore, if you are trying to disconnect exchange online session with Disconnect-PSSession command, you can face some error message on your screen.

Share

You may also like...