Posted On December 5, 2019

PowerShell: Connect to Office 365 Exchange Online

kimconnect 0 comments
blog.KimConnect.com >> Codes >> PowerShell: Connect to Office 365 Exchange Online
function disconnectExchangeOnline{
<# manually check sessions
PS C:\Windows\system32> Get-PSSession

Id Name ComputerName ComputerType State ConfigurationName Availability
-- ---- ------------ ------------ ----- ----------------- ------------
4 WinRM4 outlook.offi... RemoteMachine Opened Microsoft.Exchange Available
5 WinRM5 outlook.offi... RemoteMachine Opened Microsoft.Exchange Available
#>
$activeExchangeOnlineSessionIds=(Get-PSSession |?{$_.ConfigurationName -eq "Microsoft.Exchange"}).Id
if($activeExchangeOnlineSessionIds){
Remove-PSSession -id $activeExchangeOnlineSessionIds;
write-host "session ID $activeExchangeOnlineSessionIds is disconnected."
}
}

function connectToExchangeOnline{
param(
$credential=(get-credential),
$connectionURI="https://outlook.office365.com/powershell-liveid/"
)
#Disconnect any active sessions prior to initiating a new one
disconnectExchangeOnline;

if (!($activeExchangeOnlineSessionIds)){
#Imports the base MSOnline module
if (!(Get-Module -ListAvailable -Name MSOnline)){Install-Module MSOnline -Confirm:$false -Force;}

$GLOBAL:onlineExchangeSession = New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri $connectionURI -Credential $credential -Authentication Basic -AllowRedirection
Import-PSSession $onlineExchangeSession -AllowClobber -DisableNameChecking
}else{
write-host "An active session is already available. No new connections were made."
}
}

connectToExchangeOnline;

Leave a Reply

Your email address will not be published. Required fields are marked *

Related Post

PowerShell Commands to Discover the Server Network, Netmask, DHCP status, and Gateway

$servername = "SERVER01"get-wmiobject win32_networkadapterconfiguration -computername $servername -ea stop | ? {$_.IPEnabled}# Result:DHCPEnabled      :…

Basic CSS: Specify How Fonts Should Degrade

<link href="https://fonts.googleapis.com/css?family=Lobster" rel="stylesheet" type="text/css"><style>.red-text {color: red;}h2 {font-family: Lobster;}p {font-size: 16px;font-family: monospace;}</style><h2 class="red-text">CatPhotoApp</h2><main><p class="red-text">Click here to…

PowerShell: How To Disable and/or Stop Windows Service

Disable and Stop Using Native Command 'Set-Service' # To disable service as well as stopping…