You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

.NET 6中PowerShell命令Get-NetAdapterHardwareInfo执行失败排查

问题原因

你引用的Microsoft.PowerShell.SDK对应PowerShell 7.x版本,而Get-NetAdapterHardwareInfo是Windows PowerShell(5.1及以下)专属的NetAdapter模块命令。PowerShell 7默认不会加载这类仅Windows PowerShell提供的系统模块;而.NET 4.7.2项目默认使用Windows PowerShell运行时,因此可以直接找到该命令,迁移到.NET 6后用PowerShell 7的SDK创建实例,自然找不到未加载的命令。

解决办法

办法一:在PowerShell 7实例中手动导入Windows PowerShell模块

在调用目标命令前,先导入NetAdapter模块并指定-UseWindowsPowerShell参数(该参数用于在PowerShell 7中加载Windows PowerShell专属模块):

PowerShell ps = PowerShell.Create();
// 导入Windows PowerShell的NetAdapter模块
ps.AddCommand("Import-Module")
  .AddParameter("Name", "NetAdapter")
  .AddParameter("UseWindowsPowerShell");
ps.Invoke();
// 清空命令集合,执行目标命令
ps.Commands.Clear();
ps.AddCommand("Get-NetAdapterHardwareInfo");
var NetAdapters = ps.Invoke();

办法二:改用Windows PowerShell运行时创建实例

如果不需要PowerShell 7的特性,直接使用Windows PowerShell引擎执行命令:

  1. 移除项目中Microsoft.PowerShell.SDK的NuGet引用
  2. 添加Windows PowerShell对应的System.Management.Automation引用:
    • 可直接从GAC引用(路径通常为C:\Windows\Microsoft.NET\assembly\GAC_MSIL\System.Management.Automation\v4.0_3.0.0.0__31bf3856ad364e35)
    • 或通过NuGet安装System.Management.Automation.WindowsPowerShell包(对应Windows PowerShell 5.1版本)
  3. 原有代码无需修改,PowerShell.Create()会创建Windows PowerShell实例,即可正常执行命令。

办法三:排查PowerShell 7环境兼容性

若坚持使用PowerShell 7,先在本地PowerShell 7终端中测试Import-Module NetAdapter -UseWindowsPowerShell和Get-NetAdapterHardwareInfo是否能正常运行,排除权限(如管理员权限)或环境配置问题后,再在代码中复用该逻辑。

内容的提问来源于stack exchange,提问作者Luishg

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.07 03:25:33