Why does WMI work through a search but not directly?

半世苍凉 提交于 2020-03-05 05:42:05

问题


The first of these 2 locks a BitLocked drive. The 2nd's InvokeMethod throws: 'Invalid object path'. Why? They seem equivalent.

//Using a search:
ManagementObjectSearcher searcher = new ManagementObjectSearcher("root\\CIMV2\\Security\\MicrosoftVolumeEncryption", "SELECT * FROM Win32_EncryptableVolume WHERE DriveLetter = 'E:'");
foreach (ManagementObject classInstance1 in searcher.Get())
    classInstance1.InvokeMethod("Lock", new object[] { true }); 

//Direct:
ManagementObject classInstance2 = new ManagementObject("root\\CIMV2\\Security\\MicrosoftVolumeEncryption", "Win32_EncryptableVolume.DriveLetter='E:'", null);
classInstance2.InvokeMethod("Lock", new object[] { 0 });//throws: 'Invalid object path'.

回答1:


You unfortunately can't instantiate an object using a property that isn't a key property. A key property in WMI is a property that has the CIM_Key qualifier, the WMI documentation goes into further detail about the Key Qualifier. For more information about the WMI requirement of using a full path with key to reference an object you can read the WMI documentation about Instance Object Paths.

In C#, for the particular class you specified (Win32_EncryptableVolume), You can only accomplish what you are trying to do by using the ManagementObjectSearcher as shown in your example. This is because you are trying to get an instance based on a standard property rather than a key property.

A great utility to explore WMI is WMI Explorer 2.0. This gives a great visual representation of WMI classes. In this utility, Key Properties are identified with an asterisk.

https://github.com/vinaypamnani/wmie2/releases




回答2:


It seems you are not calling Get() method. Try this:

ManagementObject classInstance2 = new ManagementObject("root\\CIMV2\\Security\\MicrosoftVolumeEncryption", "Win32_EncryptableVolume.DriveLetter='E:'", null);
classInstance2.Get();
classInstance2.InvokeMethod("Lock", new object[] { 0 });

Check out this documentation: https://docs.microsoft.com/en-us/windows/desktop/wmisdk/retrieving-an-instance




回答3:


I'll just assume that the correct answer is similar to what the others have mentioned but not exactly.

The class's page mentions that DeviceID has the following property:

Qualifiers: Key

I assume, for lack of actual documentation, that searching for something by their Key returns the thing itself. While searching by something else returns a list of objects that satisfy that condition. Even if the list contains only 1 entry - it's not the object itself but rather a list.

But if someone could supply some documentation, that would be nice.



来源:https://stackoverflow.com/questions/54892478/why-does-wmi-work-through-a-search-but-not-directly

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!