How to run PowerShell scripts from C#

Question:

I am trying to run a PowerShell script with C#, but I don’t have any success. Here is my function:

This is the error I get:

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

How can I solve this issue? I have seen ideas for impersonation, but I didn’t seem to find any good examples to impersonate. I would like to run this script as an administrator.

I have made the following declarations:

I have created the following function for impersonation:

I have created a function which is used as a delegate:

And I have modified my method:

The result was…

… the very sam error, telling me I can’t access registry keys.

Answer:

The default Set-ExecutionPolicy command attempts to set the machine-wide value. You only want to change the setting within the scope of your C# application, so you should add the -Scope Process option to the command.

Using Get-Help Set-ExecutionPolicy -detailed reveals this information:

NOTE: To change the execution policy for the default (LocalMachine) scope, start Windows PowerShell with the “Run as administrator” option.

… and it also describes the -Scope option.

This has the advantage of only impacting the execution policy for scripts run from your C# application, and it doesn’t unnecessarily change the execution policy for the default PowerShell behavior. (So it’s a lot safer, especially if you can make guarantees about the validity of the scripts your application runs.)

Source:

How to run PowerShell scripts from C# by licensed under CC BY-SA | With most appropriate answer!

Leave a Reply