Connect to Exchange Online From a Windows Container

In this blog post, I show you how I connect to Office 365 Microsoft Exchange from within a Windows Container in a safe and secure method.

When managing multiple Office 365 environment, it can be a bit confusing sometimes to connect to a specific environment when I am connected to one or when I need to run scripts on multiple environments at the same time.

I had a few times That I had to use 2 or 3 virtual machines at the same time to manage work in multiple environments.

Now that we have Docker and Windows Containers I don’t need to do it anymore because I can merely spin a container and run my Exchange Online scripts.

Get Started

The first step in the process is to create a Docker Volume using the command below on my Windows machine running Docker Desktop (this can work on Windows Server as well).

Docker volume create --name psscripts

Exchange Online Connect Script using PowerShell

Below, is my PowerShell script that connects to Exchange Online, I save it and copy it to the volume I created above.

$powerUser = read-host "Enter Username"
$password = read-host "Enter Password" -AsSecureString
$userCredential = New-Object -TypeName System.Management.Automation.PSCredential -argumentlist $powerUser,$password
$ExoSession = New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri -Credential $userCredential -Authentication Basic -AllowRedirection

Import-PSSession $ExoSession

Below, is the volume location where I copy the code.


Create a Container

Now that I have the volume and script configured, I run the command below to create a container and map the volume to it.

docker run -it  -v c:\programdata\docker\volumes\psscripts:c:\psscripts microsoft/windowsservercore powershell

From inside the Container, I open the folder I placed the script and run it

The script asks me to provide a user name and password and once provided it connects me to Exchange Online

When I am complete with my task, I can delete or stop the container and create a new one next time.

Please note that the script does not work if you are using MFA to log in to Office 365.

Leave a comment

Your email address will not be published.

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