首页 > 解决方案 > 在 VBScript 中,如何检索 InstancesOf 集合的第一个元素?

问题描述

我正在编写一个应该识别操作系统详细信息的 VBScript。我在这里找到了一个使用 InstancesOf Win32_Operating 系统的示例,但不是示例中的 foreach 循环,我只想解决第一次出现的问题,所以我做了:

Set SystemSet = GetObject("winmgmts:").InstancesOf ("Win32_OperatingSystem")
Set System = SystemSet.Item(0)

也试过Set System = SystemSet(0)了,但每次我都有一个通用的失败错误消息(法语中的 Echec générique)。

我怎样才能做到这一点,以便我可以比较System.Caption字符串?

标签: vbscriptwmi

解决方案


GetObject("winmgmts:")返回一个SWbemServices对象。根据该SWbemServices对象的文档,该InstanceOf()方法:

FromSWbemServices.InstancesOf方法
创建一个枚举器,它根据用户指定的选择条件返回指定类的实例。

枚举器的想法是枚举对象的集合,这适用于 VBScriptFor Each语句来迭代枚举器。

一个简单的例子是;

Dim swbemInstances, swbemInstance
Set swbemInstances = GetObject("winmgmts:").InstancesOf("Win32_OperatingSystem")
For Each swbemInstance In swbemInstances
  WScript.Echo swbemInstance.Caption
Next

ItemIndex您可以使用文档所述的方法直接从枚举器访问实例;

FromSWbemObjectSet.ItemIndex方法
SWbemObject与指定索引关联的对象返回到集合中。索引指示元素在集合中的位置。集合编号从零开始。


注意:有趣的一点是,文档实际上引用了 Win32_OperatingSystem该类作为示例,您可能只想检索一个实例,并解释了如何使用ItemIndex它来促进它。

FromSWbemObjectSet.ItemIndex方法 - 示例每个操作系统安装只存在一个Win32_OperatingSystem
实例。创建 GetObject 路径以获取单个实例很麻烦,因此脚本通常会枚举Win32_OperatingSystem,即使只有一个实例可用。下面的 VBScript 代码示例展示了如何使用ItemIndex方法在不使用For Each循环的情况下访问一个Win32_OperatingSystem 。

就像是;

Dim swbemInstance
Set swbemInstance = GetObject("winmgmts:").InstancesOf("Win32_OperatingSystem").ItemIndex(0)
WScript.Echo swbemInstance.Caption

评论中也提到了


推荐阅读