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.

ServerMonkey
  • 1,042
  • 3
  • 19
  • 42
  • Is there any reason you can't rewrite the script as a library? It might be easier and more maintainable in the end. – jrummell Feb 01 '12 at 21:27
  • The idea is that different commands will be used, the above is a simplified version of what I'm doing. – ServerMonkey Feb 01 '12 at 22:18
  • @ServerMonkey - when you say "the Application is crashing out" what error message are you getting? The same one? – MrKWatkins Feb 02 '12 at 10:17
  • 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. – ServerMonkey Feb 02 '12 at 20:27

1 Answers1

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)
ServerMonkey
  • 1,042
  • 3
  • 19
  • 42