從 WMI 集合中移除多個專案

如果您嘗試移除集合中的多個專案,您可能會發現某些專案並未移除。 您無法在移除專案時逐一查看集合,因為當您從集合中移除專案時,集合指標會移至下一個專案。 例如,嘗試從集合中移除所有專案會導致移除所有其他專案。 當您使用 SWbemQualifierSet.RemoveSWbemPropertySet.Remove 方法移除專案時,可能會看到此問題。 您可以迴圈查看集合,並將要移除的專案名稱放在陣列中,以避免這個問題。 然後您可以迴圈查看陣列,並刪除陣列中名為 的專案。 SWbemNamedValueSetSWbemPrivilegeSetSWbemRefresher等集合也有一個方法,可刪除重新整理器容器中的所有專案。

下列腳本說明如何從集合中移除數個專案。

Const WBEM_CIMTYPE_STRING = 8    ' Value for string data type
Dim names()
Redim names (0)
set objSWbemService = GetObject("winmgmts:root\default")
set objClass = ObjSWbemService.Get()

Wscript.Echo "Creating class NewClass"
objClass.Path_.Class = "NewClass"
For i = 1 to 5
    objClass.Properties_.Add "Prop" & i, WBEM_CIMTYPE_STRING
Next
objClass.Put_
Getprops()

' Get all the property names in an array
For Each oprop in objClass.properties_
    Redim Preserve names(Ubound(names)+1)
    names(Ubound(names)-1) = oprop.name
Next
Wscript.Echo "Remove first 3 properties using array of names:"

For i = Lbound(names) to Ubound(names)-1
    If (i < 3) Then
       Wscript.Echo "Removing " & names(i)
       objClass.Properties_.Remove names(i)
    End If
Next

objClass.Put_
Wscript.Echo "Result:"
Getprops()

Sub Getprops()
    Wscript.Echo "Number of properties = " _
        & objClass.Properties_.Count
    For Each oprop in objClass.Properties_
        Wscript.Echo oprop.name
    Next
End Sub

您無法移除類別實例或衍生類別中具有繼承屬性的屬性和限定詞。 這類刪除嘗試會引發錯誤,而且不會移除屬性或限定詞;相反地,WMI 會將屬性或限定詞重設為預設值。 如果是具有繼承屬性的衍生類別,WMI 會將繼承的屬性重設為父類別中屬性的預設值。

如需詳細資訊,請參閱 操作類別和實例資訊存取集合,以及 從集合中移除單一專案