[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)
- 确认环境:报错发生在 PowerShell 环境而非 CMD。
- 定位文件:报错路径指向
npm.ps1,说明系统在尝试执行脚本文件。
- 检查权限:报错关键词
disabled提示这并非安装损坏,而是系统“禁止”执行脚本。
💡 发现原因 (Root Cause)
Windows PowerShell 默认的 执行策略 (Execution Policy) 是
Restricted。- 该策略出于安全考虑,禁止运行任何
.ps1脚本。
npm在 Windows 上是通过脚本调用的,因此被系统安全机制拦截。
🛠️ 解决问题 (Solution)
一键修复方案:
- 以 管理员身份 打开 PowerShell。
- 输入并执行:PowerShell
Set-ExecutionPolicy RemoteSigned -Scope CurrentUser -Force- 验证:再次输入
npm -v,即可正常显示版本号。
🚀 问题扩展 (Expansion)
- 策略选择:
RemoteSigned是开发最平衡的选择(本地脚本随便跑,下载的脚本才验签名)。
- 作用域控制:
Scope CurrentUser仅修改当前用户,不影响系统全局或其他账号,安全性更高且操作门槛低。
- 其他工具:此方案同样适用于解决
yarn,pnpm,nodemon,vue-cli等工具报同样的脚本受限错误。
#Windows #Nodejs #PowerShell #环境配置
Loading...