How to run PowerShell scripts from C#

断了今生、忘了曾经 提交于 2019-12-05 12:56:46
JaredReisinger

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.)

MatthewMartin

Here is method b, that doesn't require elevated rights or Registry modification rights.

Using Process.Start launch this and add the relevant initial -command or -file args.

%SystemRoot%\system32\WindowsPowerShell\v1.0\powershell.exe -ExecutionPolicy bypass

Here is another technique, http://dmitrysotnikov.wordpress.com/2008/06/27/powershell-script-in-a-bat-file/

That relies on executing by encoding it first and passing int through the -EncodedCommand arg of powershell.exe, which appears to bypass execution policy.

MethodMan

You could try something like the following

using ( new Impersonator( "Username", "DomainName", "Password" ) )
{
    using (RunspaceInvoke invoker = new RunspaceInvoke())
    {
        invoker.Invoke("Set-ExecutionPolicy Unrestricted");
    }
}

Here is a link you can look at to get an idea as an example, Class For Impersonating a User.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!