[npm] 脚本执行受限问题修复

comment (1)
type
Post
status
Published
date
Apr 4, 2026
slug
summary
tags
category
icon
password
comment

🚩 问题现象 (Problem)

在 Windows 终端执行 npm 命令(如 npm -v)时失败,报错:
npm.ps1 cannot be loaded because running scripts is disabled on this system.
错误码SecurityError, PSSecurityException

🔍 排查思路 (Troubleshooting)

  1. 确认环境:报错发生在 PowerShell 环境而非 CMD。
  1. 定位文件:报错路径指向 npm.ps1,说明系统在尝试执行脚本文件。
  1. 检查权限:报错关键词 disabled 提示这并非安装损坏,而是系统“禁止”执行脚本。

💡 发现原因 (Root Cause)

Windows PowerShell 默认的 执行策略 (Execution Policy)Restricted
  • 该策略出于安全考虑,禁止运行任何 .ps1 脚本。
  • npm 在 Windows 上是通过脚本调用的,因此被系统安全机制拦截。

🛠️ 解决问题 (Solution)

一键修复方案:
  1. 管理员身份 打开 PowerShell。
  1. 输入并执行:PowerShell
    1. Set-ExecutionPolicy RemoteSigned -Scope CurrentUser -Force
  1. 验证:再次输入 npm -v,即可正常显示版本号。

🚀 问题扩展 (Expansion)

  • 策略选择RemoteSigned 是开发最平衡的选择(本地脚本随便跑,下载的脚本才验签名)。
  • 作用域控制Scope CurrentUser 仅修改当前用户,不影响系统全局或其他账号,安全性更高且操作门槛低。
  • 其他工具:此方案同样适用于解决 yarn, pnpm, nodemon, vue-cli 等工具报同样的脚本受限错误。

#Windows #Nodejs #PowerShell #环境配置
Loading...

© 阿柏 2009-2026