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

其他回答

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

我得到这个错误:

 ng : File C:\Users\Nisha Jain\AppData\Roaming\npm\ng.ps1 cannot be loaded 
 because running scripts is disabled on this system. For more        
 information, see about_Execution_Policies at https:/go.microsoft.com/fwlink/? 
 LinkID=135170.
   At line:1 char:1
   + ng serve
   + ~~
    + CategoryInfo          : SecurityError: (:) [], PSSecurityException
    + FullyQualifiedErrorId : UnauthorizedAccess

只要删除这个文件ng.ps1

   Path is : C:\Users\username\AppData\Roaming\npm\ng.ps1

这对我来说很有效。

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

Set-ExecutionPolicy RemoteSigned

打开windows powershell或cmd并粘贴以下命令。如果需要进一步确认,只需输入YesSet-ExecutionPolicy -Scope CurrentUser -ExecutionPolicy remotessigned

如下图所示

`Execution Policy Change

执行策略有助于保护您不受不信任脚本的影响。更改执行策略可能会暴露 请注意about_Execution_Policies帮助主题中描述的安全风险 https: / go.microsoft.com/fwlink/ ? LinkID = 135170。是否要更改执行策略? [Y]是[A]全部是[N]否[L]全部不是[S]暂停[?]帮助(默认为“N”):是 PS C:\Users\ Tessact01 >”

最近,当我试图在netlify上部署一个应用程序时,我遇到了同样的问题:在这个系统上运行-scripts-is-disabled-on-this-system

下面cmd对我有用。

Set-ExecutionPolicy -ExecutionPolicy Bypass -Scope CurrentUser