Search code examples
vbscriptwmi

Get data from Win32_DiskDrive


I have I problem while I try to get disk data from Win32_DiskDrive via VBScript.

Here is my code:

dim objService, colDiskDrives, objItem 
dim DiskInfo, objClassProperty  

Set objService = GetObject("winmgmts:\\.\Root\CIMV2")
Set colDiskDrives = objService.ExecQuery("SELECT * FROM Win32_DiskDrive")
DiskInfo = "Disk Drive Info" & vbCrLf & vbCrLf   

For Each objItem in colDiskDrives          
  For Each objClassProperty In objItem.Properties_  
    DiskInfo = DiskInfo & objClassProperty.Name &" = " & objClassProperty.value &vbCrLf          
  Next     
  DiskInfo = DiskInfo & "----------------------------------------------" &vbCrLf &vbCrLf 
Next   
WScript.Echo DiskInfo

The value of objClassProperty.value is always null.


Solution

  • It's not that the values are always null, but sometimes they are. Sometimes they are arrays as well, and just as null values, arrays cannot be printed.

    Your code doesn't check for either condition. The following code does, and it checks for objects and Nothing values as well.

    Dim objService, colDiskDrives, objItem 
    Dim DiskInfo, objClassProperty  
    
    Set objService = GetObject("winmgmts:\\.\Root\CIMV2")
    Set colDiskDrives = objService.ExecQuery("SELECT * FROM Win32_DiskDrive")
    
    DiskInfo = "Disk Drive Info" & vbCrLf & vbCrLf   
    
    For Each objItem in colDiskDrives
        For Each objClassProperty In objItem.Properties_
            DiskInfo = DiskInfo & objClassProperty.Name & " = " & StringVal(objClassProperty.value) & vbCrLf
        Next
        DiskInfo = DiskInfo & "----------------------------------------------" & vbCrLf & vbCrLf
    Next
    
    WScript.Echo DiskInfo
    
    Function StringVal(value)
        If IsNull(value) Then
            StringVal = "[null]"
        ElseIf IsObject(value) Then
            If value Is Nothing Then StringVal = "[nothing]" Else StringVal = "[object]"
        ElseIf IsArray(value) Then
            StringVal = "[array]"
        Else
            StringVal = CStr(value)
        End If
    End Function
    

    prints this for me

    Availability = [null]
    BytesPerSector = 512
    Capabilities = [array]
    CapabilityDescriptions = [array]
    Caption = SAMSUNG SSD 830 Series
    CompressionMethod = [null]
     ... more ...
    -------------------------------