从 C# 启用 PowerShell 的执行策略 [英] Enabling execution policy for PowerShell from C#

查看:33
本文介绍了从 C# 启用 PowerShell 的执行策略的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个调用 PowerShell 的 ASP.NET MVC 4 页面.但是,我遇到了一个问题,因为我使用的模块没有签名,所以我必须启用 Unrestricted 策略.如何强制 PowerShell 子级使用 Unrestricted 策略?

I have an ASP.NET MVC 4 page that calls a piece of PowerShell. However, I am running into a problem as a module I am using is not signed, so I have to enable the Unrestricted policy. How can I force the PowerShell child to use Unrestricted policy?

我在我的脚本中启用了它,但它被忽略了.此外,当我尝试在代码中设置策略时,会引发异常.

I have enabled this in my script, but it is ignored. Also when I try to set the policy in code, an exception is thrown.

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

推荐答案

如果您只需要运行一个脚本而无需交互,您可以通过命令提示符设置执行策略,如下所示:

If you only need to run the one script with no interactions you can set the execution policy via the command prompt like so:

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

这篇关于从 C# 启用 PowerShell 的执行策略的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆