SQL Server with Mr. Denny

Jan 28 2019   4:00PM GMT

Connecting to Office365 with PowerShell

Denny Cherry Denny Cherry Profile: Denny Cherry

Tags:

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

 Comment on this Post

 
There was an error processing your information. Please try again later.
Thanks. We'll let you know when a new response is added.
Send me notifications when other members comment.

Forgot Password

No problem! Submit your e-mail address below. We'll send you an e-mail containing your password.

Your password has been sent to:

Share this item with your network: