Connect to Office 365 with PowerShell

I've recently been working on a project to migrate an Exchange Server 2010 environment to Office 365. As with Exchange, there are several things that simply can't be done from the GUI in Office 365. This means that if you're the Office 365 administrator for your company, you'll need a certain level of proficiency with PowerShell to effectively do your job .

While not requirements, this blog article is written using Windows 10 Enterprise Edition version 1803 and PowerShell Core version 6.0.2. All of the examples also work using the default version of Windows PowerShell that ships with Windows 10. Your mileage may vary with other operating systems and other versions of PowerShell.

The following three commands could be run using a PowerShell one-liner, but I find that it's easier to understand if they're broken down into separate commands.

First, store your Office 365 credentials with sufficient access to your Office 365 environment in a variable.

1$O365Cred = Get-Credential

office365login1a.png

Create a new PSSession to your Office 365 account.

1$Session = New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri https://ps.outlook.com/powershell-liveid?DelegatedOrg=yourdomain.onmicrosoft.com -Credential $O365Cred -Authentication Basic -AllowRedirection

office365login2a.png

Import the PSSession.

1Import-PSSession -Session $Session

office365login3a.png

This creates a temporary module on your local system with a random name. Use Get-Command along with the name of the temporary module to determine the list of commands that were added.

1Get-Command -Module <modulename>

office365login4a.png

At this point, any of the commands from the temporary module can be run and used to manage your Office 365 environment.

This module will exist until PowerShell is closed or until you remove the PSSession.

1Remove-PSSession -Session $Session

office365login5a.png

Or at least until the PSSession has be idle for a certain amount of time. The default idle timeout is 15 minutes (900,000 milliseconds).

1Get-PSSession | Select-Object -Property IdleTimeout

office365login6a.png

In the previous command, if more than one PSSession exists, narrow down the results using one of the parameters for Get-PSSession to obtain accurate results for the specific one that's established to Office 365.

µ