Connecting to Exchange Online
Connecting to Exchange Online involves creating a remote PowerShell session. This session is created using a special URL that points to your tenant. When you import the session, it downloads all the commands that the remote Exchange server understands.
You do not need to connect to Office 365 using Connect-MsolService before connecting to Exchange Online. Note that if you run the following scripts without setting $Credentials first, it will prompt you for authentication before connecting:
$TenantName = "my365tenant"
$exchUri = "https://ps.outlook.com/PowerShell-LiveID"
if (-not [string]::IsNullOrEmpty($TenantName)) {
if (-not $TenantName.EndsWith('onmicrosoft.com')) {
$TenantName = "$TenantName.onmicrosoft.com"
}
$exchUri = "$($exchUri)?DelegatedOrg=$($TenantName)"
}
Write-Host -ForegroundColor Cyan "Connect to Exchange Online"
Write-Host "Uri: $exchUri "
$global:ExoSession = New-PSSession -ConfigurationName Microsoft.Exchange
-ConnectionUri $exchUri -Credential $Credentials -Authentication Basic
-AllowRedirection -Verbose <#:$VerbosePreference #>
Import-PSSession $global:ExoSession -DisableNameChecking -Verbose #:$VerbosePreference | Out-Null
In the preceding code example, you can see that several pieces have been commented out. This is to make the code produce output that will help you understand how it works. You could incorporate the code into a PowerShell function, and re-enable these parts to hide the output except for when you need it for debugging purposes and so on.
Here's the entire command sequence in action:
To get a full list of available commands you can run Get-Command and feed it the temporary name of the module as shown in the following command:
Get-Command -Module tmp_4m3pgtnt.aa0
The list is quite long, so it won't be shown here. The Import-PSSession command creates a module object, so you can also modify the previous example to grab this object's Name property directly, rather than using copy and paste.
Now that you're connected, you can use commands such as Get-Mailbox and Get-MailUser. We'll cover these in detail during Chapter 4, Administering Exchange Online – Essentials.