PowerShell module not found when running as a service

ぐ巨炮叔叔 提交于 2019-12-12 16:50:28

问题


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.



来源:https://stackoverflow.com/questions/15091392/powershell-module-not-found-when-running-as-a-service

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!