Connecting to Office365 with PowerShell

Published On: 2019-01-28By:

When looking at support documents for Office365, you’ll often see instructions like “connect PowerShell to Office365,” but there are no instructions on how to do that.  I was going through this, and thought, this is a problem I can fix.  It only takes a few lines of PowerShell to connect your PowerShell to an Office365 environment.  Basically what you are doing is PowerShell Remoting.  The underlying code that you’ll want to run is this:

Set-ExecutionPolicy RemoteSigned
$UserCredential = Get-Credential
$Session = New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri https://outlook.office365.com/powershell-liveid/ -Credential $UserCredential -Authentication Basic -AllowRedirection
Import-PSSession $Session -DisableNameChecking

When you run this code, it’ll prompt you for a username and password (that’s what the second line does). These are the credentials that you use to manage the Office365 environment.  After that, you can fire off whatever commands you need to, and they’ll be send to the Office365 farm, and the response will be sent back to your PowerShell window.

It should be noted that you’ll get an error with the line that starts with “$Session” if you have MFA on your account.  You’ll either need to disable MFA or put an exception for your IP address so that you don’t get an MFA prompt.  Once you do that, you can authenticate without MFA, and the third line of the code will work as connectinos to Office 365 via PowerShell appear not to support MFA currently.

Denny

The post Connecting to Office365 with PowerShell appeared first on SQL Server with Mr. Denny.


Contact the Author | Contact DCAC

Video

Globally Recognized Expertise

As Microsoft MVP’s and Partners as well as VMware experts, we are summoned by companies all over the world to fine-tune and problem-solve the most difficult architecture, infrastructure and network challenges.

And sometimes we’re asked to share what we did, at events like Microsoft’s PASS Summit 2015.

Awards & Certifications

Microsoft Partner       Insights Sccess Award    Technology Headlines Award    Golden Bridge Gold Award    CIO Review Top 20 Azure Solutions Providers    VMWare Partner
Microsoft Certified Master    Microsoft MVP
Share via