We will use a powershell script to check the office 365 login status.
##First we create a function to check the response function MSOLConnected { Get-MsolDomain -ErrorAction SilentlyContinue | out-null $result = $? return $result } Install-module MSOnline #connect only if it's not connected if (-not (MSOLConnected)) { Connect-MSOLService } Import-Module MSOnline ##your other code #Remove the session Remove-PSSession $Session