Use a PoSH-function to connect to MS Online

I like to make my life as easy as possible. One of the ways is doing this, is bij using Powershell whenever I can. To quicly connect to O365 and Azure AD through PoSH, I use a simple function in my Powershell-profile.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
function Open-MSOLConnection
{
<#
.SYNOPSIS
Connects and loads a MSOL PoSH Connection.
.DESCRIPTION
Gets credential for MSOL Session, configures a new session and loads it.
.EXAMPLE
Open-MSOLConnection
#>
$LiveCred = Get-Credential
$Session = New-PSSession -Name MSOL -ConfigurationName Microsoft.Exchange -ConnectionUri https://ps.outlook.com/powershell/ -Credential $LiveCred -Authentication Basic -AllowRedirection
Import-PSSession $Session
connect-msolservice -credential $LiveCred
}

When called through open-msolconnection, the function will ask for credentials, create a new PoSH-session to O365 and starts the Exchange Online session, so you can interact with both the Office 365 backend as the Exchange Online service in one session.

Ofcourse, you can expand this function as much as you’d like. For example, you could add a parameter that gets the stored credentials from disk for a given tenant, so you won’t have to manually enter those credentials when connecting.

Doing this would also make it easier to use the function in other scripts, so you can automate as much as possible!