本文记录 Windows 下,PowerShell 报错 无法加载文件,因为在此系统上禁止运行脚本 问题的解决方案。
问题描述
PowerShell 启动时报错
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
| Windows PowerShell 版权所有 (C) Microsoft Corporation。保留所有权利。尝试新的跨平台 PowerShell https://aka.ms/pscore6 . : 无法加载文件 C:\Users\vvd\Documents\WindowsPowerShell\profile.ps1,因为在此系统上禁止运行脚本。有关详细信息,请 参阅 https:/go.microsoft.com/fwlink/?LinkID=135170 中的 about_Execution_Policies。 所在位置 行:1 字符: 3 + . 'C:\Users\vvd\Documents\WindowsPowerShell\profile.ps1' + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + CategoryInfo : SecurityError: (:) [],PSSecurityException + FullyQualifiedErrorId : UnauthorizedAccess . : 无法加载文件 C:\Users\张逸为\Documents\WindowsPowerShell\Microsoft.PowerShell_profile.ps1,因为在此系统上禁止运行脚 本。有关详细信息,请参阅 https:/go.microsoft.com/fwlink/?LinkID=135170 中的 about_Execution_Policies。 所在位置 行:1 字符: 3 + . 'C:\Users\vvd\Documents\WindowsPowerShell\Microsoft.PowerShell_prof ... + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + CategoryInfo : SecurityError: (:) [],PSSecurityException + FullyQualifiedErrorId : UnauthorizedAccess
|
问题原因
这些错误都是因为 Windows PowerShell 默认的脚本执行策略限制导致的。需要先更改 PowerShell 的执行策略,才能正常加载配置文件(profile.ps1)。
简单来说,Windows 系统出于安全考虑,默认禁止运行所有脚本(包括 .ps1 文件)。你通过以上步骤将其更改为 RemoteSigned,就为在当前计算机上运行本地脚本授予了权限,解决了配置文件和一些特殊命令的加载问题。
解决步骤
-
以管理员身份打开 PowerShell
- 点击“开始”菜单,搜索
PowerShell。
- 在搜索结果中,右键点击 Windows PowerShell,选择 “以管理员身份运行”。
-
检查当前执行策略
- 在打开的管理员 PowerShell 窗口中,输入以下命令并回车,查看当前的策略设置:
- 如果显示
Restricted,这确认了正是该限制导致了你的问题。
-
更改执行策略
- 输入以下命令,将策略修改为
RemoteSigned。这个设置允许运行本地编写的脚本,而来自远程(如下载的)脚本则必须有受信任的发布者的数字签名,是在安全和便利性上比较平衡的选择。
1
| Set-ExecutionPolicy RemoteSigned
|
-
验证更改
- 再次运行检查命令,确保策略已成功更新为
RemoteSigned。
-
测试命令
- 关闭当前管理员 PowerShell 窗口,然后重新打开一个普通的 PowerShell 窗口,报错消失。
文章链接:
https://www.zywvvd.com/notes/system/windows/fix-windows-powershell-err/fix-windows-powershell-err/