用 Set-ExecutionPolicy 解决「禁止运行脚本」报错

理解 PowerShell 执行策略的作用域,选择既能运行自己的本地脚本、又不破坏安全模型的策略。

Windows终端开发安全中风险
在 PowerShell 中运行 `Set-ExecutionPolicy -ExecutionPolicy RemoteSigned -Scope CurrentUser`,本地脚本即可运行,下载的脚本仍需签名。

01命令

命令
$ Set-ExecutionPolicy -ExecutionPolicy RemoteSigned -Scope CurrentUser

02作用说明

执行策略是一道安全闸门而非沙箱:它防止误执行脚本,但很容易绕过,因此不能当作防恶意软件手段。策略按作用域优先级生效:Process(仅当前会话,如 `powershell -ExecutionPolicy Bypass -File script.ps1`)、CurrentUser、LocalMachine,越具体者优先。RemoteSigned 允许你自己写的本地脚本免签名运行,但从网络下载的文件(带 Zone.Identifier 标记)必须有签名;用 `Get-Item script.ps1 -Stream Zone.Identifier` 查看标记,可信文件用 `Unblock-File` 解除。把某个作用域设回 Undefined 即可移除该级设置并回退到下一级,`Get-ExecutionPolicy -List` 可查看完整的生效矩阵。

03风险

风险中风险
使用条件A non-elevated PowerShell window is enough for -Scope CurrentUser; changing LocalMachine scope requires administrator.
!注意: 不要把 Unrestricted 或 Bypass 设为持久的机器级策略——Bypass 只适合安装程序这类一次性调用,不适合当默认。

04撤销

撤销
$ Set-ExecutionPolicy -ExecutionPolicy Undefined -Scope CurrentUser

05来源

  • Set-ExecutionPolicy | Microsoft Learn
    Microsoft · vendor-doc · 2026-09-17
    依据: Microsoft documents Set-ExecutionPolicy with the RemoteSigned and Undefined policies and the process, currentuser, localmachine scope parameters.
  • Set-ExecutionPolicy - PowerShell
    SS64 · technical · 2026-09-17
    依据: SS64 explains the execution policy scopes and that RemoteSigned requires downloaded scripts to carry a trusted signature while local scripts run freely.

最后验证: 2026-09-17 · 分类: 开发者

06相关方案