PowerShell module not found when running as a serv

2019-07-15 22:07发布

问题:

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:

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