WMI .NET 无效查询

WMI .NET Invalid query

我在尝试执行以下查询时不断收到 "Invalid Query" 异常:

ManagementObjectSearcher searcher = new ManagementObjectSearcher("SELECT * FROM Win32_DiskQuota WHERE QuotaVolume.DeviceID = 'C:'");
ManagementObjectCollection quotaCollection = searcher.Get();

但是这有效:"SELECT * FROM Win32_DiskQuota"。

根据 MSDN:

For most uses of class descriptors in a WHERE clause, WMI flags the query as invalid and returns an error. However, use the dot (.) operator for properties of type object in WMI. For example, the following query is valid if Prop is a valid property of MyClass and is type object:

SELECT * FROM MyClass WHERE Prop.embedprop = 5

这是否意味着只有当 Prop 声明为 OBJECT 时才有效?

以下是异常详情:

System.Management.ManagementException was unhandled
  HResult=-2146233087
  Message=Invalid query 
  Source=System.Management
  StackTrace:
       в System.Management.ManagementException.ThrowWithExtendedInfo(ManagementStatus errorCode)
       в System.Management.ManagementObjectCollection.ManagementObjectEnumerator.MoveNext()
       в UserQuota.Program.getQuota() в c:\users\administrator\documents\visual studio 2015\Projects\UserQuota\UserQuota\Program.cs:строка 40
       в UserQuota.Program.Main(String[] args) в c:\users\administrator\documents\visual studio 2015\Projects\UserQuota\UserQuota\Program.cs:строка 33
       в System.AppDomain._nExecuteAssembly(RuntimeAssembly assembly, String[] args)
       в System.AppDomain.ExecuteAssembly(String assemblyFile, Evidence assemblySecurity, String[] args)
       в Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()
       в System.Threading.ThreadHelper.ThreadStart_Context(Object state)
       в System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
       в System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
       в System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
       в System.Threading.ThreadHelper.ThreadStart()
  InnerException: 

是的。根据 Win32_DiskQuota class documentation,QuotaVolume 属性 是对 Win32_LogicalDisk WMI class 的引用。您提供的来自 MSDN 的引文给出了根据 WQL 规范查询无效的原因。

相反,您可以使用这样的东西:

ManagementObjectSearcher searcher = new ManagementObjectSearcher("SELECT * FROM Win32_DiskQuota WHERE QuotaVolume = \"Win32_LogicalDisk.DeviceID=\\"C:\\"\"");
ManagementObjectCollection quotaCollection = searcher.Get();

(注意所有转义...)