How to get WMI object from a WMI object reference?

2019-06-14 16:35发布

Similar to this question except that no answer was given with regards to the main question of getting an object from reference.

For example:

PS C:\Users\admin> Get-WmiObject -Namespace $namespace -Class $class


    ...

IsActive     :  1
oA: \\.\ROOT\abc\abc\ABC:abc.xyz="tst2"
oB : \\.\ROOT\abc\abc\ABC:abc.xyz="tst3"
PSComputerName         : admin-test2

oA and oB are references and therefore come up as strings in powershell. Is there a way I can get the object they represent using WMI query in powershell?

2条回答
迷人小祖宗
2楼-- · 2019-06-14 16:53

Assuming that oA and oB actually are strings you should be able to resolve these WMI paths to WMI objects like this:

Get-WmiObject -Namespace $namespace -Class $class | % {
  $oA = [wmi]$_.oA
  $oB = [wmi]$_.oB
}

Example:

PS C:\> $namespace = 'root/cimv2'
PS C:\> $class = 'Win32_OperatingSystem'
PS C:\> $obj1 = Get-WmiObject -Namespace $namespace -Class $class
PS C:\> $obj1

SystemDirectory : C:\Windows\system32
Organization    :
BuildNumber     : 7601
RegisteredUser  : foo
SerialNumber    : 00371-OEM-8310595-XXXXX
Version         : 6.1.7601


PS C:\> $obj1.GetType().FullName
System.Management.ManagementObject
PS C:\> $obj1.Path.Path
\\FOO\root\cimv2:Win32_OperatingSystem=@
PS C:\> ($obj1.Path.Path).GetType().FullName
System.String
PS C:\> $obj2 = [wmi]$obj1.Path.Path
PS C:\> $obj2

SystemDirectory : C:\Windows\system32
Organization    :
BuildNumber     : 7601
RegisteredUser  : foo
SerialNumber    : 00371-OEM-8310595-XXXXX
Version         : 6.1.7601


PS C:\> $obj2.GetType().FullName
System.Management.ManagementObject

Your question is rather vague, though, so I'm not sure if this answer actually covers what you've been asking.

查看更多
forever°为你锁心
3楼-- · 2019-06-14 17:00

As OP mentioned that all he wants is a generic answer (which is again tough given the nature of Object Paths and dependency on key), I am giving another example of using Associators Of WMI query.

$query = "ASSOCIATORS OF {Win32_Account.Name='DemoGroup2',Domain='DomainName'} WHERE Role=GroupComponent ResultClass=Win32_Account"
Get-WMIObject -Query $query | Select Name

If you need to use the example above, you need to first find out what is the key property and use that in the object path.

-----Original answer -----

What namespace? What class? You need to use associations and/or references to retrieve that. It is hard to give a generic answer unless we know the exact object path. For example,

$query = "REFERENCES OF {Win32_Service.Name='Netlogon'} WHERE ClassDefsOnly"
Get-WMIObject -Query $query

The above query will give all references of Win32_Service with an object path ServiceName='NetLogon'

查看更多
登录 后发表回答