我尝试从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。


当前回答

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

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

Set-ExecutionPolicy -Scope CurrentUser -ExecutionPolicy Unrestricted

其他回答

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

Set-ExecutionPolicy RemoteSigned

我认为您可以在管理模式或命令提示符下使用powershell。

在管理员模式下打开windows powershell并运行以下命令,它的工作VOILA!!

Set-ExecutionPolicy RemoteSigned

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

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

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

关闭当前命令提示符或vs code(终端) 在管理模式下打开PowerShell 在PowerShell中运行此命令 Set-ExecutionPolicy -Scope CurrentUser -ExecutionPolicy无限制 回答Y或A(如果你想让所有用户访问) 现在打开命令提示符或vs code或任何你喜欢的来运行你的项目