2010-11-23 56 views
5

,而不是像這樣的代碼:可能在VBScript中訪問WMI對象的屬性BY NAME?

On Error Resume Next 
strComputer = "." 
Set objWMIService = GetObject("winmgmts:\\" & strComputer & "\root\cimv2") 
Set colItems = objWMIService.ExecQuery("Select * from Win32_IP4RouteTable",,48) 
For Each objItem in colItems 
    Wscript.Echo "Age: " & objItem.Age 
    Wscript.Echo "Caption: " & objItem.Caption 
    Wscript.Echo "Description: " & objItem.Description 
Next 

是否有可能通過名稱來訪問每個屬性,像這些語法之一:

Wscript.Echo "Age: " & objItem("Age") 
Wscript.Echo "Age: " & objItem.Properties("Age") 
Wscript.Echo "Age: " & objItem.Item("Age") 

更妙的是,有沒有什麼辦法可以做到是這樣的:

Dim colItems 
Dim objItem 
Dim aProperty 
Set colItems = objWMIService.ExecQuery("Select * from Win32_IP4RouteTable",,48) 
For Each objItem in colItems 
    For Each aProperty in objItem.Properties 
     Wscript.Echo aProperty.Name & ": " & objItem(aProperty.Name) 
    Next 
Next 

回答

7

您可以通過Properties_屬性訪問命名WMI對象的屬性:

objItem.Properties_("Age") 
objItem.Properties_.Item("Age") 

當然,你也可以列舉Properties_集合:

For Each objItem in colItems 
    For Each prop in objItem.Properties_ 
    If IsArray(prop) Then 
     WScript.Echo prop.Name & ": " & Join(prop, ", ") 
    Else 
     Wscript.Echo prop.Name & ": " & prop 
     ''# -- or -- 
     ''# Wscript.Echo prop.Name & ": " & prop.Value 
    End If 
    Next 
Next