'New-ExoPSSession: Index was out of range

Im developing a script that connects to Exchange Online Microsoft 365, but when the script executes the cmdlet "Connect-ExchangeOnline", it ends with errors.

The specific instruction is:

Connect-ExchangeOnline -Organization $myTenant -AppId $AppId -Certificate $myCert

The variables in the parameters are correct, the error says:

New-ExoPSSession: Index was out of range. Must be non-negative and less than the size of the collection. Parameter name: index

I can load the module succesfully. The script connects to Exchange Online trough a cert installed in my machine, my script can read it without issues.

I'm running this script in Powershell V4 and .Net Framework 4.7.1. If i execute the same script in another machine with PowerShell V5.1 I can connect to Microsoft 365 Exchange Online succesfully. I tried with a lower version (ExchangeOnlineManagement 1.0.1) but this version hasn't got those parameters (Organization, AppId, etc...), I'm now using 2.0.3 version. I not sure if you can upgrade Powershell to 5.1.

Does anyone know why i can't connect to Exchange Online?



Solution 1:[1]

EXO V2 is only supported on PowerShell 5.1 and later. If you want to use PowerShell 4.0 you will have to use EXO V1.

I'm not familiar enough with the EXO module to how or whether you can use EXO V1 in your current environment. If V2 is required for modern Exchange Online management then you will need to upgrade your nodes to use WMF 5.1 or install PowerShell Core (7+) and use EXO V2 from there.

PowerShell Core installs in parallel to Windows PowerShell so there is less of a risk of impacting other code which requires PowerShell 4.0 if you go this route.

Solution 2:[2]

I've been struggling with this issue, and I finally found a solution.
Turns out running Import-Module ExchangeOnlineManagement before Connect-ExchangeOnline causes this error.
Removing Import-Module ExchangeOnlineManagement was enough to allow Connect-ExchangeOnline to connect without the New-ExoPSSession: Index was out of range error

Solution 3:[3]

I am using Windows PowerShell 5.1 and this seems to be an issue that's introduced in ExchangeOnlineManagement version 2.0.4.

Downgrading to 2.0.3 worked for me.

Solution 4:[4]

PowerShell needs to be started in elevated mode. However, my error was caused by RunAs with a domain admin account. Using RunAs with a local admin account works. YMMV.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Bender the Greatest
Solution 2 az1d
Solution 3 tyteen4a03
Solution 4