Reputation: 481
I'm writing a VBScript that should identify the OS details. I found an exemple here using InstancesOf Win32_Operating system, but instead of the foreach loop from the sample, I only want to address the first occurence, so I did:
Set SystemSet = GetObject("winmgmts:").InstancesOf ("Win32_OperatingSystem")
Set System = SystemSet.Item(0)
Also tried Set System = SystemSet(0)
, but each time I have a generic failure error message (Echec générique in french).
How can I achieve this so I can then compare the System.Caption
string?
Upvotes: 3
Views: 733
Reputation: 16682
The GetObject("winmgmts:")
returns a SWbemServices
object. According to the documentation for the SWbemServices
object the InstanceOf()
method:
From
SWbemServices.InstancesOf
method
creates an enumerator that returns the instances of a specified class according to the user-specified selection criteria.
The idea of an enumerator is to enumerate over a collection of objects this lends itself to the VBScript For Each
statement for iterating over an enumerator.
A simple example would be;
Dim swbemInstances, swbemInstance
Set swbemInstances = GetObject("winmgmts:").InstancesOf("Win32_OperatingSystem")
For Each swbemInstance In swbemInstances
WScript.Echo swbemInstance.Caption
Next
You can access an instance directly from the enumerator using the ItemIndex
method which as the documentation says;
From
SWbemObjectSet.ItemIndex
method
returns theSWbemObject
associated with the specified index into the collection. The index indicates the position of the element within the collection. Collection numbering starts at zero.
Note: Interesting point the documentation actually cites the
Win32_OperatingSystem
class as an example where you likely want to retrieve only one instance and explains how to useItemIndex
to facilitate it.From
SWbemObjectSet.ItemIndex
method - Examples
Only one instance of Win32_OperatingSystem exists for each operating system installation. Creating the GetObject path to obtain the single instance is awkward so scripts normally enumerate Win32_OperatingSystem even though only one instance is available. The following VBScript code example shows how to use the ItemIndex method to get to the one Win32_OperatingSystem without using a For Each loop.
Something like;
Dim swbemInstance
Set swbemInstance = GetObject("winmgmts:").InstancesOf("Win32_OperatingSystem").ItemIndex(0)
WScript.Echo swbemInstance.Caption
Also mentioned in the comments
Upvotes: 4