Exchange Online Reconnect script

I’ve seen and known many scripts that interact with Exchange Online for extended periods of time. After a while, Exchange Online likes it if you reconnect, this can be an Impliciet Authentication popup, or it can simply drop you based on what command you’re using.

If you call the following function every loop in whatever you’re doing, it’ll automatically force a reconnect to Exchange Online every hour (adjustable if you prefer longer):

function validateExOConnection{
$timeSpanMinutes = (New-TimeSpan $script:timeConnected (Get-Date)).TotalMinutes
if($timeSpanMinutes -gt 60){
$script:timeConnected = Get-Date
$script:timeConnected = Get-Date
if($script:Session -eq $Null -or $script:Session.State -ne "Opened"){
#There is no session, or it has gone stale
Get-PSSession | Remove-PSSession -Confirm:$False
$failed = $False
try{ $a = New-PSSessionOption
$a.IdleTimeout = 432000000000
$script:Session = New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri -Credential $o365Creds -Authentication Basic -AllowRedirection -SessionOption $a
$res = Import-PSSession $script:Session -AllowClobber -DisableNameChecking -WarningAction SilentlyContinue -Prefix EXO
Write-Host "Reconnected to Exchange Online" -ForegroundColor White
return $Null
$failed = $True
if($failed -and !$retry){
validateExoConnection -o365Creds $o365Creds -retry
return $Null
if($failed -and $retry){
Throw "Failed to connect to Exchange Online $_"

Download: ExOReconnect.ps1 (right click, save as)

Leave a Reply

2 Comments on "Exchange Online Reconnect script"

Notify of
Sort by:   newest | oldest | most voted

Hey there – I’m curious, when would you need this? Do you have an example of a situation that would require a long running script? I’ve just simply had a scheduled task on a server that runs every hour or 24 hours and it connects each time.