解决PowerShell提示“execution of scripts is disabled on this system”问题

解决PowerShell提示“execution of scripts is disabled on this system”问题

技术背景

在Windows系统中使用PowerShell执行脚本时,可能会遇到“execution of scripts is disabled on this system”的提示。这是因为PowerShell有执行策略的限制,这些策略决定了在何种条件下可以加载配置文件和运行脚本。在工作站版Windows中,脚本文件执行默认是禁用的(策略为Restricted);而在较新的服务器版Windows中,默认策略是RemoteSigned

实现步骤

检查当前执行策略

可以使用以下命令查看当前的执行策略:

1
Get-ExecutionPolicy

设置执行策略

  • 作为管理员设置系统范围的执行策略
    打开PowerShell窗口并以管理员身份运行以下命令,将执行策略设置为RemoteSigned
1
Set-ExecutionPolicy RemoteSigned

若要将策略恢复到默认值,可以使用:

1
Set-ExecutionPolicy Restricted
  • 设置当前用户的执行策略
    如果你没有管理员权限,可以为当前用户设置执行策略。例如,将当前用户的执行策略设置为RemoteSigned
1
Set-ExecutionPolicy -Scope CurrentUser RemoteSigned

或者设置为Unrestricted

1
Set-ExecutionPolicy -Scope CurrentUser Unrestricted
  • 使用-Force参数绕过确认提示
1
2
Set-ExecutionPolicy -Scope CurrentUser -ExecutionPolicy Unrestricted -Force
Set-ExecutionPolicy -Scope CurrentUser -ExecutionPolicy Bypass -Force

不同系统版本和架构的设置

  • Windows Server 2008 R2、Windows 11、Windows 10、Windows 7、Windows 8、Windows Server 2012
    • x86(32位):打开C:\Windows\SysWOW64\cmd.exe,运行命令powershell Set-ExecutionPolicy RemoteSigned
    • x64(64位):打开C:\Windows\system32\cmd.exe,运行命令powershell Set-ExecutionPolicy RemoteSigned
  • Windows 7
    • 从开始菜单搜索“Windows PowerShell ISE”。
    • 右键单击x86版本并选择“以管理员身份运行”。
    • 在顶部粘贴Set-ExecutionPolicy RemoteSigned并运行脚本,选择“Yes”。
    • 对64位版本的Powershell ISE重复上述步骤。

通过组策略设置执行策略

  • 按下Win + R,输入gpedit.msc打开组策略编辑器。
  • 导航到“本地计算机策略” -> “计算机配置” -> “管理模板” -> “Windows组件” -> “Windows PowerShell”。
  • 启用“打开脚本执行”,并根据需要设置策略,例如设置为“允许所有脚本”。

临时绕过执行策略

对于单个文件,可以在运行PowerShell时添加-ExecutionPolicy Bypass参数:

1
powershell -ExecutionPolicy Bypass -File script.ps1

也可以使用以下命令绕过:

1
powershell Get-Content .\test.ps1 | Invoke-Expression

核心代码

设置当前用户的执行策略为RemoteSigned

1
Set-ExecutionPolicy -Scope CurrentUser RemoteSigned -Force

临时绕过执行策略运行脚本

1
pwsh.exe -ExecutionPolicy RemoteSigned -File someScript.ps1

最佳实践

  • 优先使用RemoteSigned策略,它在安全性和便利性之间提供了较好的平衡,允许本地脚本(包括网络共享的脚本)在不包含签名的情况下执行,而从互联网下载的脚本需要签名。
  • 在完成脚本执行后,将执行策略恢复到更安全的状态,例如RestrictedAllSigned
  • 若不确定当前的执行策略设置,可以使用Get-ExecutionPolicy -List查看所有作用域及其相应的策略。

常见问题

权限不足

如果在普通模式下尝试更改执行策略,可能会收到以下错误:

1
Access to the registry key 'HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\PowerShell\1\ShellIds\Microsoft.PowerShell' is denied. To change the execution policy for the default (LocalMachine) scope, start Windows PowerShell with the "Run as administrator" option.

解决方法是使用“以管理员身份运行”选项启动PowerShell,或者为当前用户设置执行策略。

策略被组策略覆盖

如果执行策略是通过组策略对象(GPO)设置的,则无法使用Set-ExecutionPolicy或CLI的-ExecutionPolicy参数更改或覆盖。可以通过组策略编辑器(gpedit.msc)来修改本地组策略。

不同版本和架构的PowerShell策略设置

在不同版本和架构(32位和64位)的PowerShell中,执行策略是分开维护的。因此,需要分别为不同的版本和架构设置执行策略。


解决PowerShell提示“execution of scripts is disabled on this system”问题
https://119291.xyz/posts/solve-powershell-script-execution-disabled-issue/
作者
ww
发布于
2025年5月12日
许可协议