Attempting to execute New-CsOnlineSession returns: “The remote server returned an error: (502) Bad Gateway.”

Problem

Attempting to use New-CsOnlineSession to create a persistent connection to Microsoft Skype for Business Online for Microsoft Teams management fails with the following error:

PS C:WINDOWSsystem32> $Session = New-CsOnlineSession -UserName tluk@contoso.com

Get-CsOnlinePowerShellEndpoint : The remote server returned an error: (502) Bad Gateway.

At C:Program FilesCommon FilesSkype for Business

OnlineModulesSkypeOnlineConnectorSkypeOnlineConnectorStartup.psm1:149 char:26

+ … targetUri = Get-CsOnlinePowerShellEndpoint -TargetDomain $adminDomain …

+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

+ CategoryInfo : NotSpecified: (:) [Get-CsOnlinePowerShellEndpoint], WebException

+ FullyQualifiedErrorId : System.Net.WebException,Microsoft.Rtc.Management.OnlineConnector.GetPowerShellEndpointCm

dletPS C:WINDOWSsystem32>

179

Solution

One of the reasons why this type of error would be thrown is if there is an existing on-premise Skype for Business deployment for the SIP domain that was provided to the -Username parameter and there are DNS records that point the domain to the on-premise deployment. This would also be the same if there is a Skype for Business configured in a hybrid environment because the external DNS records would also point to the on-premises infrastructure.

There are 2 ways to get around this problem:

Option #1 – Log on with an onmicrosoft.com account

Every Office 365 tenant has the onmicrosoft.com domain configured and has an global admin account created with this domain upon the tenant creation. Using an account from this domain will get around the error:

$Session = New-CsOnlineSession -UserName admin@ccsbm.onmicrosoft.com

Option #2 – Use the OverrideAdminDomain parameter to direct the session to connect to the correct Office 365 Tenant

Another way around this is to use the OverrideAdminDomain switch to direct the session to connect to the correct Office 365 tenant as shown in the following cmdlet:

$Session = New-CsOnlineSession -UserName <AdministratorUPN> -OverrideAdminDomain <TenantName>.onmicrosoft.com

The following is an example:

$Session = New-CsOnlineSession -UserName tluk@ccs.bm -OverrideAdminDomain ccsbm.onmicrosoft.com