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

Some Useful Windows Commands to Troubleshoot Networking on Windoze

# Check this computer's trust relationship to its domain controllers$domainName="intranet.kimconnect.com"PS C:\Windows\system32> nltest /SC_QUERY:$domainNameFlags: 0Trusted DC…

Windows UAC Error This App has been blocked for your protection mmc.exe taskschd.msc

Error Message: User Account ControlThis App has been blocked for your protection.A administrator has blocked…

ARP MAC to IP Resolution

If entry already exists on the ARP table:arp -a | find "XX-XX-XX-XX-XX-XX"If entry does not…