Function for connecting to an Exchange Online session. Useful in a PowerShell profile script.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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