windows 从 WMI ExecQuery 获取第一条记录

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2378723/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-15 14:04:14  来源:igfitidea点击:

Get first record from WMI ExecQuery

windowsvbscriptwmi

提问by Lukas Cenovsky

I have a simple vbscript for retrieving the Windows version:

我有一个简单的 vbscript 来检索 Windows 版本:

Set objWMI = GetObject("winmgmts:{impersonationLevel=impersonate}!\.\root\cimv2")
Set colVersions = objWMI.ExecQuery("Select * from Win32_OperatingSystem")

For Each objVer in colVersions
   ver = objVer.Version
Next

Is is possible to get the first record or do I have to loop over all records in the collection. All examples I've seen are with For Eachconstruction. I receive Expected end of statementerror when I try:

是否可以获得第一条记录,或者我是否必须遍历集合中的所有记录。我见过的所有例子都与For Each建筑有关。我在尝试时收到预期的语句结束错误:

ver = colVersions[0].Version

It looks like the return value of ExecQueryis not a proper collection.

看起来 的返回值ExecQuery不是正确的集合。

回答by Helen

On Windows Vista and later, you can use the ItemIndexmethod to get a collection item by its index:

在 Windows Vista 及更高版本上,您可以使用该ItemIndex方法通过索引获取集合项:

ver = colVersions.ItemIndex(0).Version

On earlier Windows versions, there's no way to do this I'm afraid.

在早期的 Windows 版本上,恐怕没有办法做到这一点。

回答by Schietschijf

For Each objVer in colVersions
   ver = objVer.Version
   exit for
Next

回答by Mako-Wish

Set objWMI = GetObject("WinMgmts:{ImpersonationLevel=Impersonate}!\.\Root\CIMV2")
Set objOS  = objWMI.ExecQuery("SELECT * FROM Win32_OperatingSystem").ItemIndex(0)

msgBox objOS.Version

Edit for Explanation: By adding .ItemIndex(0) to your original query, you are grabbing the first item in the collection. This will eliminate the need for a For/Each loop.

编辑解释:通过将 .ItemIndex(0) 添加到原始查询中,您将获取集合中的第一项。这将消除对 For/Each 循环的需要。