Connect to Office 365 via Remote PowerShell

First, I should point out that there are a couple of ways of connecting to Office 365. One option involves using the Microsoft Online Service Module for Windows PowerShell cmdlet named Connect-MsolService. This option will connect you to the Office 365 PowerShell web service so that you can execute any of the cmdlets that are included in the MSOnline module.

Another option involves establishing a remote PowerShell connection to Exchange Online for the purpose of remotely executing native Exchange cmdlets against Office 365. This is the option that I describe as follows. 

Try creating a function and adding it to your PowerShell profile so that you can quickly execute the function from any open PowerShell session when you need it. Start by creating a PowerShell profile if you do not already have one. The following one liner will create an empty PowerShell profile.

PS> New-item $profile –itemtype file –force

 

Next open the profile file in Notepad. This step is easily performed from PowerShell using the following command.

PS> notepad $profile

 

Copy and paste the following function into the profile, save the file, and restart PowerShell (or reload the profile).

 

Function Connect-ExchangeOnline

{

                [CmdletBinding()]

                param

                (

                                [Parameter(Mandatory = $False)]

                                [System.Management.Automation.PsCredential]$Credential = $Host.UI.PromptForCredential("Enter MSOL Admin Credential",

                                "Enter the username and password of an MSOnline Administrator account.",

                                "",

                                "userCreds"),

                               

                                [Parameter(Mandatory = $False)]

                                [System.Uri]$Uri = "https://ps.outlook.com/powershell/"

                )

                $session = New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri $Uri -Credential $Credential -Authentication "Basic" -AllowRedirection

                Import-PSSession $session -AllowClobber

                Return $session

}

 

Now, when you need to connect to Office 365 to run Exchange cmdlets, you can simply type “Connect-ExchangeOnline” directly at the PowerShell prompt just as if you were launching a cmdlet. It is no longer necessary to try to remember where you stored that script or text file that contains the lines of code used to establish the connection - the code/function is readily available upon demand at your fingertips every time you launch PowerShell.