在VBScrip中,如何检索InstancesOf集合的第一个元素? [英] In VBScript, how can I retrieve the first element of an InstancesOf collection?
问题描述
我正在编写一个VB脚本,它应该标识操作系统的详细信息。我在这里找到了一个使用InstancesOf Win32_Operating System的示例,但我只想解决第一次出现的问题,而不是示例中的Foreach循环,所以我这样做了:
Set SystemSet = GetObject("winmgmts:").InstancesOf ("Win32_OperatingSystem")
Set System = SystemSet.Item(0)
我也尝试了Set System = SystemSet(0)
,但每次都收到一般性的失败错误消息(法语中的Echec Générique)。
如何才能完成此操作,以便可以比较System.Caption
字符串?
推荐答案
GetObject("winmgmts:")
返回SWbemServices
对象。根据SWbemServices
对象InstanceOf()
方法的文档:
发件人
SWbemServices.InstancesOf
method
创建根据用户指定的选择条件返回指定类实例的枚举数。
枚举器的概念是对对象集合进行枚举,这将使VBScriptFor Each
statement用于在枚举器上迭代。
一个简单的例子是;
Dim swbemInstances, swbemInstance
Set swbemInstances = GetObject("winmgmts:").InstancesOf("Win32_OperatingSystem")
For Each swbemInstance In swbemInstances
WScript.Echo swbemInstance.Caption
Next
您可以使用ItemIndex
方法直接从枚举器访问实例,如文档所述;
发件人
SWbemObjectSet.ItemIndex
method
将与指定索引关联的SWbemObject
返回到集合中。索引指示元素在集合中的位置。集合编号从零开始。
注意:有趣的一点文档实际上引用了
Win32_OperatingSystem
类作为一个示例,其中您可能只想检索一个实例,并解释了如何使用ItemIndex
来实现此目的。发件人
SWbemObjectSet.ItemIndex
method - Examples
对于每个操作系统安装,只存在Win32_OperatingSystem的一个实例。创建GetObject路径以获取单个实例很麻烦,因此即使只有一个实例可用,脚本通常也会枚举Win32_OperatingSystem。下面的VBScript代码示例显示如何使用ItemIndex方法访问一个Win32_OperatingSystem,而不使用for Each循环。
类似于;
Dim swbemInstance
Set swbemInstance = GetObject("winmgmts:").InstancesOf("Win32_OperatingSystem").ItemIndex(0)
WScript.Echo swbemInstance.Caption
中提到
这篇关于在VBScrip中,如何检索InstancesOf集合的第一个元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!