Actually, in relation to my Feb 21 2021 07:45 PM question. The issue may not be caused by the import-module. It seems the old connection method used in the web app ( using WSManConnectionInfo) had similar connection delays (around 12 seconds for an initial connection) but somehow the connection was being cached so subsequent "connection" calls were much faster (~10x). Apparently that's just not happening for me with the new method as subsequent calls all still take over 12 seconds.
I am using:
==========
InitialSessionState initSession = InitialSessionState.CreateDefault();
initSession.ImportPSModule(new[] { "ExchangeOnlineManagement" });
Runspace rs = RunspaceFactory.CreateRunspace(initSession);
rs.Open();
using (PowerShell session = PowerShell.Create())
{
session.Runspace = rs;
session.AddCommand("Connect-ExchangeOnline");
session.AddParameter("CommandName", cmdlet.CommandText); // optimise load time by limiting cmds
session.AddParameter("CertificateThumbprint", ActiveDirectory.O365OAuth2CertificateThumbprint);
session.AddParameter("AppID", ActiveDirectory.O365OAuth2AppID);
session.AddParameter("Organization", ActiveDirectory.O365OAuth2Organization);
if (ActiveDirectory.O365RemotePSConnectionUseIEConfigProxy == "Y")
{
session.AddParameter("PSSessionOption", new PSSessionOption() { ProxyAccessType = ProxyAccessType.IEConfig });
}
session.Invoke();
session.Commands.Clear();
session.AddCommand(cmdlet);
output = session.Invoke();
}