MVC Controller with Runspace Impersonation
Asked Answered
Q

1

2

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.

Quillan answered 1/2, 2012 at 12:28 Comment(4)
Is there any reason you can't rewrite the script as a library? It might be easier and more maintainable in the end.Euchologion
The idea is that different commands will be used, the above is a simplified version of what I'm doing.Quillan
@Quillan - when you say "the Application is crashing out" what error message are you getting? The same one?Gusti
Thats just it there's no error at all, the application just disappears from screen. Tried capturing with DebugDiag but get nothing, the capture rule doesn't fire.Quillan
Q
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)
Quillan answered 7/2, 2012 at 4:9 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.