Windows 11中“运行脚本被禁用”标准解决方案失效求助
问题分析与解决建议
核心问题
从Windows 10+VS2019升级到Windows 11+VS2022后,C#控制台应用执行PowerShell脚本时仍提示running scripts is disabled on this system,此前通过Set-ExecutionPolicy -ExecutionPolicy RemoteSigned -Scope CurrentUser解决的方法失效,尝试调整作用域、改用Unrestricted策略、组策略开启脚本执行均无效。
可能原因及对应解决方法
- PowerShell版本隔离:Windows 11默认搭载PowerShell 7.x,旧环境常用的Windows PowerShell(5.1)与它的执行策略是独立存储的,需分别设置:
- 打开Windows PowerShell(管理员),执行:
Set-ExecutionPolicy RemoteSigned -Scope CurrentUser - 打开PowerShell 7(管理员),执行:
Set-ExecutionPolicy RemoteSigned -Scope CurrentUser
- 打开Windows PowerShell(管理员),执行:
- VS2022调试权限受限:VS2022默认启动权限可能不足,右键VS2022图标选择「以管理员身份运行」后再调试应用。
- 调用的PowerShell版本不匹配:C#代码中若指定了
powershell.exe(旧版Windows PowerShell)或pwsh.exe(PowerShell 7),需对应确认该版本的执行策略是否正确配置。 - Windows Defender应用控制限制:Windows 11增强的安全策略可能通过WDAC阻止脚本执行,可临时测试:
- 按Win+R输入
gpedit.msc打开组策略编辑器; - 导航到「计算机配置」>「管理模板」>「Windows组件」>「Windows Defender应用控制」>「代码完整性」;
- 若「启用代码完整性策略」设为「已启用」,改为「已禁用」后重启电脑测试。
- 按Win+R输入
- 在C#代码中临时指定执行策略:无需修改系统全局设置,直接在调用脚本的进程内设置执行策略:
using (PowerShell ps = PowerShell.Create()) { // 仅对当前PowerShell进程生效的执行策略设置 ps.AddCommand("Set-ExecutionPolicy") .AddParameter("ExecutionPolicy", "RemoteSigned") .AddParameter("Scope", "Process") .AddParameter("Force"); // 加载并执行目标脚本 ps.AddScript(@"你的脚本路径"); var results = ps.Invoke(); // 后续结果处理逻辑 }
内容的提问来源于stack exchange,提问作者Crna Krv
相关产品推荐
相关产品推荐

