3
votes

I have a project where I assign Office 365 licenses to users. There is a web project that allows the administrators to view the available licenses and choose a license for a user. In the background, there is a service which performs the actual license assignment (and many other tasks) every 15 minutes. The reason why we don't assign the licenses directly is that a user may not have been synchronized to Office 365 yet. The service automatically tries again later if the DirSync hasn't run yet.

Back to my problem: The connection to Office 365 is using the PowerShell module "MSOnline". The problem is that this module can't be loaded by the service. I always get the standard error message:

The specified module 'MSOnline' was not loaded because no valid module file was found in any module directory.

The web application doesn't have this problem. It connects and can retrieve the available licenses, for example. If I use the code from the service application in LINQPad or as a small standalone executable, everything works fine, too. Only the service can't load the module. Can anyone help me?

The following code snippet is used by both, web application and service, to connect to Office 365 (code is simplified to increase readability).

var iss = InitialSessionState.CreateDefault();

iss.ThrowOnRunspaceOpenError = true;
iss.AuthorizationManager = new AuthorizationManager("MyPowerShellInvoker");

iss.ImportPSModule("MSOnline");

_runspace = RunspaceFactory.CreateRunspace(iss);
_runspace.Open();
_invoker = new RunspaceInvoke(_runspace);

using (Pipeline pipeline = _runspace.CreatePipeline())
{
    var cmd = new Command("Connect-MsolService");
    cmd.Parameters.Add("Credential", /* PSCredential object */);

    pipeline.Commands.Add(cmd);
    pipeline.Invoke();
}

P.S.: The service is running under the "Local System" account.

1
Does your PSModulePath environment variable includes the path where your MSOnline module sits?David Brabant
@DavidBrabant Unfortunately yes, the PSModulePath is correct. It's the same value for web application and service.fero
Is you service running as 32 bits or 64 bits target. It may have some infuence.JPBlanc
So I put it as an answer.JPBlanc

1 Answers

2
votes

Is your service running as 32 bits or 64 bits target. I met the 32/64 problem in multiple cases.