背景
更换新电脑后,在vsCode的终端中执行nodejs命令,报错
            
            
              js
              
              
            
          
           + CategoryInfo          : SecurityError: (:) [],PSSecurityException
 + FullyQualifiedErrorId : UnauthorizedAccess
        原因
vscode中终端默认为PowerShell,其有较为严格的执行策略,运行失败是 PowerShell 的执行策略(Execution Policy)限制导致的。
解决
方法一:更改 PowerShell 执行策略(推荐临时修改)
以管理员身份运行 PowerShell 或 VS Code终端,然后运行以下命令:
            
            
              powershell
              
              
            
          
          Set-ExecutionPolicy RemoteSigned -Scope CurrentUser
        参数说明:
RemoteSigned:允许运行本地编写的脚本,但来自网络的脚本必须签名。Scope CurrentUser:只对当前用户生效,无需系统级权限,安全且推荐
还原命令:Set-ExecutionPolicy Restricted -Scope CurrentUser
方法二:在 VS Code 中切换终端为 Command Prompt(cmd)或 Git Bash
PowerShell 对脚本限制严格,而 cmd 和 Git Bash 不受 PowerShell 执行策略影响。
操作步骤:
- 打开 VS Code 终端
 - 点击右上角下拉箭头,选择:Command Prompt(cmd)或 Git Bash
 - 然后运行 npm -v 就不会报错了
