无法加载.ps1,因为在此系统上禁用了脚本的执行

ume*_*ape 119 c# asp.net powershell

我运行此代码以从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();
Run Code Online (Sandbox Code Playgroud)

但我收到一个错误:

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

从命令提示符或Windows(Windows窗体)应用程序运行相同的代码.

gho*_*ord 148

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

您需要以管理员身份运行PowerShell,并在客户端PC上将其设置为Unrestricted.您可以通过调用Invoke来执行此操作:

Set-ExecutionPolicy Unrestricted
Run Code Online (Sandbox Code Playgroud)

  • 这对我不起作用.好吧,实际上如果你设置32位和64位它确实有效. (8认同)
  • 遵循最少许可的原则.在删除对安全策略的所有限制之前,至少将策略设置为"RemoteSigned".如果这不起作用,那么重新评估你的痛点是什么以及它为什么不起作用.您可以将无限制设置为最后的手段,但它不应该是您的起点. (4认同)
  • 我安装了 32 位和 64 位 PS。我必须对两者都制定执行策略。例如 C:\Windows\System32\WindowsPowerShell\v1.0\Powershell.exe 和 C:\Windows\SysWOW64\WindowsPowerShell\v1.0\Powershell.exe。如果只有一个人,生活会好一点。 (2认同)

Jon*_*ell 79

在某些情况下,您可以按照其他答案中建议的步骤进行操作,验证是否正确设置了执行策略,并且仍然使脚本失败.如果您遇到这种情况,您可能位于具有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,具体取决于您尝试为其设置策略的范围.

您可以在此处阅读更多内容:运行Windows PowerShell脚本

  • **Set-ExecutionPolicy -Scope Process Unrestricted**适用于我 (7认同)
  • 这是最好的答案 (5认同)
  • Set-ExecutionPolicy -Scope CurrentUser Unrestricted为我工作 (5认同)
  • 这为我解决了(在 64 位机器上) (2认同)

Nad*_*_MK 24

你需要运行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.
Run Code Online (Sandbox Code Playgroud)


Mat*_*les 23

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

Set-ExecutionPolicy -Scope Process -ExecutionPolicy RemoteSigned
Run Code Online (Sandbox Code Playgroud)

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

(来源)

  • 这适用于 Windows 10 的 VScode PowerShell 控制台 (6认同)

小智 13

我有一个类似的问题,并注意到 Windows Server 2012 上的默认 cmd 运行的是 x64 的。

对于 Windows 7、Windows 8、Windows Server 2008 R2 或 Windows Server 2012,以管理员身份运行以下命令:

x86

打开C:\Windows\SysWOW64\cmd.exe 运行命令:powershell Set-ExecutionPolicy RemoteSigned

x64

打开C:\Windows\system32\cmd.exe 运行命令powershell Set-ExecutionPolicy RemoteSigned

您可以使用检查模式

在 CMD 中:echo %PROCESSOR_ARCHITECTURE% 在 Powershell 中:[Environment]::Is64BitProcess

我希望这可以帮助你。


小智 8

尝试这个:

Set-ExecutionPolicy -scope CurrentUser Unrestricted
Run Code Online (Sandbox Code Playgroud)