225

我运行此代码以从 ASP.NET 应用程序执行 PowerShell 代码:

System.Management.Automation.Runspaces.Runspace runspace = System.Management.Automation.Runspaces.RunspaceFactory.CreateRunspace();
runspace.Open();
System.Management.Automation.Runspaces.Pipeline pipeline = runspace.CreatePipeline();
pipeline.Commands.AddScript(@"\\servername\path");

pipeline.Commands.Add("Out-String");

Collection<PSObject> results = pipeline.Invoke();

runspace.Close();

但我收到一个错误:

.ps1 无法加载,因为在此系统上禁用了脚本的执行。有关更多详细信息,请参阅“get-help about_signing”。

相同的代码在命令提示符或 Windows(Windows 窗体)应用程序中运行良好。

4

5 回答 5

392

由于执行策略,您的脚本被阻止执行。

您需要以管理员身份运行 PowerShell 并将其在客户端 PC 上设置为无限制。您可以通过调用 Invoke 来做到这一点:

Set-ExecutionPolicy Unrestricted
于 2013-05-09T11:01:44.717 回答
144

在某些情况下,您可以按照其他答案中建议的步骤进行操作,验证执行策略是否设置正确,但脚本仍然会失败。如果您遇到这种情况,您可能在 64 位计算机上同时安装了 32 位和 64 位版本的 PowerShell,而故障发生在没有设置执行策略的版本上。该设置不适用于两个版本,因此您必须明确设置两次。

在 Windows 目录中查找 System32 和 SysWOW64。

对每个目录重复这些步骤:

  1. 导航到 WindowsPowerShell\v1.0 并启动 powershell.exe

  2. 检查 ExecutionPolicy 的当前设置:

    Get-ExecutionPolicy -List

  3. 为您想要的级别和范围设置 ExecutionPolicy,例如:

    Set-ExecutionPolicy -Scope LocalMachine Unrestricted

请注意,您可能需要以管理员身份运行 PowerShell,具体取决于您尝试为其设置策略的范围。

于 2014-04-08T22:01:10.357 回答
49

问题是执行策略是基于每个用户设置的。每次运行应用程序时,您都需要在应用程序中运行以下命令以使其正常工作:

Set-ExecutionPolicy -Scope Process -ExecutionPolicy RemoteSigned

可能还有一种方法可以为 ASP.NET 用户设置它,但是这种方法意味着您不会打开整个系统,而只是打开您的应用程序。

来源

于 2013-05-09T11:47:02.670 回答
49

你需要运行Set-ExecutionPolicy

Set-ExecutionPolicy Unrestricted <-- Will allow unsigned PowerShell scripts to run.

Set-ExecutionPolicy Restricted <-- Will not allow unsigned PowerShell scripts to run.

Set-ExecutionPolicy RemoteSigned <-- Will allow only remotely signed PowerShell scripts to run.
于 2013-11-14T10:13:42.287 回答
16

I had a similar issue and noted that the default cmd on Windows Server 2012 was running the x64 one.

For Windows 7, Windows 8, Windows Server 2008 R2 or Windows Server 2012, run the following commands as Administrator:

x86

Open C:\Windows\SysWOW64\cmd.exe Run the command: powershell Set-ExecutionPolicy RemoteSigned

x64

Open C:\Windows\system32\cmd.exe Run the command powershell Set-ExecutionPolicy RemoteSigned

You can check mode using

In CMD: echo %PROCESSOR_ARCHITECTURE% In Powershell: [Environment]::Is64BitProcess

I hope this helps you.

于 2016-06-16T07:23:32.060 回答