从C#启用PowerShell的执行策略

alb*_*bal 1 c# powershell

我有一个MVC4页面,它调用了一个powershell.但是我遇到了问题,因为我使用的模块没有签名,所以我必须启用Unrestricted策略.如何强制powershell child使用Unrestricted Policy.我在我的脚本中启用了它,但它被忽略了.此外,当我尝试在代码中设置策略时,会抛出异常.

    using (Runspace myRunSpace = RunspaceFactory.CreateRunspace())
    {
        myRunSpace.Open();

        using (PowerShell powerShell = PowerShell.Create())
        {
            powerShell.Runspace = myRunSpace;
            powerShell.AddCommand("Set-ExecutionPolicy").AddArgument("Unrestricted");
            powerShell.AddScript(script);

            objectRetVal = powerShell.Invoke();
        }
    }
Run Code Online (Sandbox Code Playgroud)

谢谢,Al

Jac*_*ult 15

对于 PowerShell 5.1 和 PowerShell 7 Core,您可以使用ExecutionPolicy Enum来设置执行策略,如下所示:

using Microsoft.PowerShell;
using System.Management.Automation;
using System.Management.Automation.Runspaces;
...
public class MyClass
{
     public void MyMethod() 
     {
          // Create a default initial session state and set the execution policy.
          InitialSessionState initialSessionState = InitialSessionState.CreateDefault();
          initialSessionState.ExecutionPolicy = ExecutionPolicy.Unrestricted;

          // Create a runspace and open it. This example uses C#8 simplified using statements
          using Runspace runspace = RunspaceFactory.CreateRunspace(initialSessionState);
          runspace.Open();

          // Create a PowerShell object 
          using PowerShell powerShell = PowerShell.Create(runspace);

          // Add commands, parameters, etc., etc.
          powerShell.AddCommand(<command>).AddParameter(<parameter>);

          // Invoke the PowerShell object.
          powerShell.Invoke()
     }
}
Run Code Online (Sandbox Code Playgroud)


kra*_*s88 8

如果您只需要在没有交互的情况下运行一个脚本,则可以通过命令提示符设置执行策略,如下所示:

string command = "/c powershell -executionpolicy unrestricted C:\script1.ps1";
System.Diagnostics.Process.Start("cmd.exe",command);
Run Code Online (Sandbox Code Playgroud)


小智 5

您必须使用参数 \xef\xbc\x8dScope = CurrentUser:

\n\n
  powershell.AddCommand("Set-ExecutionPolicy").AddArgument("Unrestricted")\n    .AddParameter("Scope","CurrentUser");\n
Run Code Online (Sandbox Code Playgroud)\n