从C#启用PowerShell的执行策略

时间:2012-11-16 16:43:13

标签: 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();
        }
    }

谢谢, 人

5 个答案:

答案 0 :(得分:7)

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

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

答案 1 :(得分:1)

这与@ kravits88答案相同,但没有显示cmd:

static void runPowerShellScript(string path, string args) {
        ProcessStartInfo startInfo = new ProcessStartInfo();
        startInfo.FileName = "cmd.exe";
        startInfo.Arguments = @"/c powershell -executionpolicy unrestricted " + path + " " + args;
        startInfo.UseShellExecute = false;
        startInfo.WindowStyle = ProcessWindowStyle.Hidden;
        startInfo.CreateNoWindow = true;
        Process process = new Process();
        process.StartInfo = startInfo;
        process.Start();
    }

答案 2 :(得分:1)

您必须使用参数-Scope = CurrentUser:

  powershell.AddCommand("Set-ExecutionPolicy").AddArgument("Unrestricted")
    .AddParameter("Scope","CurrentUser");

答案 3 :(得分:0)

我的解决方案是自我签署从IIS Express运行的模块和脚本。我还在开发中,发现IIS Express没有看到你可能已安装在\ System32 \ WindowsPowerShell ... \ Modules路径中的所有模块。我将我正在使用的模块移动到另一个驱动器,并使用该位置将模块导入到我的脚本中。

感谢您的回复: - )

答案 4 :(得分:0)

对于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()
     }
}