.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引擎执行命令:
- 移除项目中
Microsoft.PowerShell.SDK的NuGet引用 - 添加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版本)
- 可直接从GAC引用(路径通常为
- 原有代码无需修改,
PowerShell.Create()会创建Windows PowerShell实例,即可正常执行命令。
办法三:排查PowerShell 7环境兼容性
若坚持使用PowerShell 7,先在本地PowerShell 7终端中测试Import-Module NetAdapter -UseWindowsPowerShell和Get-NetAdapterHardwareInfo是否能正常运行,排除权限(如管理员权限)或环境配置问题后,再在代码中复用该逻辑。
内容的提问来源于stack exchange,提问作者Luishg
相关产品推荐
相关产品推荐

