MVC Controller with Runspace Impersonation

夙愿已清 提交于 2019-12-10 23:29:16

问题


Trying to execute a Powershell cmdlet from a MVC 3 Controller using impersonation but keep receiving an "Requested registry access is not allowed." exception when calling Runspace.Open()

StringBuilder stringBuilder = new StringBuilder();   

RunspaceConfiguration rsConfig = RunspaceConfiguration.Create();

using (new Impersonator("username", "domain", "password"))
{
    Runspace runspace = RunspaceFactory.CreateRunspace(rsConfig);

    runspace.Open();

    Pipeline pipeLine = runspace.CreatePipeline();

    string script = "get-process";
    pipeLine.Commands.AddScript(script);

    Collection<PSObject> commandResults = pipeLine.Invoke();                

    foreach (PSObject obj in commandResults)
    {
        stringBuilder.AppendLine(obj.Properties["ProcessName"].Value.ToString());
    }

Debugging shows the registry error is due to a Registry Key Read being attempted on HKCU\Environment. Running the above with no impersonation works successfully.

Note: Impersonation class was found here: http://platinumdogs.wordpress.com/2008/10/30/net-c-impersonation-with-network-credentials/

Any ideas on why this is happening or what can be done to resolve it?

UPDATE:

After getting some sleep I reasoned that moving the Runspace.Open() above the impersonation line would allow the runspace to access the required registry data (Environment Variables) and this indeed helped.

Now the code works fine with the built in cmdlets but when I load "Microsoft.Exchange.Management.PowerShell.Admin" and try any of the Exchange Cmdlets the Application is crashing out.


回答1:


Success!

In the event this is useful to someone else here's how I got it to work:

  1. Install the Exchange management tools
  2. Apply latest service pack
  3. Ensure you add a parameter for the Domain Controller (Microsoft - KB943937)


来源:https://stackoverflow.com/questions/9095803/mvc-controller-with-runspace-impersonation

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