Skip to content

Instantly share code, notes, and snippets.

@shinjijai
Last active April 24, 2018 16:58
Show Gist options
  • Save shinjijai/c0aef8ac1fb5b1328d43184f8f410c6b to your computer and use it in GitHub Desktop.
Save shinjijai/c0aef8ac1fb5b1328d43184f8f410c6b to your computer and use it in GitHub Desktop.
Function that'll connect to either on premise Exchange or Office 365 Exchange
#Requires -Version 4.0
#Requires -modules ActiveDirectory
function Connect-Exchange {
[CmdletBinding()]
param(
[Parameter(Mandatory=$true,
HelpMessage="User admin credentials")]
[System.Management.Automation.PSCredential]$Credential,
[Parameter(Mandatory=$false)]
$URI = "https://outlook.office365.com/powershell-liveid/",
[Parameter(Mandatory=$false)]
[Bool]$Online=$false,
[Parameter(Mandatory=$false)]
[String]$Prefix = ""
)
if($Online) { #Office 365
$ExchangeOptions = @{
ConfigurationName = "Microsoft.Exchange"
ConnectionUri = $URI
Authentication = "Basic"
Credential = $Credential
}
$ExcName = "Office 365"
$ExcFound = $true
}
else { #On premise
$ExcServerList = Get-ADGroupMember -Identity "Exchange Servers" | Where-Object {$_.objectClass -eq "computer"}
if($ExcServerList -is [Array]) {
Format-Displaylist -ArrayList $ExcServerList -DisplayName
$ServerSelect = Get-UserInput -DisplayText "Select the Exchange server you want to connect to" -intSearch -boundSearch $ExcServerList.Count
$ExcServer = $ExcServerList[$ServerSelect - 1]
$ExcFound = $true
}
elseif($ExcServerList -ne $null) {
$ExcServer = $ExcServerList
$ExcFound = $true
}
else {
$ExcFound = $false
}
if($ExcFound) {
$ExcName = $ExcServer.Name
$ExchangeOptions = @{
ConfigurationName = "Microsoft.Exchange"
ConnectionUri = "http://$ExcName/PowerShell"
Authentication = "Kerberos"
Credential = $Credential
}
}
}
if($ExcFound) {
Write-Host "Connecting to $ExcName..." -NoNewline
$Session = New-PSSession @ExchangeOptions
$PSSessionOptions = @{
Session = $Session
DisableNameChecking = $true
AllowClobber = $true
}
$ModuleOptions = @{
Global = $true
DisableNameChecking = $true
}
if($Prefix -ne "") {
$ModuleOptions.Add("Prefix",$Prefix)
}
Import-Module (Import-PSSession @PSSessionOptions) @ModuleOptions | Out-Null
Write-Host "done."
}
else {
Write-Host "Could not find an Exchange server on the domain. Exiting."
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment