Question

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.

Was it helpful?

Solution

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)
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top