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{
Param(
[Parameter(Mandatory=$true)]$o365Creds,
[switch]$retry
)
if($script:timeConnected){
$timeSpanMinutes = (New-TimeSpan $script:timeConnected (Get-Date)).TotalMinutes
if($timeSpanMinutes -gt 60){
$script:Session=$Null
$script:timeConnected = Get-Date
}
}else{
$script:timeConnected = Get-Date
$script:Session=$Null
}
if($script:Session -eq $Null -or $script:Session.State -ne "Opened"){
#There is no session, or it has gone stale
try{
Get-PSSession | Remove-PSSession -Confirm:$False
}catch{$Null}
$failed = $False
try{ $a = New-PSSessionOption
$a.IdleTimeout = 432000000000
$script:Session = New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri https://outlook.office365.com/powershell-liveid/ -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
}catch{
$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
avatar
Sort by:   newest | oldest | most voted
Mike
Guest

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.

Thanks!