Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Execute PowerShell as an administrator from C#

Tags:

c#

powershell

I have the following C# code

using (RunspaceInvoke invoker = new RunspaceInvoke())
{
  invoker.Invoke("Set-ExecutionPolicy Unrestricted");
  // ...
}

which gives me the exception

Access to the registry key 'HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\PowerShell\1\ShellIds\Microsoft.PowerShell' is denied.

According to this, the solution is to start PowerShell as an administrator.

Ordinarily, this can be accomplished by right-clicking PowerShell and selecting "Run as Administrator". Is there a way to do this programmatically?

like image 630
Emmett Avatar asked Aug 21 '09 18:08

Emmett


People also ask

How do I Run a ps1 as administrator?

Open the task manager by using the shortcut keys Ctrl+Alt+Del. Explore the File tab and Run a new task by clicking on the option given. In the PowerShell type the same command start-process PowerShell -verb runas and hit enter to run it as administrator.

Can you launch PowerShell from CMD?

You actually need to invoke PowerShell from Command Prompt to launch a different PowerShell window. To do so, type or paste powershell start-process powershell -verb runas into Command Prompt, and then hit Enter. A new elevated PowerShell window will appear.


1 Answers

I know this is an old post, but we ran into this same problem recently.

We had to scope the execution policy on the machine running the C# code by running the following from PowerShell...

Set-ExecutionPolicy -Scope CurrentUser -ExecutionPolicy Unrestricted

When we had done this previously, without scoping, we were setting the execution policy for Administrator. Visual Studio \ C# was running as the current user, causing it to fail with insufficient permissions.

like image 187
BradleyMorgan Avatar answered Sep 20 '22 08:09

BradleyMorgan