title: How to run PowerShell from C# as administrator?
body: <p>I want to execute some PowerShell script through C# but it requires admin privilege. This is my code (I got it <a href="https://stackoverflow.com/questions/1313673/execute-powershell-as-an-administrator-from-c-sharp">here</a>):</p>
  
  <pre><code>using (new Impersonator("user", "domain", "password"))
  {
      // create Powershell runspace
      Runspace runspace = RunspaceFactory.CreateRunspace();
  
      // open it
      runspace.Open();
  
      // create a pipeline and feed it the script text
      Pipeline pipeline = runspace.CreatePipeline();
      pipeline.Commands.AddScript(scriptText);
  
      // add parameters if any
      foreach (var parameter in parameters)
      {
          pipeline.Commands[0].Parameters.Add(parameter.Key, parameter.Value);
      }
  
      // add an extra command to transform the script
      // output objects into nicely formatted strings
  
      // remove this line to get the actual objects
      // that the script returns. For example, the script
  
      // "Get-Process" returns a collection
      // of System.Diagnostics.Process instances.
      pipeline.Commands.Add("Out-String");
  
      // execute the script
      Collection&lt;PSObject&gt; results = pipeline.Invoke();
  
      // close the runspace
      runspace.Close();
  
      // convert the script result into a single string
      StringBuilder stringBuilder = new StringBuilder();
      foreach (PSObject obj in results)
      {
          stringBuilder.AppendLine(obj.ToString());
      }
  
      return stringBuilder.ToString();
  }
  </code></pre>
  
  <p>Anyway, this doesn't work on my machine. For example, if the script text is "<code>Set-ExecutionPolicy Unrestricted</code>" then I get "<code>Access to the registry key 'HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\PowerShell\1\ShellIds\Microsoft.PowerShell' is denied.</code>"</p>
  
  <p>And in my case, it cannot get list of virtual machines through <code>Get-VM</code> command. (I found that <code>Get-VM</code> only return results if it runs under Admin privilege.)</p>
  
  <p>Do I do something wrong? Is there another solution for this problem?</p>