tags:

views:

749

answers:

2

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?

+6  A: 

Check this out

You need to impersonate as an administrator to do it (you will of course need administrator credentials)

Check that article, that also comes with code ready to use (I've used it and it works great)

Basically, you need to do this:

using ( new Impersonator( "myUsername", "myDomainname", "myPassword" ) )
{
    using (RunspaceInvoke invoker = new RunspaceInvoke())
    {
        invoker.Invoke("Set-ExecutionPolicy Unrestricted");
    }
}
Juan Manuel
+2  A: 

Administrative privileges are at the application level. The app that needs admin access in this case is yours. Creating runspaces in C# in a custom app does not invoke powershell the application - it just loads some assemblies into your application.

That said, you can elevate as the other poster said although embedding admin usernames and passwords into source code make me feel ill.

-Oisin

x0n
It doesn't have to ho into the source code, my snippet is just an example
Juan Manuel