WQL does not support TOP - need workaround

2020-04-07 12:14发布

WQL (basically SQL for WMI) does not support a TOP or LIMIT keyword. Sql Server used TOP and many other RDBMSs supprt LIMIT etc.

Is there a workaround to emulating a SELECT query to behave as though it had a TOP/LIMIT clause that limits the result set to some arbitrary number?

Or is there some other WQL-specific keyword that works like TOP or LIMIT?

3条回答
神经病院院长
2楼-- · 2020-04-07 12:44

Like Justin has said. I am not sure about your exact requirement though. I was doing a simple project with Visual Basic and part of it was to fetch event log, the listview fails due to the huge size of Application log(>20MB) and the control enters into some kind of infinite loop. I wanted to limit so here is the pseudocode

topval = UserInputText.Text 'Assuming user entered the top 10 or 20

while ThereAreStillItemsInCollection
 if topval = 0 then
 goto CleanUpMemObjectsAndReturn
 end if
topval = topval  - 1
wend
CleanUpMemObjectsAndReturn:
set obj = Nothing
end sub
查看更多
劫难
3楼-- · 2020-04-07 12:58

Nope, there's no way to simulate TOP using WQL alone.

Exception: if you're lucky enough to be querying a WMI class which has ungapped, ascending numeric instance numbers used as keys, then you can use greater-than and less-then comparisons to limit and page through the results.

It's possible that ManagementClass.GetInstances() instead of using a WQL query might allow you to cancel the enumeration midway once you've collected enough instances, and hence avoid paying the CPU and RAM cost of enumerating the whole list at once.

Note that, AFAIK, the CIMV2 WMI provider doesn't natively handle WQL-- instead it simply relies on WMI to enumerate all instances, process the WQL, and filter the results before returning them to the caller. But the expensive part (actually fetching the underlying WMI data) is still done. So I believe there's no efficiency gain to be had (for local WMI queries, that is) by using WQL vs. using GetInstances() and filtering the results yourself-- and if GetInstances() allows you to cancel midway, then GetInstances() may be much cheaper for long result sets.

查看更多
Luminary・发光体
4楼-- · 2020-04-07 13:06

pipe it with "select xyz -First 1"

eg: Get-WmiObject win32_logicaldisk |select -First 1

查看更多
登录 后发表回答