Managing Your Connections

When working with on-premises servers we may not thing about the remote PowerShell connections that are made, whether they are broken or if they could cause issues with the connected server at all. When it comes to cloud services, these remote connections become even more important. Having too many connections open is not good for your tenant and Microsoft has put a limit on the number of connections you can make as documented here:

https://docs.microsoft.com/en-us/office365/enterprise/powershell/connect-to-exchange-online-tenants-with-remote-windows-powershell-for-delegated

“There’s a limit of three simultaneous sessions that can run under one account.”

So when working with PowerShell to manage your Office 365 tenant, proper cleanup of connections should be forefront of your scripts. Again, a typical script for on-premises servers pays no attention to these connections. However, with Office 365, a conscientious effort needs to be taken. This means adding code to a script to close any open connections when the connections are no longer needed. The code is relatively simple:

[sourcecode language=”powershell”]
Get-PSSession | Remove-PSSession
[/sourcecode]
There should be no feedback if the cmdlet executes successfully. Another reason to cleanup PowerShell sessions is if they are broken. This could happen with a timeout if a PowerShell windows is left to idle too long, or if there is an issue on the Office 365 side of the connection. Often if you were to execute a PowerShell cmdlet in a window where the connection is broken, an authentication prompt could occur.

Sometimes the cmdlets do not work at all. If you run ‘Get-PSSession’ you may see broken PowerShell connections. closing these sessions and opening new ones may not resolve the issue. Closing the PowerShell window and opening a new one should resolve the issue.

Conclusion

Important cmdlets for PowerShell session management:
[sourcecode language=”powershell”]
Get-PSSession
Remove-PSSession
[/sourcecode]
Just remember to cleanup your connections, or you may experience issues if you hit the limit or are left with stale broken connections.

Related Post