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

ep6jt1vc  于 2023-01-10  发布在  .NET
关注(0)|答案(7)|浏览(185)

我运行以下代码是为了从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窗体)应用程序运行良好。

7hiiyaii

7hiiyaii1#

由于execution policy,您的脚本被阻止执行。
你需要以管理员身份运行PowerShell,并在客户端PC上将其设置为“不受限制”。你可以使用以下命令调用Invoke来执行此操作:

Set-ExecutionPolicy Unrestricted
4nkexdtk

4nkexdtk2#

在某些情况下,您可以按照其他答案中建议的步骤操作,验证执行策略是否设置正确,但脚本仍然会失败。如果您遇到这种情况,则可能是因为您使用的是同时安装了32位和64位版本PowerShell的64位计算机。而失败发生在未设置执行策略的版本上。此设置不适用于两个版本,因此必须显式设置两次。
在Windows目录中查找System32和SysWOW64。
对每个目录重复这些步骤:
1.导航到Windows PowerShell\v1.0并启动powershell.exe
1.检查ExecutionPolicy的当前设置:
第一个月
1.为所需的级别和范围设置ExecutionPolicy,例如:
Set-ExecutionPolicy -Scope LocalMachine Unrestricted
请注意,您可能需要以管理员身份运行PowerShell,具体取决于您尝试为其设置策略的作用域。

k3fezbri

k3fezbri3#

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

Set-ExecutionPolicy -Scope Process -ExecutionPolicy RemoteSigned

可能也有一种方法可以为ASP.NET用户设置这个值,但是这种方法意味着您并没有打开整个系统,而只是打开了应用程序。
Source

nnt7mjpx

nnt7mjpx4#

您需要运行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.
okxuctiv

okxuctiv5#

我遇到了类似的问题,并注意到Windows Server 2012上的默认cmd运行的是X64。
对于Windows 7、Windows 8、Windows Server 2008 R2或Windows Server 2012,请以管理员身份运行以下命令:

x86

运行命令:powershell Set-ExecutionPolicy RemoteSigned

x64

打开C:\Windows\system32\cmd.exe运行命令powershell Set-ExecutionPolicy RemoteSigned
您可以使用检查模式
在CMD中:echo %PROCESSOR_ARCHITECTURE%在Powershell中:[Environment]::Is64BitProcess
希望这对你有帮助。

iezvtpos

iezvtpos6#

试试这个:

Set-ExecutionPolicy -scope CurrentUser Unrestricted
qgelzfjb

qgelzfjb7#

如果你在运行json-server时遇到了这个错误,并且登陆到了这个页面。一个替代的解决方案是直接使用npx运行它,而不安装它。
npx json-server --watch db.json

相关问题