我尝试从c#运行powershell脚本。

首先,我将ExecutionPolicy设置为无限制,脚本现在从PowerShell ISE运行。

这是我的c#代码:

class Program
{
    private static PowerShell ps;
    static void Main(string[] args)
    {
        ps = PowerShell.Create();
        string ps1File = Path.Combine(Environment.CurrentDirectory, "script.ps1");
        ExecuteScript(ps1File);
        Console.ReadLine();
    }

    static void ExecuteScript(string script)
    {
        try
        {
            ps.AddScript(script);
            Collection<PSObject> results = ps.Invoke();
            Console.WriteLine("Output:");
            foreach (var psObject in results)
            {
                Console.WriteLine(psObject);
            }
            Console.WriteLine("Non-terminating errors:");
            foreach (ErrorRecord err in ps.Streams.Error)
            {
                Console.WriteLine(err.ToString());
            }
        }
        catch (RuntimeException ex)
        {
            Console.WriteLine("Terminating error:");
            Console.WriteLine(ex.Message);
        }
    }
}

输出为:

Ps1无法加载,因为在此上禁用了运行脚本 系统。要了解更多信息,请参阅about_Execution_Policies at http://go.microsoft.com/fwlink/?LinkID=135170。


当前回答

在管理模式下打开powershell 并执行以下命令

Set-ExecutionPolicy RemoteSigned

其他回答

PowerShell的执行策略默认为“受限”。您可以使用Set-ExecutionPolicy cmdlet来更改PowerShell的执行策略。要运行外部脚本,请将policy设置为remotessigned。

PS C:> Set-ExecutionPolicy remotessigned 下面是PowerShell中四种不同执行策略的列表

受限-不允许运行脚本。 AllSigned -只有经过可信发布者签名的脚本才能运行。 remotessigned -下载的脚本必须由可信的发布者签名。 无限制-所有Windows PowerShell脚本都可以运行。

这可能是由于当前用户有一个未定义的ExecutionPolicy。

在PowerShell中作为管理员,您可以尝试以下操作:

Set-ExecutionPolicy -Scope CurrentUser -ExecutionPolicy Unrestricted

在管理模式下打开PowerShell并运行以下命令

Set-ExecutionPolicy -Scope CurrentUser -ExecutionPolicy Unrestricted

进入系统设置->更新和安全->开发人员-> PowerShell

应用以下选项

打开VS Code终端,运行以下脚本:

Set-ExecutionPolicy -Scope CurrentUser -ExecutionPolicy Unrestricted