哪个适用于Powershell 6的库包含get-wmiobject命令?

23

当我尝试在PowerShell(版本6)中使用get-WmiObject命令时,出现了以下错误:

PS C:\Users\zsofi> Get-WmiObject Win32_product | select name, packagecache

Get-WmiObject : The term 'Get-WmiObject' is not recognized as the name of a cmdlet, function, script file, or operable program.
Check the spelling of the name, or if a path was included, verify that the path is correct and try again.
At line:1 char:1
+ Get-WmiObject Win32_product | select name, packagecache
+ ~~~~~~~~~~~~~
+ CategoryInfo          : ObjectNotFound: (Get-WmiObject:String) [], CommandNotFoundException
+ FullyQualifiedErrorId : CommandNotFoundException`

3
根据 MSDocs 网站的内容,"The requested page is not available for PowerShell 6. You have been redirected to the newest product version this page is available for." ,而目前可用的“最高版本”是5.1。从我所了解的情况来看,您应该能够使用 Get-CimInstance 命令 - Get-CimInstance (CimCmdlets) | Microsoft Docs — https://learn.microsoft.com/en-us/powershell/module/cimcmdlets/get-ciminstance?view=powershell-6。 - Lee_Dailey
2个回答

36

Gert Jan Kraaijeveld的有用答案提供了一种解决方案,适用于仅在Windows PowerShell(而不是PowerShell [Core] 6+)中真正可用的cmdlet。

然而,在这种特定情况下,正如Lee_Dailey在评论中指出的那样,您可以使用Get-CimInstance cmdlet,它也在PowerShell [Core] 6+中可用

Get-CimInstance CIM_Product | Select-Object Name, PackageCache

请注意CIM_Product类名;CIM类通常具有与其WMI Win32_*对应项相同的属性。

为什么通常应该使用CIM cmdlet而不是WMI cmdlet:

在PowerShell Core中,所有未来的开发工作都将采用CIM cmdlet,但即使在Windows PowerShell中,也建议使用CIM (*-Cim*) cmdlet,因为自PowerShell版本3(于2012年9月发布)引入CIM cmdlet后,WMI (*-Wmi*) cmdlet已被弃用。从Get-CimInstance docs中了解更多:

从Windows PowerShell 3.0开始,此cmdlet已被Get-CimInstance取代。

关于为什么CIM cmdlets是更好的选择(引用自this TechNet blog post):
WMI cmdlets的一个大缺点是它们使用DCOM来访问远程计算机。DCOM不适合防火墙,可能会被网络设备阻止,并且在出现问题时会给出一些晦涩的错误信息。
同一篇博客文章还描述了CIM cmdlets的优点:
  • 使用与 PowerShell 本身相同的基于标准的远程机制 (WS-Management,通过其 Windows 实现 WinRM)

    • 也就是说,已设置为 PowerShell 远程操作的计算机 (请参阅 about_Remote_Requirements) 隐式支持通过 CIM cmdlet 进行定位。

    • 但是,您仍然可以选择使用 DCOM 协议 (就像 WMI cmdlet 所做的那样),使用 New-CimSessionOption cmdlet 进行选择性加入。

  • 具有会话支持

  • 与其过时的 WMI 对应项略有不同,因为返回的对象没有直接的方法; 必须通过 Invoke-CimMethod 调用方法,并且删除实例需要 Remove-CimInstance


6
据我所知,唯一的方法是使用兼容性模块。这是微软提供的一个非常方便的模块,通过隐式远程连接到同一台计算机上的Windows Powershell 5.1会话,实际上使得Windows PS cmdlets在PS Core中可用。https://github.com/PowerShell/WindowsCompatibility

请注意,该项目指向 PowerShell 主项目中的一个 RFC,声称该模块已添加到 PowerShell v7,因此不再需要导入。(并且该项目已被适当地存档。)我仍在努力理解如何使用兼容性功能 - ruffin

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接