Exchange Online reconnect script v2

A few weeks ago I posted a script that would automatically, periodically, reconnect to Exchange Online. In field testing it would still prompt for credentials after 1-2 days, whatever I did.

So I took a different route and am now rewriting Microsofts’ module on the fly to no longer prompt for credentials. If you use below function to connect to Exchange Online, you should never receive reconnect prompts 🙂

disclaimer: don’t overwrite $o365Creds with invalid creds elsewhere in your script as those are used globally.


function buildResilientExchangeOnlineSession {
    Param(
        [Parameter(Mandatory=$true)]$o365Creds,
        $commandPrefix
    )
    Write-Verbose "Connecting to Exchange Online"
    Set-Variable -Scope Global -Name o365Creds -Value $o365Creds -Force
    $Session = New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri https://outlook.office365.com/powershell-liveid/ -Credential $o365Creds -Authentication Basic -AllowRedirection
    Import-PSSession $Session -AllowClobber -DisableNameChecking
    Write-Verbose "Connected to Exchange Online, exporting module..."
    $temporaryModulePath = (Join-Path $Env:TEMP -ChildPath "temporaryEXOModule")
    $res = Export-PSSession -Session $Session -CommandName * -OutputModule $temporaryModulePath -AllowClobber -Force
    $temporaryModulePath = Join-Path $temporaryModulePath -ChildPath "temporaryEXOModule.psm1"
    Write-Verbose "Rewriting Exchange Online module, please wait..."
      $regex='^.*\bhost\.UI\.PromptForCredential\b.*$'
    (Get-Content $temporaryModulePath) -replace $regex, "-Credential `$global:o365Creds ``" | Set-Content $temporaryModulePath
    $Session | Remove-PSSession -Confirm:$False
    Write-Verbose "Module rewritten, re-importing..."
    if($commandPrefix){
        Import-Module -Name $temporaryModulePath -Prefix $commandPrefix -DisableNameChecking -WarningAction SilentlyContinue -Force
        Write-Verbose "Module imported, you may now use all Exchange Online commands using $commandPrefix as prefix"
    }else{
        Import-Module -Name $temporaryModulePath -DisableNameChecking -WarningAction SilentlyContinue -Force
        Write-Verbose "Module imported, you may now use all Exchange Online commands"
    }
    return $temporaryModulePath
}

download: https://gitlab.com/Lieben/assortedFunctions/blob/master/buildResilientExchangeOnlineSession.ps1

Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

5 Comments
Most Voted
Newest Oldest
Inline Feedbacks
View all comments
Ryan Hunter
Ryan Hunter
1 year ago

Hi Jos, I am curious if you have a PowerShell script that could force Outlook to re-establish connectivity to Exchange online. There is a way to do this through the GUI where you ctrl right click the Outlook Icon in the sys tray, go to Connection Status then click Reconnect. It would be very helpful to do this via script as often when VPN is dropped, Outlook has a hard time automatically reconnecting. Thanks in advance!

Richard Summers
Richard Summers
5 years ago

I’ve been banging my head with a long running script that occasionally hung due to credential re-prompt. This is exactly what I was looking for. Great concept!

The only thing that bothers me is how long it takes to rewrite the module. Depending on the system it takes anywhere from 10-20 minutes. I replaced lines 15-32 with the following two lines and it now rewrites the file instantly.

$regex=’^.*\bhost\.UI\.PromptForCredential\b.*$’

(Get-Content $temporaryModulePath) -replace $regex, “-Credential $global:o365Creds`” | Set-Content $temporaryModulePath

trackback

[…] Edit: read v2 of this post 🙂 […]