2013-05-09 123 views
70

我运行此代码从一个asp.net应用程序执行电源外壳:.ps1无法加载,因为在此系统上禁用了脚本的执行?

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 cannot be loaded because the execution of scripts is disabled on this system. Please see "get-help about_signing" for more details.

相同的代码运行在命令提示符下或Windows罚款(winform)应用程序。

回答

84

由于execution policy,您的脚本被阻止执行。

您需要在客户端PC上将其设置为Unrestricted。你可以通过调用Invoke来做到这一点

Set-ExecutionPolicy Unrestricted 
+3

这不适合我。嗯,实际上如果你把它设置为32位和64位,它确实能工作。 – 2016-02-12 08:45:28

18

问题是,执行策略是在每个用户的基础上设置的。你需要在你的应用程序每次运行时运行以下命令它,使其能够工作:

Set-ExecutionPolicy -Scope Process -ExecutionPolicy RemoteSigned 

有可能是设置此为ASP.NET用户还有一种方式,但这种方式意味着你不打开你的整个系统,只是你的应用程序。

Source

+0

这对我来说是完美的答案。而不是始终启用它,只是启用它为您想要的功能,然后它重置。 – Tschallacka 2016-12-15 07:18:55

6

你需要运行设置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. 

希望这有助于!

51

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

在您的Windows目录中查找System32和SysWOW64。

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

  1. 导航到WindowsPowerShell \ v1.0和推出powershell.exe
  2. 检查ExecutionPolicy当前设置:

    Get-ExecutionPolicy -List

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

    Set-ExecutionPolicy -Scope LocalMachine Unrestricted

请注意,您可能需要运行PowerShell中的因您要设置策略的范围管理员。

你可以阅读了很多在这里:Running Windows PowerShell Scripts

+3

这是最好的答案 – 2016-02-12 08:49:26

+2

** Set-ExecutionPolicy -Scope Process Unrestricted **适用于我 – daniel 2016-03-16 09:22:56

+3

Set-ExecutionPolicy -Scope CurrentUser无限制为我工作 – Jignesh 2016-04-13 08:53:39

1

我也有类似的问题,并指出Windows Server 2012中的默认CMD正在运行的64位之一。

对于Windows 7,Windows 8中,Windows Server 2008的R2或Windows Server 2012,运行下面的命令作为管理员:

打开C:\的Windows \ Syswow64资料\ cmd.exe的 运行命令:PowerShell的SET-ExecutionPolicy RemoteSigned就是

打开C:\ WINDOWS \ SYSTEM32 \ cmd.exe的 运行命令的PowerShell设置ExecutionPolicy RemoteSigned就是

可以使用

在CMD检查模式:回声%PROCESSOR_ARCHITECTURE% 在PowerShell中:[环境] :: Is64BitProcess

我希望这可以帮助您。

相关问题