Skip to content

Instantly share code, notes, and snippets.

@davegreen
Last active April 12, 2018 13:00
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save davegreen/93a7a6d54652ac36ea7f to your computer and use it in GitHub Desktop.
Function for connecting to an Exchange Online session. Useful in a PowerShell profile script.
function Connect-ExchangeOnline {
<#
.Synopsis
A function that connects to the Exchange online system.
.Parameter Credential
A credential object with rights to connect to the Exchange server. This parameter is mandatory.
.Parameter AllowClobber
Boolean value of whether the imported session will clobber existing commands. Defaults to True.
.Parameter Prefix
Use this switch to prefix 'EOL' onto any imported cmdlets for Exchange Online.
This switch will prefix 'Compliance' onto imported cmdlets for the Compliance centre.
.Example
Connect-ExchangeOnline
Asks for credentials and connects to Exchange Online.
.Example
$mycreds = Get-Credential
Connect-ExchangeOnline -Credential $mycreds
Connects to Exchange Online with the credentials in $mycreds.
.Notes
Author: David Green
#>
[CmdletBinding()]
Param (
[Parameter(Mandatory)]
[PSCredential]
$Credential,
[Parameter(
ParameterSetName = 'Prefix'
)]
[switch]
$Prefix,
[Parameter()]
[ValidateSet(
'EOL',
'Compliance'
)]
[string]
$Connection = 'EOL'
)
$Uri = switch ($Connection) {
'EOL' { 'https://outlook.com/powershell-liveid' }
'Compliance' { 'https://ps.compliance.protection.outlook.com/powershell-liveid/' }
}
try {
$Splat = @{
ConfigurationName = 'Microsoft.Exchange'
ConnectionUri = $Uri
Credential = $Credential
Authentication = 'basic'
AllowRedirection = $true
}
if ($Prefix) {
$Splat.Add('Prefix', $Connection)
}
$null = Import-Module (Import-PSSession (New-PSSession @Splat)) -Global -ErrorAction Stop
}
catch {
Write-Error "Cannot connect or invalid credentials. Please try again."
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment